如何使用 Matplotlib 设置图形背景颜色的不透明度
- 2025-04-16 08:58:00
- admin 原创
- 18
问题描述:
我一直在玩 Matplotlib,但我不知道如何改变图形的背景颜色,或者如何使背景完全透明。
解决方案 1:
如果您只是希望图形和轴的整个背景都是透明的,您只需transparent=True
在保存图形时指定即可fig.savefig
。
例如:
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()
解决方案 2:
另一种方法是设置适当的全局变量 rcParams
并简单指定颜色。这是一个 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()
上面的代码产生以下输出:
并plt.savefig("temp.png")
产生以下输出:
如果您想让某些东西完全透明,只需将相应颜色的 alpha 值设置为 0。对于plt.savefig
,还有一个“懒惰”选项,通过将 rc 参数设置savefig.transparent
为True
,将所有面部颜色的 alpha 设置为 0%。
请注意,更改rcParams
具有全局影响,因此请记住所有绘图都会受到这些更改的影响。但是,如果您有多个绘图,或者您想在无法更改源代码的情况下更改绘图的外观,此解决方案将非常有用。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD