使用PolyCollection在matplotlib mplot3d图中出现奇数线伪影

时间:2013-10-21 10:27:30

标签: python matplotlib mplot3d

我正在使用mplot3d示例,该示例使用PolyCollection堆叠XY图,http://matplotlib.org/examples/mplot3d/polys3d_demo.html

然而,我在剧情中看到一些奇怪的线条文物。

  • 如何删除从可见区域消失的水平线?
  • 是否有更好的方法沿深度方向堆叠XY图?

以下脚本生成此图

Odd lines in mplot3d plot

from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
from matplotlib.colors import colorConverter
import matplotlib.pyplot as plt
import numpy as np

zs = []
fig = plt.figure()
ax = fig.gca(projection='3d')
verts = []

# XY data (i.e. "normal line plots")
count = 4
for i in range(count):
    xs, ys = [800.0, 900.0, 1000.0, 1100.],  [0., 1., 1., 0.]
    verts.append(list(zip(xs, ys)))

# Z position (i.e. depth at which the XY plot is drawn)
zs = [0,1,2,3]

colours = plt.cm.Blues(np.linspace(0.2, 0.8, len(zs)))
poly = PolyCollection(verts, facecolors = colours )
ax.add_collection3d(poly, zs=zs, zdir='y')

ax.set_xlabel('X')
ax.set_xlim3d(800,1150)
ax.set_ylabel('Y')
ax.set_ylim3d(0, 4)
ax.set_zlabel('Z')
ax.set_zlim3d(0, 1)
plt.show()

1 个答案:

答案 0 :(得分:1)

如果仍然存在此问题,请尝试手动更改相应的Path对象。您应该将最后一个顶点的代码修改为STOP(代码0):

from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
from matplotlib.colors import colorConverter
import matplotlib.pyplot as plt
import numpy as np

zs = []
fig = plt.figure()
ax = fig.gca(projection='3d')
verts = []

# XY data (i.e. "normal line plots")
count = 4
for i in range(count):
    xs, ys = [800.0, 900.0, 1000.0, 1100.],  [0., 1., 1., 0.]
    verts.append(list(zip(xs, ys)))

# Z position (i.e. depth at which the XY plot is drawn)
zs = [0,1,2,3]

colours = plt.cm.Blues(np.linspace(0.2, 0.8, len(zs)))
poly = PolyCollection(verts, facecolors = colours )

for path in poly.get_paths() :  # There is the fix :
  path.codes[-1] = 0        # we have to manually switch the last point in a path to STOP (code = 0)

ax.add_collection3d(poly, zs=zs, zdir='y')

ax.set_xlabel('X')
ax.set_xlim3d(800,1150)
ax.set_ylabel('Y')
ax.set_ylim3d(0, 4)
ax.set_zlabel('Z')
ax.set_zlim3d(0, 1)
plt.show()

......结果如下: enter image description here