Matplotlib 图形面色(背景颜色)

140 投票
4 回答
243435 浏览
提问于 2025-04-16 10:39

有人能解释一下为什么下面的代码在设置图形的背景颜色时不起作用吗?

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 个回答

45

我需要使用透明这个关键词,才能得到我最开始选择的颜色。

fig=figure(facecolor='black')

像这样:

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

savefig 这个函数有一个专门用来设置背景颜色的参数叫 facecolor。我觉得有个更简单的方法,就是只需要设置一次全局的背景颜色,而不是每次都写 facecolor=fig.get_facecolor()

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

这是因为 savefig 会覆盖图像的背景颜色。

(其实这是故意这样设计的……因为假设你可能想用 savefigfacecolor 参数来控制保存图像的背景颜色。不过这个默认设置确实让人感到困惑和不一致!)

最简单的解决办法就是这样做:fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none') (我在这里指定了边框颜色,因为实际图像的默认边框颜色是白色,这样保存的图像周围就会有一个白色的边框)

撰写回答