【发布时间】:2011-06-02 15:54:38
【问题描述】:
我一直在玩 Matplotlib,但我不知道如何更改图形的背景颜色,或者如何使背景完全透明。
【问题讨论】:
-
facecolor/set_facecolor?
-
但是如何使用 set_facecolor?
标签: python matplotlib alpha
我一直在玩 Matplotlib,但我不知道如何更改图形的背景颜色,或者如何使背景完全透明。
【问题讨论】:
标签: python matplotlib alpha
如果您只希望图形和轴的整个背景都是透明的,您可以在使用fig.savefig 保存图形时简单地指定transparent=True。
例如:
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png', transparent=True)
如果您想要更细粒度的控制,您可以简单地为图形和轴背景补丁设置 facecolor 和/或 alpha 值。 (要使补丁完全透明,我们可以将 alpha 设置为 0,或者将 facecolor 设置为 'none'(作为字符串,而不是对象 None!))
例如:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.patch.set_facecolor('blue')
fig.patch.set_alpha(0.7)
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.patch.set_facecolor('red')
ax.patch.set_alpha(0.5)
# If we don't specify the edgecolor and facecolor for the figure when
# saving with savefig, it will override the value we set earlier!
fig.savefig('temp.png', facecolor=fig.get_facecolor(), edgecolor='none')
plt.show()
【讨论】:
facecolor 设置为'none' 对我不起作用;将alpha 设置为0.0 做了。
"None" 确实有效。将其设置为 None 不起作用。
savefig怎么办?我正在尝试写入缓冲区。
rcParams 应该可以解决问题,请参阅下面的my answer
另一种方法是设置适当的全局 rcParams 并简单地指定colors。这是一个 MWE(我使用 RGBA 颜色格式来指定 alpha/opacity):
import matplotlib.pyplot as plt
plt.rcParams.update({
"figure.facecolor": (1.0, 0.0, 0.0, 0.3), # red with alpha = 30%
"axes.facecolor": (0.0, 1.0, 0.0, 0.5), # green with alpha = 50%
"savefig.facecolor": (0.0, 0.0, 1.0, 0.2), # blue with alpha = 20%
})
plt.plot(range(10))
plt.savefig("temp.png")
plt.show()
figure.facecolor 是主背景色,axes.facecolor 是实际绘图的背景色。无论出于何种原因,plt.savefig 使用savefig.facecolor 作为主要背景颜色而不是figure.facecolor,因此请务必相应地更改此参数。
以上代码中的plt.show() 会产生以下输出:
plt.savefig("temp.png") 会产生以下输出:
如果你想让某些东西完全透明,只需将相应颜色的 alpha 值设置为 0。对于plt.savefig,还有一个“惰性”选项,通过将 rc 参数 savefig.transparent 设置为 True ,这会将所有 facecolors 的 alpha 设置为 0%。
请注意,更改 rcParams 具有全局影响,因此请记住,您的所有绘图都会受到这些更改的影响。但是,如果您有多个绘图,或者如果您想更改绘图的外观而您无法更改源代码,则此解决方案可能非常有用。
【讨论】: