Skip to content Skip to sidebar Skip to footer

Matplotlib - How To Plot A Random-oriented Rectangle (or Any Shape)?

I wish to draw a line whose width is specified in the data unit. In this case, simply doing plot(x, y, linewidth=1) would fail, as the linewidth there is NOT specified in data un

Solution 1:

Even simpler, matplotlib.patches.Rectangle

rect = matplotlib.patches.Rectangle((.25, .25), .25, .5, angle=45)
plt.gca().add_patch(rect)
plt.draw()

Solution 2:

Good question! I would suggest you that do not limit yourself in the fill_between function. I always regard it as beneficial to look deep inside the things. Let's dive into the essence of the Python drawing.

The object underlying all of the matplotlib.patch objects is the Path.

Therefore, if you master the Path, you basically can draw whatever you like in whatever manner. Let's now see how do we achieve your goal with the magical Path.

To get the rectangle you mentioned in the question, only a bit of adaption on the example is needed.

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

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

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

path = Path(verts, codes)
fig = plt.figure()
ax = fig.add_subplot(111)
patch = patches.PathPatch(path, facecolor='orange', lw=2)
ax.add_patch(patch) 
ax.axis('equal')
plt.show()

I think the code is so straightforward and self-explanatory that I do not need to waste my words on it. Just copy and paste and run it, you will get this, exactly what you want.

enter image description here

Solution 3:

Instead of plotting the lines, you can draw the filled area as a polygon. To do this, you need to concatenate x1 with the reverse of x2 and do the same for y1 and y2. Something like this:

In [1]: from pylab import *
In [2]: x1 = arange(0,11,2)
In [3]: x2 = arange(0,11)
In [4]: y1 = x1**2+1
In [5]: y2 = x2**2-1
In [6]: xy = c_[r_[x1,x2[::-1]], r_[y1,y2[::-1]]]
In [7]: ax = subplot(111) # we need an axis first
In [8]: ax.add_patch(Polygon(xy))
Out[8]: <matplotlib.patches.Polygon at 0x3bff990>
In [9]: axis([0,10,-10,110]) # axis does not automatically zoom to a patch
Out[9]: [0, 10, -10, 110]
In [10]: show()

Post a Comment for "Matplotlib - How To Plot A Random-oriented Rectangle (or Any Shape)?"