Matplotlib 图 facecolor(背景色) [英] Matplotlib figure facecolor (background color)

查看:67
本文介绍了Matplotlib 图 facecolor(背景色)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下为什么下面的代码在设置图形的facecolor时不起作用?

Can someone please explain why the code below does not work when setting the facecolor of the figure?

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").但是,不会选择 facecolor 设置.为什么?

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?

感谢您的帮助.

推荐答案

这是因为 savefig 覆盖了图形背景的 facecolor.

It's because savefig overrides the facecolor for the background of the figure.

(这是故意的,实际上......假设你可能想用 facecolor kwarg to savefig 控制保存图形的背景颜色.不过,这是一个令人困惑且不一致的默认值!)

(This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the facecolor kwarg to savefig. It's a confusing and inconsistent default, though!)

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

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)

希望有帮助!

这篇关于Matplotlib 图 facecolor(背景色)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