如何在matplotlib.collections中使用PolyCollection?

时间:2017-08-14 16:26:09

标签: python matplotlib

我不太明白这句话的功能:

return [(xlist[0], 0.)] + list(zip(xlist, ylist)) + [(xlist[-1], 0.)]

[(xlist[0], 0.)]对我来说似乎很奇怪。 为什么我必须在列表的开头和结尾添加y = 0的顶点?这让我很困惑。 list(zip(xlist,ylist))对我来说似乎已经足够了,它已经描绘了多边形的开始和结束。

此代码的网页: http://matplotlib.org/devdocs/gallery/mplot3d/polys3d.html

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

# Fixing random state for reproducibility
np.random.seed(19680801)


def cc(arg):
    '''
    Shorthand to convert 'named' colors to rgba format at 60% opacity.
    '''
    return mcolors.to_rgba(arg, alpha=0.6)


def polygon_under_graph(xlist, ylist):
    '''
    Construct the vertex list which defines the polygon filling the space under
    the (xlist, ylist) line graph.  Assumes the xs are in ascending order.
    '''
    return [(xlist[0], 0.)] + list(zip(xlist, ylist)) + [(xlist[-1], 0.)]


fig = plt.figure()
ax = fig.gca(projection='3d')

# Make verts a list, verts[i] will be a list of (x,y) pairs defining polygon i
verts = []

# Set up the x sequence
xs = np.linspace(0., 10., 26)

# The ith polygon will appear on the plane y = zs[i]
zs = range(4)

for i in zs:
    ys = np.random.rand(len(xs))
    verts.append(polygon_under_graph(xs, ys))

poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'), cc('y')])
ax.add_collection3d(poly, zs=zs, zdir='y')

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_xlim(0, 10)
ax.set_ylim(-1, 4)
ax.set_zlim(0, 1)

plt.show()

1 个答案:

答案 0 :(得分:1)

如果您不确定您找到的某些代码的用途,首先要做的就是尝试一下如果将其删除,会发生什么。

因此,让我们删除[(xlist[0], 0.)][(xlist[-1], 0.)],即收集中的两个额外点,看看会发生什么(在2D情况下,可能更容易看到差):

from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(19680801)


def polygon_under_graph(xlist, ylist):
    return [(xlist[0], 0.)] + list(zip(xlist, ylist)) + [(xlist[-1], 0.)]

def polygon_under_graph_without_endpoints(xlist, ylist):
    return list(zip(xlist, ylist))


fig, (ax,ax2) = plt.subplots(nrows=2, figsize=(5,5), sharex=True, sharey=True)

xs = np.linspace(0., 10., 26)
ys = np.random.rand(len(xs))

### with endpoints ###
verts = []
verts.append(polygon_under_graph(xs, ys))

poly = PolyCollection(verts, facecolors="limegreen")
ax.add_collection(poly)

### without endpoints ###
verts2 = []
verts2.append(polygon_under_graph_without_endpoints(xs, ys))

poly2 = PolyCollection(verts2, facecolors="limegreen")
ax2.add_collection(poly2)

### limits, title, annotation ###
ax.set_xlim(-1, 11)
ax.set_ylim(-.5, 1.5)

ax.set_title("with endpoints")
ax2.set_title("without endpoints")

ax.scatter([xs[0],xs[-1]],[0.,0.], label="endpoints")
ax2.scatter([xs[0],xs[-1]],[0.,0.], label="endpoints")

ax2.legend()
plt.show()

enter image description here

您想要遗漏的两点被绘制为分散,以更清楚地看到差异。考虑到比较,我不确定是否有必要添加更多解释,我认为它不言自明。