使用savefig()将图形导出为pdf会扰乱matplotlib中的轴背景

2024-04-20 08:21:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试更改绘图中的轴背景,其中几个imshow()调用通过extent参数在不同位置呈现图像。

当我使用savefig()保存图形的pdf时,如果轴显示多个图像,则会丢失背景色。请注意,在导出同一图形的png时不会发生这种情况。

下面是一个最小的脚本来说明这个问题:

import matplotlib.pyplot as plt
from numpy.random import rand

fig, ax = plt.subplots(nrows=3, ncols=1, sharex=True)

ax[0].imshow(rand(15,15), extent=[0, 2, 15, 0], \
            cmap=plt.cm.gray, aspect='auto', interpolation='Nearest')
ax[0].set_axis_bgcolor('k')

ax[1].imshow(rand(15,15), extent=[0, 2, 15, 0], \
            cmap=plt.cm.gray, aspect='auto', interpolation='Nearest')
ax[1].imshow(rand(15,15), extent=[4, 6, 15, 0], \
            cmap=plt.cm.gray, aspect='auto', interpolation='Nearest')
ax[1].set_axis_bgcolor('k')

ax[2].imshow(rand(15,15), extent=[0, 2, 15, 0], \
            cmap=plt.cm.gray, aspect='auto', interpolation='Nearest')
ax[2].imshow(rand(15,15), extent=[4, 6, 15, 0], \
            cmap=plt.cm.gray, aspect='auto', interpolation='Nearest')
ax[2].imshow(rand(15,15), extent=[8, 10, 15, 0], \
            cmap=plt.cm.gray, aspect='auto', interpolation='Nearest')
ax[2].set_axis_bgcolor('k')

ax[-1].set_xlim([0, 12])
fig.savefig('test.pdf', format='PDF')
fig.savefig('test.png', format='PNG')

这是脚本的pdf输出(eps输出相同):

test.pdf

这是脚本的预期输出(保存为png):

test.png

我遇到matplotlib错误了吗,还是缺少了修复pdf输出的命令?

编辑:我用默认的matplotlibrc重新绘制了这些图形。


Tags: autopdfcmpltaxextentcmapset
2条回答

看看你的matplotlibrc。有一部分以savefig开头的选项定义了保存的图形的外观。即使是默认的matplotlibrc也有这个部分。

还有一个类似的问题:matplotlib savefig() plots different from show()

这最终成为一个matplotlib错误。

当在同一轴上渲染多个图像时,将创建一个合成图像,该图像在渲染为pdf时没有透明背景,因此轴的背景色不会显示出来。

这作为an issue I opened in the matplotlib's GitHub repo的一部分得到了解决。

相关问题 更多 >