# 路径教程

``````import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches

verts = [
(0., 0.), # left, bottom
(0., 1.), # left, top
(1., 1.), # right, top
(1., 0.), # right, bottom
(0., 0.), # ignored
]

codes = [Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.CLOSEPOLY,
]

path = Path(verts, codes)

fig = plt.figure()
patch = patches.PathPatch(path, facecolor='orange', lw=2)
ax.set_xlim(-2,2)
ax.set_ylim(-2,2)
plt.show()
``````

`STOP` 1 （被忽略） 标志整个路径终点的标记（当前不需要或已忽略）
`MOVETO` 1 提起笔并移动到指定顶点
`LINETO` 1 从当前位置向指定顶点画线
`CURVE3` 2 （一个控制点，一个终点） 从当前位置，以给定控制点向给定端点画贝塞尔曲线
`CURVE4` 3 （两个控制点，一个终点） 从当前位置，以给定控制点向给定端点画三次贝塞尔曲线
`CLOSEPOLY` 1 （点自身被忽略） 向当前折线的起点画线

## 贝塞尔示例

``````import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches

verts = [
(0., 0.),  # P0
(0.2, 1.), # P1
(1., 0.8), # P2
(0.8, 0.), # P3
]

codes = [Path.MOVETO,
Path.CURVE4,
Path.CURVE4,
Path.CURVE4,
]

path = Path(verts, codes)

fig = plt.figure()
patch = patches.PathPatch(path, facecolor='none', lw=2)

xs, ys = zip(*verts)
ax.plot(xs, ys, 'x--', lw=2, color='black', ms=10)

ax.text(-0.05, -0.05, 'P0')
ax.text(0.15, 1.05, 'P1')
ax.text(1.05, 0.85, 'P2')
ax.text(0.85, -0.05, 'P3')

ax.set_xlim(-0.1, 1.1)
ax.set_ylim(-0.1, 1.1)
plt.show()
``````

## 复合路径

``````# histogram our data with numpy
data = np.random.randn(1000)
n, bins = np.histogram(data, 100)
``````

``````# get the corners of the rectangles for the histogram
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n
``````

``````nverts = nrects*(1+3+1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5,0] = left
verts[0::5,1] = bottom
verts[1::5,0] = left
verts[1::5,1] = top
verts[2::5,0] = right
verts[2::5,1] = top
verts[3::5,0] = right
verts[3::5,1] = bottom
``````

``````barpath = path.Path(verts, codes)
patch = patches.PathPatch(barpath, facecolor='green',
edgecolor='yellow', alpha=0.5)