如何设置pcolor savefig颜色条透明度

问题描述 投票:0回答:1

我正在尝试导出带有颜色条的 pcolor 图形。 颜色条的 cmap 具有透明颜色。 导出的图形在轴中具有透明颜色,但在颜色栏中没有。我该如何解决这个问题?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

x = np.random.random((10, 10))
colors = [(0,0,0,0), (0,0,0,1)]
cm = LinearSegmentedColormap.from_list('custom', colors, N=256, gamma=0)
plt.pcolor(x,cmap=cm)
plt.colorbar()
plt.savefig('figure.pdf',transparent=True)

我将图像放在灰色背景下进行检查。可以看到,坐标区中的 cmap 是透明的,而颜色栏中的 cmap 不是透明的。

I put the image against a grey background to check. As can be seen, the cmap in the axes is transparent while the one in the colorbar is not

python matplotlib transparency colorbar
1个回答
0
投票

虽然颜色条位于轴内,但它有一个与之关联的附加背景块。默认情况下为白色,当在

transparent=True
内部使用
savefig
时,不会考虑该值。

因此,解决方案是手动删除该补丁的面部颜色,

cb.patch.set_facecolor("none")

一个完整的示例,无需实际保存图形即可显示这一点

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

x = np.random.random((10, 10))
colors = [(1,1,1,0), (0,0,0,1)]
cm = LinearSegmentedColormap.from_list('custom', colors, N=256, gamma=0)

fig, ax = plt.subplots(facecolor="grey")

im = ax.pcolor(x,cmap=cm)
cb = fig.colorbar(im, drawedges=False)

ax.set_facecolor("none")
cb.patch.set_facecolor("none")

plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.