November 13, 2024

How to Properly Draw Rectangles in Matplotlib and Python

In this Matplotlib and Python tutorial, we thoroughly explain how to draw rectangles in Python and how to adjust the rectangle properties, such as transparency, face color, edge color, hatch, and other visual properties. The YouTube tutorial accompanying this webpage tutorial is given below.

Copyright Notices and NOT to Be Used for AI Notice

COPYRIGHT NOTICE: THE TEXT, PHOTOS, AND CODES POSTED ON THIS WEBSITE AND ON THIS WEBPAGE ARE THE OWNERSHIP, INTELLECTUAL PROPERTY, AND COPYRIGHTED BY THE AUTHOR: ALEKSANDAR HABER. THE TEXT AND THE CONTENT OF THIS PAGE SHOULD NOT BE PHYSICALLY COPIED, SHOULD NOT BE COPIED ON OTHER WEBSITES, SHOULD NOT BE REPRINTED, SHOULD NOT BE REPOSTED ON OTHER WEBSITES, SHOULD NOT BE USED AS A LECTURE MATERIAL IN UNIVERSITY COURSES, SHOULD NOT BE USED AS LECTURE MATERIAL IN COURSES ORGANIZED BY AND HOSTED ON ONLINE LEARNING PLATFORMS (such as Udemy, Coursera, etc), AND SHOULD NOT BE USED IN COMMERCIAL SETTING. THE TEXT, PHOTOS, AND CODE PRESENTED ON THIS WEBSITE AND WEBPAGE SHOULD NOT BE INCLUDED IN REPORTS, STUDENT PAPERS, SCIENTIFIC PAPERS, OR IN ANY OTHER PRINTED OR A DIGITAL FORM OR A DOCUMENT WITHOUT WRITTEN CONSENT OF THE AUTHOR. A MONEY FEE MIGHT BE REQUIRED TO REPRINT THE MATERIAL POSTED ON THIS WEBSITE: CONTACT THE AUTHOR: ml.mecheng@gmail.com

CODE COPYRIGHT NOTICE AND LICENSE: THE CODE FILES POSTED ON THIS WEBSITE ARE NOT FREE SOFTWARE AND CODE. IF YOU WANT TO USE THIS CODE IN THE COMMERCIAL SETTING OR ACADEMIC SETTING, THAT IS, IF YOU WORK FOR A COMPANY OR IF YOU ARE AN INDEPENDENT CONSULTANT AND IF YOU WANT TO USE THIS CODE OR IF YOU ARE ACADEMIC RESEARCHER OR STUDENT, THEN WITHOUT MY PERMISSION AND WITHOUT PAYING THE PROPER FEE, YOU ARE NOT ALLOWED TO USE THIS CODE. YOU CAN CONTACT ME AT
ml.mecheng@gmail.com
TO INFORM YOURSELF ABOUT THE LICENSE OPTIONS AND FEES FOR USING THIS CODE. ALSO, IT IS NOT ALLOWED TO (1) MODIFY THIS CODE IN ANY WAY WITHOUT MY PERMISSION. (2) INTEGRATE THIS CODE IN OTHER PROJECTS WITHOUT MY PERMISSION. (3) POST THIS CODE ON ANY PRIVATE OR PUBLIC WEBSITES OR CODE REPOSITORIES. DELIBERATE OR INDELIBERATE VIOLATIONS OF THIS LICENSE WILL INDUCE LEGAL ACTIONS AND LAWSUITS.

NOT TO BE USED FOR AI COPYRIGHT NOTICE: The code and text, as well as all other material on this webpage and the YouTube page, should NOT be used to train an AI algorithm or a large language model, or any type of AI or machine learning algorithm used to recognize, interpret, and draw conclusions from text. Also, it is forbidden to crawl this webpage and to extract information for training an AI algorithm of any sort on the basis of the material presented on this webpage.

How to Draw Rectangles in Python

In Python, we draw geometrical shapes such as rectangles, circles, polygons, etc, by using patches. Patches are primitive shapes that are defined by the Matplotlib library.

To create and draw a rectangle in Python, we first need to create a rectangle patch object, and then we need to add the created rectangle to the Axes object. A rectangle is defined by the coordinates of its bottom left corner point, width, and height. The Python script given below creates and draws a rectangle.

import matplotlib.pyplot as plt

