• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Data Viz with Python and R

Learn to Make Plots in Python and R

  • Home
  • Python Viz
  • Seaborn
  • Altair
  • R Viz
  • ggplot2
  • About
    • Privacy Policy
  • Show Search
Hide Search

How To Draw a Rectangle on a Plot in Matplotlib?

datavizpyr · January 30, 2021 ·

When you make data visualization one might want to highlight a specific region of the plot by adding some annotation. In this post, we will learn how to add rectangle on top of a plot made with matplotlib in Python. We will first add a simple rectangle with specific color and then learn how to fill the rectangle with a color of choice. Next we will also see an example of adding text to describe the addition of rectangle. And finally we will see how can we add multiple rectangles on matplotlib plot in python.

Let us load Matplotlib and Pandas.

import matplotlib.pyplot as plt
import pandas as pd

We will use Palmer penguins dataset and load it directly from datavizpyr.com’s github page.

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")
df.head()

To illustrate how to add rectangle on a plot made with matplotlib, we will use scatter plot made with matplotlib. Let us first make the scatter plot using scatter() function in matplotlib. Here we also specify x and y-axis labels in bold font with larger fontsize.

plt.scatter(x=df.culmen_length_mm,
            y=df.culmen_depth_mm)
plt.xlabel("Culmen Length (mm)",fontweight ='bold', size=14)
plt.ylabel("Culmen Depth (mm)", fontweight ='bold',size=14)
Scatter plot with matplotlib in Python
Scatter plot with matplotlib in Python

How To Draw Rectangle on a Plot Made With matplotlib?

patches module in matplotlib allows us add shapes like rectangle on top of a plot. Let us load patches as mpatches.

import matplotlib.patches as mpatches

We can add rectangle by using Rectangle() function in patches module. The Rectangle function takes the location/size of the rectangle you need, left position, bottom location, and width & height.

# specify the location of (left,bottom),width,height
rect=mpatches.Rectangle((31,15),14,7, 
                        fill = False,
                        color = "purple",
                        linewidth = 2)

To add this rectangle object on top of the already exisitng plot, we get current axis using gca() function and add the rectangle on top of the plot using add_patch() function.

plt.gca().add_patch(rect)

We just saw how to add rectangle step-by-step above. Let us put together the codes above as chunk and add rectangle on top of the scatter plot.

plt.scatter(x=df.culmen_length_mm,
            y=df.culmen_depth_mm)
plt.xlabel("Culmen Length (mm)",fontweight ='bold', size=14)
plt.ylabel("Culmen Depth (mm)", fontweight ='bold',size=14)
left, bottom, width, height = (31, 15, 14, 7)
rect=mpatches.Rectangle((left,bottom),width,height, 
                        fill=False,
                        color="purple",
                       linewidth=2)
                       #facecolor="red")
plt.gca().add_patch(rect)

And we get a nice scatter plot with rectangle highlighting the specific portion of the plot as we needed.

Add Rectangle with mpatches in Matplotlib Python
Add Rectangle with mpatches in Matplotlib Python

How To Draw Rectangle filled with color on a Plot Made With matplotlib?

Previously, we drew a simple rectangle.Now, let us customize it in a few different ways. First, we will fill the rectangle with a color to highlight the portion of the plot better.

We can fill the rectangle with a color by not using fill=False and specifying the color with facecolor. Here we also specify transparency level for filling.

plt.scatter(x=df.culmen_length_mm,
            y=df.culmen_depth_mm)
plt.xlabel("Culmen Length (mm)",fontweight ='bold', size=14)
plt.ylabel("Culmen Depth (mm)", fontweight ='bold',size=14)
left, bottom, width, height = (31, 15, 14, 7)
rect=mpatches.Rectangle((left,bottom),width,height, 
                        #fill=False,
                        alpha=0.1,
                       facecolor="red")
plt.gca().add_patch(rect)
Add Rectangle with Fill Color Matplotlib
Add Rectangle with Fill Color Matplotlib

How To Add Text Annotation to Rectangle on a Plot Made With matplotlib?

We can add text to describe the rectangle using text() function in matplotlib. Here, we add text annotation right after we draw rectangle.

plt.scatter(x=df.culmen_length_mm,
            y=df.culmen_depth_mm)
plt.xlabel("Culmen Length (mm)",fontweight ='bold', size=14)
plt.ylabel("Culmen Depth (mm)", fontweight ='bold',size=14)
left, bottom, width, height = (31, 15, 14, 7)
rect=mpatches.Rectangle((left,bottom),width,height, 
                        #fill=False,
                        alpha=0.1,
                        #color="purple",
                       #linewidth=2,
                       facecolor="red")
plt.gca().add_patch(rect)
# add text with text() function in matplotlib
plt.text(31, 21.3,'rectangle',fontsize=16, color="red", weight="bold")
Add Rectangle with text annotation Matplotlib
Add Rectangle with text annotation Matplotlib

How To Draw Multiple Rectangles on a Plot Made With matplotlib?

It is also easy to add multiple rectangles to highlight multiple parts of the plot. In this example, we use the similar code chunk twice to add two rectangles in different colors.

# make scatter plot
plt.scatter(x=df.culmen_length_mm,
            y=df.culmen_depth_mm)
plt.xlabel("Culmen Length (mm)",fontweight ='bold', size=14)
plt.ylabel("Culmen Depth (mm)", fontweight ='bold',size=14)
# add first rectangle with patches
left, bottom, width, height = (31, 15, 14, 7)
rect=mpatches.Rectangle((left,bottom),width,height, 
                        #fill=False,
                        alpha=0.1,
                        #color="purple",
                       #linewidth=2,
                       facecolor="red")
plt.gca().add_patch(rect)

# add second rectangle with patches
left, bottom, width, height = (48, 17.5, 7, 4)
rect=mpatches.Rectangle((left,bottom),width,height, 
                        #fill=False,
                        alpha=0.1,
                        #color="purple",
                       #linewidth=2,
                       facecolor="green")
plt.gca().add_patch(rect)

And this is how the plot with two filled rectangles over a scatter plot looks like.

Add Multiple Rectangles with Matplotlib
Add Multiple Rectangles with Matplotlib

Related posts:

How To Adjust Axes Label Position in Matplotlib?How To Adjust Positions of Axis Labels in Matplotlib? Connect Paired Points with Lines in MatplotlibHow To Connect Paired Data Points with Lines in Scatter Plot with Matplotlib Matplotlib Scatter plot with legendHow to Add Legend to Scatterplot Colored by a Variable with Matplotlib in Python Barplot with dollar sign on axis ticksHow To Add Dollar Sign on Axis Ticks in Matplotlib

Filed Under: Matplotlib, Python Tagged With: Matplotlib, Python

Primary Sidebar

Tags

Altair barplot Boxplot boxplot python boxplot with jiitered text labels Bubble Plot Color Palette Countplot Density Plot Facet Plot gganimate ggplot2 ggplot2 Boxplot ggplot2 error ggplot boxplot ggridges ggtext element_markdown() Grouped Barplot R heatmap heatmaps Histogram Histograms Horizontal boxplot Python lollipop plot Maps Matplotlib Pandas patchwork pheatmap Pyhon Python R RColorBrewer reorder boxplot ggplot Ridgeline plot Scatter Plot Scatter Plot Altair Seaborn Seaborn Boxplot Stock Price Over Time Stripplot UpSetR Violinplot Violin Plot World Map ggplot2

Buy Me a Coffee

Copyright © 2025 · Daily Dish Pro on Genesis Framework · WordPress · Log in

Go to mobile version