Black background behind a figure's labels and ticks after saving figure, but not in Interactive view
Asked Answered
A

2

11

I have a strange problem where if I save a figure, its labels and ticks will have a black background, see this example:

plt.savefig("asdsadsad.png")

enter image description here

I'm not even including any code here because this happens on the simplest plotting, even with code that I made earlier with a different computer that never had this problem. I'm using VS Code with Jupyter functionality and the figures look normal in the Python Interactive view, but have the black border when saved.

Any ideas what could cause this strange problem?

Aquinas answered 11/12, 2018 at 15:51 Comment(2)
The "black" background might just be a transparent background. Typically it's saved with a transparent background, and your viewer might display that as black.Flores
edit: Photoshop and another device also shows it as black so I think it really is blackAquinas
F
17

plt.savefig will not use the same settings that you plotted with. That's why the saved image might look different from what you have plotted in Python. To define the background color of your figure, you need to define the facecolor parameter when you call savefig.

plt.savefig('asdsadsad.png', facecolor='w')

Your default facecolor may be set to black in your rcParams

Flores answered 11/12, 2018 at 16:29 Comment(1)
Thank you very much, adding facecolor="w" fixed this and good to know that plt.savefig overwrites the plotting settings. The black background's funny though because I was not aware of the facecolor parameter and certainly had not used it in the code (just checked again, no rc-parameters either) so there shouldn't have been anything to suggest using a black background. But this fixed it so thanks again!Aquinas
C
1

I think I got the same issue, besides having facecolor and edgecolor set to white ('w'). For some strange reason the problems occured only with PNG image format and shifting to JPG solved everything.

Cooking answered 14/9, 2022 at 16:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.