Python Pool: 4 Ways to Draw a Rectangle in Matplotlib

Hello geeks and welcome in today’s article, we will cover the Matplotlib draw rectangle. Along with that, for an overall better understanding, we will also look at its syntax and parameter. Then we will see the application of all the theory part through a couple of examples.

So to draw rectangles on matplotlib plot, we use the function matplotlib patches Rectangle. This function helps us in plotting the rectangular patch with a specific width and height. As we move ahead, things will become a lot clearer to us. We will be looking at the syntax associated with this function, followed by parameters.

Contents of Tutorial

Syntax

matplotlib.patches.Rectangle()

This is the general syntax for our function. It has several parameters associated with it, which we will be cover in the next section of this article.

Parameters

1. xy:

This parameter represents the lower left point from which the rectangle plotting will start.

2. width

Through this parameter user specifies the width of the rectangle that he or she wants to create.

3. height

Through this parameter user specifies the height of the rectangle that he or she wants to create.

4. angle

This parameter represents the angle of rotation for the created rectangle.

Examples

As we are done with all the theory portion related to the Matplotlib draw rectangle. This section will be looking at how this function works and how it helps us achieve our desired output. We will start with an elementary level example and gradually move our way to more complicated examples.

1. How to draw a rectangle in a plot

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
fig, ax = plt.subplots()
ax.plot([1,5,2],[2,3,4],color="cyan")
ax.add_patch(Rectangle((2, 2), 1, 3,color="yellow"))
plt.xlabel("X-AXIS")
plt.ylabel("Y-AXIS")
plt.title("PLOT-1")
plt.show()
Matplotlib draw rectangle

Here we can see the very first example related to matplotlib patches Rectangle. The primary aim of this example was to get aware of the syntax and how it is executed. To do it at first, we have imported the necessary modules. Then we have created a simple plot and changed its color as per my wish. Then to make a rectangle, we have used our functions syntax. Here (2,2) represents the lower-left point from which the rectangle formation will start. Next, we have defined 1 and 3 as their width and height, respectively, for the rectangle. From seeing the output image, it is quite evident that we have executed the program successfully.

2. Draw Matplotlib 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.xlabel("X-AXIS")
plt.ylabel("Y-AXIS")
plt.title("PLOT-2")
plt.show()
matplotlib patches Rectangle

Above, we can see an example related to the scatter plot. A Scatter plot is seen commonly in statistics. Herewith the help of for function, we have tried to create a boundary between the like points and outliners. Outliners can be understood as points that are a way to apart from the rest of the data. If taken into consideration, they can hurt the calculation for the value of central tendencies.

To do so, first, we have created a scatter plot. After this, we have used our function as the above example. Here we have made specific customization to the function. Like we have used “fc,” which decides whether the rectangle will be color filled or not. Then we have used the “linewidth” and “line style” parameters to customize the rectangle border.

3. Plotting a Matplotlib Rectangle on an Image

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
import numpy as np

x = np.array(Image.open('89.jpg'))
plt.imshow(x)


fig, ax = plt.subplots(1)


ax.imshow(x)


rect = patches.Rectangle((500, 1500), 1400, 1300, linewidth=1,
                         edgecolor='r', facecolor="none")


ax.add_patch(rect)
plt.show()
Plotting a Matplotlib Rectangle on an Image

Here we have successfully created a rectangle on an image. To so, we have used our function and specified all the parameters we need.

4. Drawing a 3D Rectangle

The essential thing to draw 3d rectangle is a set of proper coordinates. Using mpl toolkits, you can then plot a 3d rectangle or parallelepiped using the right sets for vertices. Below you can see the code through which we can create a 3d rectangle

import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import matplotlib.pyplot as plt
points = np.array([[-1, -1, -1],
                  [1, -1, -1 ],
                  [1, 1, -1],
                  [-1, 1, -1],
                  [-1, -1, 1],
                  [1, -1, 1 ],
                  [1, 1, 1],
                  [-1, 1, 1]])
Z = points
Z = 10.0*Z
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
r = [-1,1]
X, Y = np.meshgrid(r, r)
ax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2])
verts = [[Z[0],Z[1],Z[2],Z[3]],
 [Z[4],Z[5],Z[6],Z[7]],
 [Z[0],Z[1],Z[5],Z[4]],
 [Z[2],Z[3],Z[7],Z[6]],
 [Z[1],Z[2],Z[6],Z[5]],
 [Z[4],Z[7],Z[3],Z[0]]]
ax.add_collection3d(Poly3DCollection(verts, facecolors='cyan', linewidths=1, edgecolors='r', alpha=.20))
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
3d rectangle matplotlib

Also Read: 6 Ways to Plot a Circle in Matplotlib

Conclusion

In this article, we covered the Matplotlib draw rectangle. The function matplotlib patches Rectangle is used to create rectangles in a plot. Besides that, we have also looked at its syntax and parameters. For better understanding, we looked at a couple of examples. We varied the syntax and looked at the output for each case.

I hope this article was able to clear all doubts. But in case you have any unsolved queries feel free to write them below in the comment section. Done reading this; why not read about ways to convert float to string next.

Author: Shantun Parmar

2 thoughts on “Python Pool: 4 Ways to Draw a Rectangle in Matplotlib

Leave a Reply

Your email address will not be published.