填充轮廓图中的轮廓栅格化 [英] Rasterization of contours in filled contour plot
问题描述
我有一个填充的轮廓图,我希望将其另存为.svg或.pdf文件.下面是一个简化的例子.我想栅格化等高线图本身(彩色部分!),同时将其他所有内容(所有轴、标签等)保留为矢量图形.
I have a filled contour plot, which I wish to save as an .svg or .pdf file. The following is a simplified example. I want to rasterize the contour plot itself (the colorful part!), while keeping everything else (all axes, labels etc.) as vector graphics.
import numpy as np
import matplotlib.pylab as plt
x = np.linspace(0, 2*np.pi, 100)
y = np.linspace(0, 2*np.pi, 100)
xi, yi = np.meshgrid(x, y)
zi = np.cos(xi)**2 + np.sin(yi)**2
plt.figure()
plt.contourf(xi, yi, zi, rasterized=True)
plt.savefig('fig.svg', dpi=100)
但是,当我检查fig.svg或在Inkscape中打开它进行编辑时(我可以将填充的轮廓取消分组为矢量形状),显然光栅化没有用!
However, when I inspect fig.svg or open it for editing in Inkscape (I am able to ungroup the filled contour into vector shapes) it is clear that rasterization has not worked!
对于这样一个简单的图而言,这很好,但是如果我的图具有更高的轮廓级别(如下所示),则矢量图像将需要许多曲线,并且文件大小会更大.
That's fine for such a simple plot, but if my plot has a higher number of contour levels (below) the vector image will need many many curves and the filesize would be much bigger.
plt.close()
plt.figure()
plt.contourf(xi, yi, zi, 100, rasterized=True)
plt.savefig('fig.svg', dpi=100)
有人可以提出解决方案并解释为什么这个 rasterized=True
标志没有完成我的要求吗?
Can someone please suggest a solution and explain why this rasterized=True
flag has not done what I require?
推荐答案
我刚刚发现这是 使用 rasterized=True
作为 contour
或 contourf
的参数应该显示一个
Using rasterized=True
as argument to contour
or contourf
should show a
UserWarning: The following kwargs were not used by contour: 'rasterized'
要栅格化等高线图,您需要栅格化其各个部分,即
In order to rasterize a contour plot, you need to rasterize its individual parts, i.e.
cs = plt.contour(...)
for c in cs.collections:
c.set_rasterized(True)
问题的示例因此看起来像
The example from the question would hence look like
import numpy as np
import matplotlib.pylab as plt
x = np.linspace(0, 2*np.pi, 100)
y = np.linspace(0, 2*np.pi, 100)
xi, yi = np.meshgrid(x, y)
zi = np.cos(xi)**2 + np.sin(yi)**2
plt.figure()
cs = plt.contourf(xi, yi, zi)
for c in cs.collections:
c.set_rasterized(True)
plt.savefig('fig.svg', dpi=100)
这篇关于填充轮廓图中的轮廓栅格化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!