python - Matplotlib 中 Poly3DCollection 的光栅化

标签 python matplotlib plot

当尝试在 Matplotlib 中强制对 Poly3DCollection 对象进行栅格化时,我收到以下错误消息(并且我可以确认没有应用栅格化):

/usr/lib/python3/dist-packages/matplotlib/artist.py:788: UserWarning: Rasterization of '<mpl_toolkits.mplot3d.art3d.Poly3DCollection object at 0x2b49e8faeba8>' will be ignored
  warnings.warn("Rasterization of '%s' will be ignored" % self)

可以栅格化整个图形,但只栅格化某些对象显然更可取,同时将轴、标签、键、文本等项目保留为矢量图形。

我尝试在我的代码中使用以下语法:

  • ax.add_collection3d(Poly3DCollection(polygons, rasterized=True), zs='z')
  • c = Poly3DCollection(polygons) 然后是 c.set_rasterized(True)

根据 this post ,可以光栅化 PolyCollection(没有 3D 位)对象。

有什么建议吗?

这是一个 MWE:

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.set_xlim([0, 4])
ax.set_ylim([0, 4])
ax.set_zlim([0, 4])

polygons = [[(3, 1, 1), (1, 3, 1), (1, 1, 3)]]

ax.add_collection3d(Poly3DCollection(polygons, facecolors='r', rasterized=True), zs='z')

plt.show()

最佳答案

首先请注意,光栅化仅适用于导出矢量图形,如 pdf。我假设这就是你在这里谈论的内容,所以我想你会在最后调用类似 plt.savefig("some.pdf") 的东西。

我认为有人只是忘记允许对 3D 对象进行光栅化。

解决方法是进入 matplotlib 源代码,找到

python\lib\site-packages\mpl_toolkits\mplot3d\art3d.py

在导入部分添加

from matplotlib.artist import allow_rasterization

然后在 Poly3DCollection 中找到它的 draw 方法(在我的例子中是在第 709 行)并添加 @allow_rasterization。它应该看起来像

@allow_rasterization
def draw(self, renderer):
    return Collection.draw(self, renderer)

如果运行上面的代码,并将其保存为 pdf,则三角形被光栅化。 pdf截图:

enter image description here

关于python - Matplotlib 中 Poly3DCollection 的光栅化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47818231/

相关文章:

python - 仅查找列表中的唯一坐标

python - numpy.linalg.norm 给出奇怪的结果

python - 在 kmeans 中绘制二维簇

python - 我可以将字典的值分成多列并且仍然能够绘制它们吗?

python - vim如何定义一个句子。我怎样才能尽快结束一个句子

python - Python 中的可视化和聚类

python-2.7 - Pyplot 旋转标签偏移一

python -\frac{}{} 不会为我工作 w/pylab

python - 如何对seaborn relplot的轴使用对数刻度?

r - 如何在脚本模式下只显示 `plot(model)` 的前两个图?