Python Matplotlib 图 facecolor(背景色)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4804005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matplotlib figure facecolor (background color)
提问by Curious2learn
Can someone please explain why the code below does not work when setting the facecolor of the figure?
有人可以解释为什么在设置图形的 facecolor 时下面的代码不起作用吗?
import matplotlib.pyplot as plt
# create figure instance
fig1 = plt.figure(1)
fig1.set_figheight(11)
fig1.set_figwidth(8.5)
rect = fig1.patch
rect.set_facecolor('red') # works with plt.show().
# Does not work with plt.savefig("trial_fig.png")
ax = fig1.add_subplot(1,1,1)
x = 1, 2, 3
y = 1, 4, 9
ax.plot(x, y)
# plt.show() # Will show red face color set above using rect.set_facecolor('red')
plt.savefig("trial_fig.png") # The saved trial_fig.png DOES NOT have the red facecolor.
# plt.savefig("trial_fig.png", facecolor='red') # Here the facecolor is red.
When I specify the height and width of the figure using fig1.set_figheight(11)fig1.set_figwidth(8.5)these are picked up by the command plt.savefig("trial_fig.png"). However, the facecolor setting is not picked up. Why?
当我使用fig1.set_figheight(11)fig1.set_figwidth(8.5)这些指定图形的高度和宽度时,命令会拾取它们plt.savefig("trial_fig.png")。但是,不会选取 facecolor 设置。为什么?
Thanks for your help.
谢谢你的帮助。
采纳答案by Joe Kington
It's because savefigoverrides the facecolor for the background of the figure.
这是因为savefig覆盖了图形背景的 facecolor。
(This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the facecolorkwarg to savefig. It's a confusing and inconsistent default, though!)
(这是故意的,实际上......假设你可能想用facecolorkwarg to控制保存图形的背景颜色。不过,savefig这是一个令人困惑和不一致的默认值!)
The easiest workaround is just to do fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none')(I'm specifying the edgecolor here because the default edgecolor for the actual figure is white, which will give you a white border around the saved figure)
最简单的解决方法就是这样做fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none')(我在这里指定边缘颜色,因为实际图形的默认边缘颜色是白色,这将为您在保存的图形周围提供白色边框)
Hope that helps!
希望有帮助!
回答by Labibah
I had to use the transparent keyword to get the color I chose with my initial
我不得不使用 transparent 关键字来获得我用我的初始选择的颜色
fig=figure(facecolor='black')
like this:
像这样:
savefig('figname.png', facecolor=fig.get_facecolor(), transparent=True)
回答by tozCSS
savefighas its own parameter for facecolor.
I think an even easier way than the accepted answer is to set them globally just once, instead of putting facecolor=fig.get_facecolor()every time:
savefig有自己的参数facecolor。我认为比接受的答案更简单的方法是将它们全局设置一次,而不是facecolor=fig.get_facecolor()每次都设置:
plt.rcParams['axes.facecolor']='red'
plt.rcParams['savefig.facecolor']='red'

