Creating pie charts in Matplotlib is straightforward. You can use the plt.pie()
function to generate pie charts. Here’s a comprehensive guide on how to create and customize pie charts in Matplotlib.
To create a basic pie chart, you need to provide a list of values that represent the sizes of the pie slices.
import matplotlib.pyplot as plt # Data sizes = [15, 30, 45, 10] # Create a pie chart plt.pie(sizes) plt.show()
You can add labels to each slice of the pie chart by using the labels
parameter.
# Data sizes = [15, 30, 45, 10] labels = ['A', 'B', 'C', 'D'] # Create a pie chart with labels plt.pie(sizes, labels=labels) plt.show()
You can customize the colors of the pie chart slices using the colors
parameter.
# Data sizes = [15, 30, 45, 10] labels = ['A', 'B', 'C', 'D'] colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue'] # Create a pie chart with custom colors plt.pie(sizes, labels=labels, colors=colors) plt.show()
Adding a legend to the pie chart can make it more informative.
# Data sizes = [15, 30, 45, 10] labels = ['A', 'B', 'C', 'D'] colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue'] # Create a pie chart with a legend plt.pie(sizes, labels=labels, colors=colors) plt.legend(labels, loc='best') plt.show()
You can "explode" one or more slices away from the center to highlight them using the explode
parameter.
# Data sizes = [15, 30, 45, 10] labels = ['A', 'B', 'C', 'D'] colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue'] explode = (0, 0.1, 0, 0) # Only "explode" the 2nd slice (i.e. 'B') # Create a pie chart with exploded slice plt.pie(sizes, labels=labels, colors=colors, explode=explode) plt.show()
You can add percentages to the slices using the autopct
parameter.
# Data sizes = [15, 30, 45, 10] labels = ['A', 'B', 'C', 'D'] colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue'] # Create a pie chart with percentages plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%') plt.show()
Here’s a more comprehensive example that incorporates several of the customizations discussed:
import matplotlib.pyplot as plt # Data sizes = [15, 30, 45, 10] labels = ['A', 'B', 'C', 'D'] colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue'] explode = (0, 0.1, 0, 0) # Only "explode" the 2nd slice (i.e. 'B') # Create a pie chart plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140) # Equal aspect ratio ensures that pie is drawn as a circle. plt.axis('equal') # Add legend plt.legend(labels, loc='best') # Show plot plt.title('Custom Pie Chart') plt.show()