有没有办法在matplotlib中绘制一边带有弧形的矩形patch?

3
我需要绘制一个有四条边的多边形,其中右侧是一段弧线。类似于下面这个图示:

enter image description here

我尝试使用matplotlib提供的贝塞尔曲线代码,但没有成功。希望能得到帮助:)
from matplotlib.path import Path
import matplotlib.patches as patches


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

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

path = Path(verts, codes)

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

xs, ys = zip(*verts)
ax.plot(xs, ys, lw=2, color='black', ms=10)
ax.set_xlim(-0.1, 1.1)
ax.set_ylim(-0.1, 1.1)
plt.show()

1个回答

3

我不确定用这种方式绘制路径对象是否正确,最好等待有经验的人。但在此之前,您可以这样做:

from matplotlib.path import Path
import matplotlib.patches as patches


verts = [
   (0, 0),    # P0
   (0, 1),    # P1
   (1, 1),    # P2
   (0.4, 1),  #these are the vertices for the 
   (0.2, 0),  #Bezier curve
   (0.5, 0),  # P3
   (0, 0)     #and back to P0
]

codes = [
    Path.MOVETO,  # P0
    Path.LINETO,  #line to P1
    Path.LINETO,  #line to P2
    Path.CURVE4,  #control point one for the Bezier curve
    Path.CURVE4,  #control point two
    Path.CURVE4,  #end point for the Bezier curve
    Path.LINETO   #and back to P0
 ]

path = Path(verts, codes)

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

#you can add the hull figure for the Bezier curve
#xs, ys = zip(*verts)
#ax.plot(xs, ys, "x--", lw=2, color='black', ms=10) 

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

样例输出:

请输入图片描述

Matplotlib 文档 表明,在贝塞尔曲线中,你需要(除了当前位置)两个控制点和一个结束点。因此,你基于四个点的方法可能不足够。


非常感谢!这正好是我所需的。 - C_van3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接