繁体   English   中英

Matplotlib 绘图在另存为 .pdf 时失去透明度

[英]Matplotlib plots lose transparency when saving as .pdf

我看到了与此完全相同的问题: Matplotlib 绘图在另存为 .ps/.eps 时失去透明度,但我试图输出为 PDF 而不是 ps/eps。

上一个问题的答案指出eps不支持透明度并建议光栅化或另存为PDF。 当我另存为 png 时,我确实得到了正确的输出,所以似乎 matplotlib 正在正确处理透明度,但后端失败了。 显然 PDF确实支持透明度,所以我尝试使用的格式不是问题。

我在 OS X (Yosemite) 中运行,使用默认的 MacOSX matplotlib 后端并使用 matplotlib 1.4.1。 是否有任何原因导致此设置无法生成透明的 PDF 输出?

这曾经在过去工作(使用 OS X Mavericks 和早期版本的 matplotlib),但我不确定究竟是什么变化导致了这个问题。

如果运行以下代码,问题会出现在 with_hatch.pdf 中,但不会出现在任何其他输出文件中。

#! /usr/bin/env python
import matplotlib.pyplot as plt

fig = plt.figure( figsize=(6, 6), dpi=100, facecolor='white' )
ax = fig.add_axes( [0.15, 0.1, 0.8, 0.85] )

bin_edges = [0.0, 0.5, 0.5, 1.0, 1.0, 1.5, 1.5, 2.0, 2.0, 2.5, 2.5, 3.0, 3.0, 3.5, 3.5, 4.0, 4.0, 4.5, 4.5, 5.0, 5.0, 5.5, 5.5, 6.0, 6.0, 7.0, 7.0, 8.0]
y_low     = [0.9581631739289882, 0.9581631739289882, 0.8966054746563691, 0.8966054746563691, 0.8369962202270926, 0.8369962202270926, 0.7824880045351325, 0.7824880045351325, 0.7231695683685057, 0.7231695683685057, 0.6673767757896321, 0.6673767757896321, 0.6083447707111752, 0.6083447707111752, 0.5602384968623321, 0.5602384968623321, 0.5109567893600544, 0.5109567893600544, 0.4707872827805316, 0.4707872827805316, 0.4304527769718274, 0.4304527769718274, 0.39024135798617826, 0.39024135798617826, 0.3593458738615755, 0.3593458738615755, 0.3275704585658484, 0.3275704585658484]
y_high    = [0.9762065896798683, 0.9762065896798683, 0.9227253843496172, 0.9227253843496172, 0.8738222849514, 0.8738222849514, 0.8299500683866315, 0.8299500683866315, 0.7810616940586165, 0.7810616940586165, 0.7357506442258693, 0.7357506442258693, 0.6852756294051707, 0.6852756294051707, 0.6441575476130643, 0.6441575476130643, 0.5987788803224889, 0.5987788803224889, 0.5630257208701298, 0.5630257208701298, 0.5274860424153797, 0.5274860424153797, 0.4915335923551736, 0.4915335923551736, 0.46502435263727837, 0.46502435263727837, 0.43196895235913746, 0.43196895235913746]

ax.fill_between( bin_edges, y_low, y_high, facecolor='green', edgecolor='white', alpha=0.4 )

plt.savefig( 'without_hatch.pdf' )
plt.savefig( 'without_hatch.png' )

ax.fill_between( bin_edges, y_low, y_high, facecolor='green', edgecolor='white', hatch='xxxx', alpha=0.4 )

plt.savefig( 'with_hatch.pdf' )
plt.savefig( 'with_hatch.png' )

现在提交到 matplotlib 错误跟踪器: https : //github.com/matplotlib/matplotlib/issues/3841

解决问题?

1) 您也许可以导出为支持 alpha 的 PNG,然后将其包装在 PDF 中,但您仍然会丢失所有线条艺术而转而使用光栅化图像……可能不是您想要的。

2) 如果不同的图层具有不同的 alpha 设置,您可以将各个图层渲染为单独的 PDF,然后导入它们并将它们包装在 PDF 原生 alpha 中。 这需要一些适度的PDF-fu,但应该是可行的。 另一方面,如果 alpha 值在给定区域内发生变化,这将不起作用。

在设置要具有透明度的轴之后和保存图形之前添加此行:

ax.set_rasterized(True)
plt.savefig("fig.pdf")

这适用于我在 MacOS Big Sur 上的 Python 3。

可以在此处找到此方法的文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM