In this Matplotlib article we want to learn How to Create PieChart in Matplotlib, so PieChart allows you to create proportions and percentages in a visually appealing and easy manner, In this article we want to talk that how to create a pie chart using Matplotlib, so Matplotlib is popular data visualization library in Python.
First of all we need to install Matplotlib and we can use pip for that.
1 |
pip install matplotlib |
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import matplotlib.pyplot as plt import numpy as np # Prepare the Data categories = ['Python', 'Java', 'C++', 'C#'] values = [30, 15, 45, 10] # Create the Pie Chart plt.pie(values, labels=categories, explode=(0, 0, 0.1, 0), autopct='%1.1f%%', startangle=90) # Customize the Chart plt.title("Distribution of Categories") plt.axis('equal') # Equal aspect ratio ensures a circular pie chart # Display the Chart plt.show() |
To create a pie chart, we need to import the necessary libraries. In this case, we will import Matplotlib pyplot module and numpy for generating some sample data.
1 2 |
import matplotlib.pyplot as plt import numpy as np |
After that we need to prepare the data that will be represented in the pie chart. For the sake of simplicity, let’s assume we have some data and their corresponding values.
1 2 |
categories = ['Python', 'Java', 'C++', 'C#'] values = [30, 15, 45, 10] |
Now, we can create the pie chart using plt.pie() function. This function requires the values parameter, which represents the data to be plotted. also we can provide additional parameters like labels, colors, and explode (to highlight a particular slice).
1 |
plt.pie(values, labels=categories, explode=(0, 0, 0.1, 0), autopct='%1.1f%%', startangle=90) |
To enhance the appearance of the pie chart, we can customize it further. Matplotlib provides different options to modify the chart appearance, such as colors, shadows and title.
1 2 3 |
plt.title("Distribution of Categories") plt.axis('equal') # Equal aspect ratio ensures a circular pie chart plt.show() |
If you want to save the pie chart as an image, you can use the plt.savefig() function. Simply provide a filename with the desired extension.
1 |
plt.savefig("pie_chart.png") |
Run the complete code and this will be the result
