Matplotlib图facecolor(背景颜色)

时间:2011-01-26 11:25:11

标签: python matplotlib

有人可以解释为什么设置图的面部颜色时下面的代码不起作用吗?

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.

当我使用fig1.set_figheight(11) fig1.set_figwidth(8.5)指定图形的高度和宽度时,命令plt.savefig("trial_fig.png")会选择这些图形。但是,未拾取面部颜色设置。为什么呢?

感谢您的帮助。

4 个答案:

答案 0 :(得分:88)

这是因为savefig会覆盖图形背景的facecolor。

(这是故意的,实际上......假设您可能想要使用facecolor kwarg来控制已保存人物的背景颜色savefig。这是一个令人困惑和不一致的事情但是默认!)

最简单的解决方法就是fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none')(我在这里指定了边缘颜色,因为实际图形的默认边缘颜色为白色,这将为您提供围绕保存图形的白色边框)

希望有所帮助!

答案 1 :(得分:22)

我必须使用transparent关键字来获取我用初始

选择的颜色
fig=figure(facecolor='black')
像这样:

savefig('figname.png', facecolor=fig.get_facecolor(), transparent=True)

答案 2 :(得分:19)

savefigfacecolor提供了自己的参数。 我认为比接受的答案更简单的方法是将它们全局设置为,而不是每次都设置facecolor=fig.get_facecolor()

plt.rcParams['axes.facecolor']='red'
plt.rcParams['savefig.facecolor']='red'

答案 3 :(得分:0)

如果要更改背景颜色,请尝试以下操作:

plt.rcParams['figure.facecolor'] = 'white'