How to Draw a Rectangle in a Matplotlib Plot?

In this tutorial, we’ll try to understand how to draw a rectangle in matplotlib with the help of some examples.

We can directly use `matplotlib.patches.Rectangle` class to draw a rectangle in matplotlib.

Basic Syntax:

`matplotlib.patches.Rectangle(xy, width, height, *, angle=0.0, rotation_point='xy', **kwargs)`

Parameters:

• xy: Lower left point to start the rectangle plotting
• width: width of the rectangle
• height: Height of the rectangle
• angle: Angle of rotation of the rectangle

For more parameters, refer to this.

Examples

Now, let us try to understand the above method using worked-out examples.

Example 1 – Drawing a simple Rectangle in Matplotlib

```import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
rect = matplotlib.patches.Rectangle((0, 50),50, 100)
plt.xlim(-10,75)
plt.ylim(-10,175)
plt.show()```

Output:

In the above example, we –

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

1. First, imported the required modules.
2. Then, generated a pyplot figure and added a subplot.
3. Then, we created a rectangle with the bottom left coordinate of the rectangle to be (0,50), with width as 50 and height as 100.
4. Then, we added the created rectangle to the axes using the `add_patch` method.
5. Then, we adjusted the x and y limits of the axes and plotted the figure.

Example 2 – Drawing a rotated Rectangle in Matplotlib

```import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
rect = matplotlib.patches.Rectangle((0, 50),50, 100,angle=30)
plt.xlim(-100,100)
plt.ylim(-100,200)
plt.show()```

Output:

In the above example, we –

1. First, imported the required modules.
2. Then, generated a pyplot figure and added a subplot.
3. Then, we created a rectangle with the bottom left coordinate of the rectangle to be (0,50), with width as 50 and height as 100, and rotated by an angle of 30 degrees.
4. Then, we added the created rectangle to the axes using the `add_patch` method.
5. Then, we adjusted the x and y limits of the axes and plotted the figure.

Example 3 – Styling a Rectangle in Matplotlib

```import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
rect = matplotlib.patches.Rectangle((0, 50),50, 100,facecolor='blue',edgecolor='pink', lw = 10)
plt.xlim(-100,100)
plt.ylim(-100,200)
plt.show()```

Output:

In the above example, we –

1. First, imported the required modules.
2. Then, generated a pyplot figure and added a subplot.
3. Then, we created a rectangle with the bottom left coordinate of the rectangle to be (0,50), with width as 50 and height as 100, and changed the color of the rectangle to blue and edge color to pink, and the edge width to 10.
4. Then, we added the created rectangle to the axes using the `add_patch` method.
5. Then, we adjusted the x and y limits of the axes and plotted the figure.

Example 4 – Styling a Rectangle By adjusting transparency

```import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
rect = matplotlib.patches.Rectangle((0, 50),50, 100,facecolor='red',alpha = 0.1)
plt.xlim(-100,100)
plt.ylim(-100,200)
plt.show()```

Output:

In the above example, we –

1. First, imported the required modules.
2. Then, generated a pyplot figure and added a subplot.
3. Then, we created a rectangle with the bottom left coordinate of the rectangle to be (0,50), with width as 50 and height as 100, and adjusted the transparency as 10% using the `alpha` parameter.
4. Then, we added the created rectangle to the axes using the `add_patch` method.
5. Then, we adjusted the x and y limits of the axes and plotted the figure.

Example 5 – Drawing multiple rectangles in Matplotlib

```import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
rect1 = matplotlib.patches.Rectangle((0, 50),50, 100)
rect2 = matplotlib.patches.Rectangle((100, 50),10, 100)
plt.xlim(-400,400)
plt.ylim(-400,400)
plt.show()```

Output:

In the above example, we –

1. First, imported the required modules.
2. Then, generated a pyplot figure and added a subplot.
3. Then, we created a rectangle with the bottom left coordinate of the rectangle to be (0,50), with width as 50 and height as 100.
4. Then, we created another rectangle with the bottom left coordinate of the rectangle to be (100,50), with width as 10, and height as 100.
5. Then, we added the created rectangles to the axes using the `add_patch` method.
6. Then, we adjusted the x and y limits of the axes and plotted the figure.

Example 6 – Drawing a Rectangle on a scatter plot

```import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
fig, ax = plt.subplots()
ax.scatter([5, 7, 8, 7, 2, 17, 2, 9,
4, 11, 12, 9, 6],[99, 86, 87, 88, 100, 86,
103, 87, 94, 78, 77, 85, 86])
5, 7.5,
fc='none',
color ='yellow',
linewidth = 5,
linestyle="dotted") )
plt.show()```

Output:

In the above example, we –

1. First, imported the required modules.
2. Then, generated a subplot.
3. Then we created a scatter plot of the data points using the `pyplot.scatter()` method (refer here).
4. Then we created a rectangle with the bottom left coordinate of the rectangle to be (5,82.5), with width as 5, and height as 7.5 with a dotted `linestyle`.
5. Then, we added the created rectangle to the axes using the `add_patch` method.
6. And finally, we plotted the figure.

Example 7 – Drawing a Rectangle on a scatter plot -2

```import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.patches as mpatches

penguins_data="https://raw.githubusercontent.com/datavizpyr/data/master/palmer_penguin_species.tsv"
plt.scatter(x=df.culmen_length_mm,
y=df.culmen_depth_mm)
rect=mpatches.Rectangle((31,15),14,7,
color = "purple",
linewidth = 2,
alpha=0.2)
plt.show()```

Output:

In the above example, we –

1. First, imported the required modules.
2. Then, import the data from an online resource and read the csv using `pandas.read_csv()` method (refer this) into a pandas data frame (refer this).
3. Then, plot the scatter points which are in the dataframe.
4. Then, draw the rectangle over the scatter plot.
5. Then, we added the created rectangle to the axes using the `add_patch` method.
6. And finally, we plotted the figure.

Example 8 – Drawing a rectangle over an Image

```import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
import numpy as np
import urllib.request
urllib.request.urlretrieve(
'https://picsum.photos/200',
"temp.png")
x = np.array(Image.open('temp.png'))
fig, ax = plt.subplots(1)
ax.imshow(x)
rect = patches.Rectangle((10, 100), 100, 30, linewidth=1, edgecolor='r')
plt.show()```

Output:

In the above example, we –

1. First, imported the required modules and methods.
2. Then, we get the image from a url and store it in our local storage using the `urllib.request.urlretrieve` method (refer this).
3. Then, we open the image (refer this) and convert it into its respective pixels using `np.array` (refer this).
4. Then, we create a subplot and add the image to the subplot.
5. Then, we create a rectangle and add it to the axes using the `add_path` method.
6. And finally, we plotted the figure.

You might also be interested in –