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() ax = fig.add_subplot(111) rect = matplotlib.patches.Rectangle((0, 50),50, 100) ax.add_patch(rect) plt.xlim(-10,75) plt.ylim(-10,175) plt.show()
Output:
In the above example, we –
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 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.
- First, imported the required modules.
- Then, generated a pyplot figure and added a subplot.
- 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.
- Then, we added the created rectangle to the axes using the
add_patch
method. - 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() ax = fig.add_subplot(111) rect = matplotlib.patches.Rectangle((0, 50),50, 100,angle=30) ax.add_patch(rect) plt.xlim(-100,100) plt.ylim(-100,200) plt.show()
Output:
In the above example, we –
- First, imported the required modules.
- Then, generated a pyplot figure and added a subplot.
- 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.
- Then, we added the created rectangle to the axes using the
add_patch
method. - 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() ax = fig.add_subplot(111) rect = matplotlib.patches.Rectangle((0, 50),50, 100,facecolor='blue',edgecolor='pink', lw = 10) ax.add_patch(rect) plt.xlim(-100,100) plt.ylim(-100,200) plt.show()
Output:
In the above example, we –
- First, imported the required modules.
- Then, generated a pyplot figure and added a subplot.
- 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.
- Then, we added the created rectangle to the axes using the
add_patch
method. - 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() ax = fig.add_subplot(111) rect = matplotlib.patches.Rectangle((0, 50),50, 100,facecolor='red',alpha = 0.1) ax.add_patch(rect) plt.xlim(-100,100) plt.ylim(-100,200) plt.show()
Output:
In the above example, we –
- First, imported the required modules.
- Then, generated a pyplot figure and added a subplot.
- 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. - Then, we added the created rectangle to the axes using the
add_patch
method. - 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() ax = fig.add_subplot(111) rect1 = matplotlib.patches.Rectangle((0, 50),50, 100) rect2 = matplotlib.patches.Rectangle((100, 50),10, 100) ax.add_patch(rect1) ax.add_patch(rect2) plt.xlim(-400,400) plt.ylim(-400,400) plt.show()
Output:
In the above example, we –
- First, imported the required modules.
- Then, generated a pyplot figure and added a subplot.
- 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.
- 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.
- Then, we added the created rectangles to the axes using the
add_patch
method. - 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]) ax.add_patch( Rectangle((5, 82.5), 5, 7.5, fc='none', color ='yellow', linewidth = 5, linestyle="dotted") ) plt.show()
Output:
In the above example, we –
- First, imported the required modules.
- Then, generated a subplot.
- Then we created a scatter plot of the data points using the
pyplot.scatter()
method (refer here). - 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
. - Then, we added the created rectangle to the axes using the
add_patch
method. - 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" # load penguns data with Pandas read_csv df = pd.read_csv(penguins_data, sep="t") 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.gca().add_patch(rect) plt.show()
Output:
In the above example, we –
- First, imported the required modules.
- 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). - Then, plot the scatter points which are in the dataframe.
- Then, draw the rectangle over the scatter plot.
- Then, we added the created rectangle to the axes using the
add_patch
method. - 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') ax.add_patch(rect) plt.show()
Output:
In the above example, we –
- First, imported the required modules and methods.
- Then, we get the image from a url and store it in our local storage using the
urllib.request.urlretrieve
method (refer this). - Then, we open the image (refer this) and convert it into its respective pixels using
np.array
(refer this). - Then, we create a subplot and add the image to the subplot.
- Then, we create a rectangle and add it to the axes using the
add_path
method. - And finally, we plotted the figure.
You might also be interested in –
- How to set the aspect ratio in Matplotlib?
- Change Line Thickness in Matplotlib
- How to remove the legend border (frame) in Matplotlib?
- Matplotlib – Change Line to Dots
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.