Add labels to a pie chart in Python matplotlib
In this tutorial, we are going to see how to add labels to a pie chart. First of all, let us about what a pie chart is.
In matplotlib pie() function is used to plot the pie chart. Different parameters can be passed to the pie() function to customize the pie chart. some of them are as follows:
- Colors
- Labels
- Explode
- Shadow
- Startangle
Plotting a pie chart
import matplotlib.pyplot as plt data_set = [40, 30, 20, 7, 3] plt.title("Mode of transport") plt.pie(data_set) plt.show()
The above code is an example of a basic pie chart.
Output:
Explanation:
- Import the matplotlib package to access the functions which are used to plot a pie chart.
- Pass the values for the pie chart as a list.
- Using the pie() function plot the pie chart by passing the values list as a parameter.
- Finally, the show() function is used to display the created pie chart.
NOTE:
In the above code title for the pie chart is set using title()
function which is not mandatory.
Labeling the pie chart
import matplotlib.pyplot as plt data_set = [40, 30, 20, 7, 3] plt.title("Mode of transport") plt.pie(data_set, labels=["Motorcycle", "Car", "Bus", "Train", "Bicycle"]) plt.show()
The above code is a basic example of how to set labels in a pie chart.
Output:
Explanation:
- Import the matplotlib package to access the functions which are used to plot a pie chart.
- Pass the values for the pie chart as a list.
- Using the pie() function plot the pie chart by passing the values list as a parameter.
Labels
is an inbuilt parameter inpie()
function where the names are passed as a list.- Finally, the show() function is used to display the created pie chart.
NOTE:
The color of each value can be changed. There is an inbuilt parameter in the pie() function called “colors” where the colors are passed as a list.
import matplotlib.pyplot as plt data_set = [40, 30, 20, 7, 3] plt.title("Mode of transport") plt.pie(data_set, labels=["Motorcycle", "Car", "Bus", "Train", "Bicycle"], colors=["r", "g", "b", "y", "c"]) plt.show()
In the above code,
- r represents red
- g represents green
- b represents blue
- y represents yellow
- c represents cyan
Output:
Leave a Reply