如何保存具有透明外部背景但有彩色子图形的matplotlib图形



我想保存一个具有透明背景的图形,其中刻度线和轴标签是透明的,但子图形面是彩色的。我可以使用savefigtransparent=True来实现透明背景,后者通过为子画面中的每个轴设置facecolor='red'来实现,但无法同时实现这两种功能。

我包含了一个MWE,其中plt.show((将创建所需的面颜色,而保存的透明图形显示在注释幻灯片上。谢谢你的帮助!

import os.path as op
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(10)
y0 = np.random.rand(50)
y1 = np.random.rand(50)
x  = range(len(y1))
fig, (axe0, axe1) = plt.subplots(nrows=2, sharex=True)
axe0.scatter(x, y0, c='k')
axe0.set_facecolor('red')
axe1.scatter(x, y1, c='k')
axe1.set_facecolor('blue')
dst = op.join(op.expanduser('~'), 'Desktop', 'Temp.png')
fig.savefig(dst, transparent=True, format='png')
plt.show()

正确的彩色子批次

幻灯片上透明

不要设置transparent true,而是使用设置opacity=0

fig.patch.set_alpha(0.0)

我修改了你的代码如下:

fig, (axe0, axe1) = plt.subplots(nrows=2, sharex=True)
axe0.scatter(x, y0, c='k')
axe0.set_facecolor('red')
axe1.scatter(x, y1, c='k')
axe1.set_facecolor('blue')
dst = op.join(op.expanduser('~'), 'Desktop', 'Temp.png')
fig.patch.set_alpha(0.0)
fig.savefig(dst, format='png')
plt.show()

最新更新