Is there a way to draw a matplotlib patch rectangle with an arc on one side?

Viewed 133

I need to draw a polygon that has 4 sides with the right side being an arc. Similar to this:

enter image description here

I have tried to use the code provided by matplotlib for bezier curves but with no success. Any help would be appreciated : )

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 Answers

I have no idea if that is the correct approach to draw path objects - you better wait for people who have experience with this method. But until then, you can do this:

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()

Sample output:

enter image description here

The matplotlib documentation says that for a Bezier curve, you need (in addition to your current position) two control points and one end point. So, your four-point approach might not be sufficient.

Related