如何使用Matplotlib设置图形背景颜色的不透明度

时间:2011-01-03 01:26:23

标签: python matplotlib alpha

我一直在玩Matplotlib,我无法弄清楚如何更改图表的背景颜色,或者如何使背景完全透明。

2 个答案:

答案 0 :(得分:93)

如果您只想让图形和轴的整个背景都透明,则可以在使用transparent=True保存图形时指定fig.savefig

e.g:

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!)

e.g:

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()

alt text

答案 1 :(得分:12)

另一种方法是设置相应的全局 rcParams并只需指定colors。这是MWE(我使用RGBA颜色格式指定Alpha /不透明度):

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()产生以下输出:

enter image description here

plt.savefig("temp.png")产生以下输出:

enter image description here

如果要使某些东西完全透明,只需将相应颜色的alpha值设置为0。对于plt.savefig,还可以通过设置rc参数savefig.transparent来选择“懒惰”选项到True,将所有面部颜色的Alpha设置为0%。

请注意,更改rcParams具有全局效果,因此请记住,所有更改都会受到这些更改的影响。但是,如果您有多个图,或者想要在无法更改源代码的情况下更改图的外观,则此解决方案可能非常有用。