plt.figure(figsize=(8,8))
# we draw a rectangle by specifying the bottom left corner point, width and height
# we need to create a patch
# the class is matplotlib.patches.Rectangle
rect1=plt.Rectangle(xy=(0.2,0.3), width=1.2, height=0.8, color='r' )
# get the current figure 
fig = plt.gcf()
# get the current Axes instance
ax = fig.gca()
# add the patch to the Axes
ax.add_patch(rect1)
# set the figure limits 
plt.xlim([-2,3])
plt.ylim([-2,3])
# save the figure 
plt.savefig('rectangle1.png',dpi=600)
# show the figure
plt.show()

We create a patch object representing the rectangle by using the function

rect1=plt.Rectangle(xy=(0.2,0.3), width=1.2, height=0.8, color='r' )

“xy” specifies the coordinates of the bottom left corner of the rectangle, and the other keyword arguments specify the width and height. To get a reference to the current figure, we use “plt.gcf()”. To get a reference to the Axes object of the current figure, we use “fig.gca()”. We add the created rectangle patch to the current Axes (current figure), by using

ax.add_patch(rect1)

After that we set the figure axis limits, and save and show the figure. The figure is shown below.

How to Draw a Rectangle Without a Fill Color (Face Color) and Only With Edge Line in Python and Matplotlb

Here, we explain how to draw a rectangle without a face fill, and only with an edge line in Python.

import matplotlib.pyplot as plt

plt.figure(figsize=(8,8))
# we draw a rectangle by specifying the bottom left corner point, width and height
# we need to create a patch
# the class is matplotlib.patches.Rectangle
rect1=plt.Rectangle(xy=(0.2,0.3), width=1.2, height=0.8, color='r', 
                    fill=False, linewidth=9)
# get the current figure 
fig = plt.gcf()
# get the current Axes instance
ax = fig.gca()
# add the patch to the Axes
ax.add_patch(rect1)
# set the figure limits 
plt.xlim([-2,3])
plt.ylim([-2,3])
# save the figure 
plt.savefig('rectangle1.png',dpi=600)
# show the figure
plt.show()

We control the rectangle fill by using the keyword argument “fill”. It can be True or False. If we specify the rectangle without a fill, we need to specify the line width of the edge line. We do that by using the keyword argument “linewidth”. The rectangle is shown in the figure below.

How to Draw Rectangles with Specific Face and Edge Colors in Python and Matplotlib

Here, we explain how to draw rectangles with predefined face and edge colors in Python. The Python script is given below.

import matplotlib.pyplot as plt

plt.figure(figsize=(8,8))
# we draw a rectangle by specifying the bottom left corner point, width and height
# we need to create a patch
# the class is matplotlib.patches.Rectangle
rect1=plt.Rectangle(xy=(0.2,0.3), width=1.2, height=0.8, 
                    edgecolor='r', facecolor='b', alpha=0.7, linewidth=9)
# get the current figure 
fig = plt.gcf()
# get the current Axes instance
ax = fig.gca()
# add the patch to the Axes
ax.add_patch(rect1)
# set the figure limits 
plt.xlim([-2,3])
plt.ylim([-2,3])
# save the figure 
plt.savefig('rectangle1.png',dpi=600)
# show the figure
plt.show()

To control the face and edge colors, we use the keyword arguments “edgecolor” and “facecolor”. We control the transparency of the rectangle by using the argument “alpha” which is in the interval from 0 (completely transparent) to 1 (not transparent). The rectangle is shown in the figure below.

How to Draw Rectangles With Hatch in Python and Matplotlib

The Python script given below draws a circle with a face filled with a hatch pattern.

import matplotlib.pyplot as plt

plt.figure(figsize=(8,8))
# we draw a rectangle by specifying the bottom left corner point, width and height
# we need to create a patch
# the class is matplotlib.patches.Rectangle

# hatch 
# #  '/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'
rect1=plt.Rectangle(xy=(0.2,0.3), width=1.2, height=0.8, 
                    facecolor='r', hatch='/', linewidth=5)
# get the current figure 
fig = plt.gcf()
# get the current Axes instance
ax = fig.gca()
# add the patch to the Axes
ax.add_patch(rect1)
# set the figure limits 
plt.xlim([-2,3])
plt.ylim([-2,3])
# save the figure 
plt.savefig('rectangle4.png',dpi=600)
# show the figure
plt.show()

We specify the hatch by using the keyword argument “hatch”. We can use the following characters for the hatch pattern: “‘/’, ‘\’, ‘|’, ‘-‘, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’ “. The image is shown below.