Python, being one of the most renowned languages due to its simplicity and versatility, has libraries that allow us to create, manipulate, and visualize graphical representations with considerable ease. In this tutorial, we’ll learn how to draw shapes using Python – more specifically, we’ll use a library called Matplotlib.
Step 1: Install the Matplotlib library
Python itself doesn’t have built-in graphics functionality, but it provides several libraries to handle this. One of the most popular libraries for graphics in Python is Matplotlib. You can install it using pip:
1 |
pip install matplotlib |
Step 2: Import Matplotlib
After installation, the next step is to import the Matplotlib package into your python script.
1 |
import matplotlib.pyplot as plt |
Step 3: Draw a Circle
Below is an example of how to draw a circle in Python using Matplotlib:
1 2 3 4 5 6 |
circle = plt.Circle((0.5, 0.5), 0.2, color = 'blue', fill = False) figure, axes = plt.subplots() axes.add_artist(circle) axes.set_aspect(1) plt.title('Circle') plt.show() |
In the code above, the object “circle” is created with the plt.Circle function. The parameters include the center point, the radius, and the color of the circle, as well as whether the circle is filled. In the following lines, we add this object to our plot.
Step 4: Draw a Rectangle
To draw a rectangle, we will use the function plt.Rectangle. This function takes the bottom left point and the width and the height of the rectangle as parameters.
1 2 3 4 5 |
rectangle = plt.Rectangle((.3,.3),.2,.2,fill = False) fig,ax = plt.subplots() ax.add_artist(rectangle) plt.title('Rectangle') plt.show() |
Similar to the circle, we create the “rectangle” object, add it to our plot, and display it.
Step 5: Save the figure
Finally, if you want to save these figures, use the savefig() function.
1 |
plt.savefig('shapes.png') |
Your file, named “shapes.png”, will be saved in your present working directory.
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import matplotlib.pyplot as plt circle = plt.Circle((0.5, 0.5), 0.2, color = 'blue', fill = False) figure, axes = plt.subplots() axes.add_artist(circle) axes.set_aspect(1) plt.title('Circle') plt.show() rectangle = plt.Rectangle((.3,.3),.2,.2,fill = False) fig,ax = plt.subplots() ax.add_artist(rectangle) plt.title('Rectangle') plt.show() plt.savefig('shapes.png') |
Conclusion
In this tutorial, we’ve covered the basics of drawing shapes in Python using the Matplotlib library. We discussed how to draw a circle and a rectangle, which are some of the most basic shapes, but Matplotlib doesn’t stop there. You can draw various other shapes and even complex geometrical figures. You’re encouraged to further explore the Matplotlib documentation and unleash your creative potential on data representation!