Matplotlib图的透明背景

5

我正在使用Matplotlib和Seaborn进行绘图。我想要的是具有透明背景而不是黑色背景的图表。我的代码如下:

plt.style.use("dark_background")
plt.figure(figsize=(15,8))
sns.swarmplot(x='type',y='value', data=df, size=3.5, color='r', alpha=0.4)
sns.boxplot(x='type',y='value',data=df)

故事情节是 enter image description here

现在有没有一种样式或技术,可以使我的绘图背景颜色与单元格的背景颜色相同,即我的绘图背景为透明色。

谢谢


这个回答解决了你的问题吗?如何使用Matplotlib设置图形背景颜色的不透明度 - JE_Muc
这是用于保存图形的。我希望它在单元格中是透明的。 - Ahmad Anis
不是唯一的解决方案。你看过第二个答案了吗?这将全局设置背景,对于你的情况似乎是一个不错的解决方案,因为你正在进行“一些绘图目的”的编写。 - JE_Muc
1个回答

10
如果你想让整个图像和坐标轴的背景都是透明的,你可以在使用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()

如果OP想将他们的图形放在一个预先存在的暗色图像上,他们可以简单地降低图形/轴的不透明度,以便浅色图形元素突出显示在预先存在图像的略暗部分上。 - gboffi
好答案,我特别欣赏有关 fig.savefig 的评论。 - gboffi
这只是这个答案的复制粘贴:https://stackoverflow.com/questions/4581504/how-to-set-opacity-of-background-colour-of-graph-with-matplotlib - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接