matplotlib中3D多边形图基线倾斜
我正在尝试创建一个自己的3D多边形图,参考的是Matplotlib网站上的示例:
http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#polygon-plots
我的版本在这里:
http://hastebin.com/laqekeceru.py
示例数据:
http://hastebin.com/vocagogihu.coffee
从两个不同的视角输出的图像在这里:
从图像中可以看到,图表的基线逐渐向上倾斜。
我尝试了教程中的版本,效果很好,但数据明显少很多。
这是matplotlib的一个bug吗?还是我的代码有问题?
我使用的是:
- Windows 7
- Python 2.6
- numpy==1.8.0
- matplotlib==1.3.1(最新版本)
提前谢谢大家。
1 个回答
2
这段内容主要是关于多边形的,不涉及3D的具体内容。
你的PolyCollection其实就是一堆点,这些点连起来形成一个封闭的多边形。这里提到的“爬行”的基线,实际上就是多边形的一条边,它是从每个多边形的最后一个点到第一个点之间的隐形线。
为了更好地说明这一点,请看:
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
# some sample data
data = [(0,.5), (1,.7), (2,.3), (3,.6), (4,.2)]
fig = plt.figure()
ax = fig.add_subplot(111)
# draw the polygon
p = PolyCollection([data], facecolor=(1,0,0,.5), edgecolor='none')
ax.add_collection(p)
# draw the line
d = np.array(data)
ax.plot(*zip(*data), color='k', linewidth=2)
这个简单的例子显示了:
要解决这个问题,你需要在多边形的两端添加零:
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
# some sample data
data = [(0,.5), (1,.7), (2,.3), (3,.6), (4,.2)]
fig = plt.figure()
ax = fig.add_subplot(111)
# draw the polygon
# pad the data:
data.insert(0, (data[0][0],0))
data.append((data[-1][0], 0))
p = PolyCollection([data], facecolor=(1,0,0,.5), edgecolor='none')
ax.add_collection(p)
# draw the line, note that the padded points are not drawn
d = np.array(data)
ax.plot(*zip(*data[1:-1]), color='k', linewidth=2)
这样斜线就消失了:
如果你想在多边形的边缘有曲线效果,你需要单独绘制它(因为多边形的边缘是你不想显示的东西)。