Skip to main content
 首页 » 编程设计

python之matplotlib 生成的草率 SVG 导致图形中数据点绘图的剪裁不佳

2024年11月01日13exmyth

我用 matplotlib 创建的图形渲染时不要正确地将点剪裁到图形轴,而是绘制额外的点,即使这些图形在某些查看器中看起来不错。

例如(在 an example from the documentation 之后)使用

import matplotlib 
matplotlib.use('SVG') 
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.patches as patches 
 
fig = plt.figure() 
ax = fig.add_subplot(111) 
x, y = 12*np.random.rand(2, 1000) 
ax.set(xlim=[2,10]) 
ax.plot(x, y, 'go')  # plot some data in data coordinates 
 
circ = patches.Circle((0.5, 0.5), 0.25, transform=ax.transAxes, 
                      facecolor='yellow', alpha=0.5) 
ax.add_patch(circ) 
 
plt.savefig() 

我似乎,例如在 OS X 预览中查看时,得到

但是当我在其他编辑器中查看时,例如iDraw我弄得一团糟(奇怪的是,边缘点的正确裁剪、轴外点的裁剪失败以及在与轴或数据范围都不对应的点处裁剪 Canvas 的组合) :

我对 SVG 没有经验,但我问过的人告诉我

I looked at the SVG file and didn't like what I saw. Characters are flattened, and definition sections are scattered throughout the file instead of being at the top; some defs are inside graphics constructs. There's a lot of cruft. It turns out the definition of the clip-path is at the very end of the svg file -- after all the uses ...

我怎样才能得到 matplotlob生成没有这些问题的 SVG?我知道我可以编辑 SVG,但我不知道如何编辑,这样做违背了目的,我希望没有必要在我的工作流程中添加“手动”步骤。


我有兴趣了解 matplotlib 生成的草率 SVG 的原因是什么是:它是否可以通过稍微不同的编码来避免(虽然不是,很明显,通过简单地检查每个数据点是否在范围内),或者它是否是 matplotlib 中的错误(或者这是否只是 SVG 标准中的歧义问题)。目标是获得 matplotlob生成没有错误的 SVG。

请您参考如下方法:

这可能与已知问题有关,并且也出现在 pdf 中 (matplotlib data accessible outside of xlim range)

查看问题 #2488和 #2423 (后者包括对 pdf 的建议修复)。它是 1.4 的里程碑。