Matplotlib Pie Charts in Python
Matplotlib Pie Charts in Python
Pie charts are a popular way to represent categorical data in a circular format, where each wedge of the pie represents a proportion of the whole. In Matplotlib, you can create pie charts using the plt.pie() function.
1. Basic Pie Chart
To create a basic pie chart, you just need to pass the sizes of the different segments to plt.pie().
Example: Basic Pie Chart
import matplotlib.pyplot as plt# Datalabels = ['A', 'B', 'C', 'D']sizes = [15, 30, 45, 10]# Creating a pie chartplt.pie(sizes, labels=labels)# Adding a titleplt.title("Basic Pie Chart")# Displaying the plotplt.show()Explanation:
sizes: A list of values representing the size of each pie slice.labels: The categories corresponding to each slice.plt.pie(sizes, labels=labels): Creates the pie chart with labeled slices.
2. Exploding Slices
You can "explode" one or more slices to emphasize a specific category by slightly offsetting them from the center of the pie.
Example: Exploding a Slice
import matplotlib.pyplot as plt# Datalabels = ['A', 'B', 'C', 'D']sizes = [15, 30, 45, 10]explode = (0.1, 0, 0, 0) # "Exploding" the first slice (A)# Creating a pie chart with exploded sliceplt.pie(sizes, labels=labels, explode=explode)# Adding a titleplt.title("Pie Chart with Exploded Slice")# Displaying the plotplt.show()Explanation:
explode: A tuple where each element corresponds to a slice. A value of0.1means the slice is "exploded" or offset from the center by 10%.
3. Customizing Colors
You can specify custom colors for each slice of the pie chart.
Example: Pie Chart with Custom Colors
import matplotlib.pyplot as plt# Datalabels = ['A', 'B', 'C', 'D']sizes = [15, 30, 45, 10]colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99'] # Custom colors# Creating a pie chart with custom colorsplt.pie(sizes, labels=labels, colors=colors)# Adding a titleplt.title("Pie Chart with Custom Colors")# Displaying the plotplt.show()Explanation:
colors: A list of colors to be applied to each slice of the pie. You can use color names or hex color codes.
4. Adding Percentages to Slices
By default, the pie chart displays the fraction of each slice in relation to the total, but you can also add percentages to the slices.
Example: Pie Chart with Percentages
import matplotlib.pyplot as plt# Datalabels = ['A', 'B', 'C', 'D']sizes = [15, 30, 45, 10]# Creating a pie chart with percentagesplt.pie(sizes, labels=labels, autopct='%1.1f%%')# Adding a titleplt.title("Pie Chart with Percentages")# Displaying the plotplt.show()Explanation:
autopct='%1.1f%%': Formats the percentage displayed on each slice to 1 decimal place.
5. Adding a Shadow Effect
You can add a shadow effect to the pie chart to make it look more three-dimensional.
Example: Pie Chart with Shadow
import matplotlib.pyplot as plt# Datalabels = ['A', 'B', 'C', 'D']sizes = [15, 30, 45, 10]# Creating a pie chart with a shadowplt.pie(sizes, labels=labels, shadow=True)# Adding a titleplt.title("Pie Chart with Shadow")# Displaying the plotplt.show()Explanation:
shadow=True: Adds a shadow effect to the pie chart.
6. Setting the Start Angle
You can change the starting angle of the first slice by using the startangle parameter. This is useful if you want to rotate the pie chart to start from a different position.
Example: Pie Chart with Custom Start Angle
import matplotlib.pyplot as plt# Datalabels = ['A', 'B', 'C', 'D']sizes = [15, 30, 45, 10]# Creating a pie chart with a custom start angleplt.pie(sizes, labels=labels, startangle=90)# Adding a titleplt.title("Pie Chart with Custom Start Angle")# Displaying the plotplt.show()Explanation:
startangle=90: Rotates the pie chart by 90 degrees, so the first slice starts from the top.
7. Equal Aspect Ratio (Circle Shape)
By default, Matplotlib will make the pie chart fill the available space, which could distort the pie chart if the axes are not square. You can ensure the pie chart stays circular by setting an equal aspect ratio.
Example: Pie Chart with Equal Aspect Ratio
import matplotlib.pyplot as plt# Datalabels = ['A', 'B', 'C', 'D']sizes = [15, 30, 45, 10]# Creating a pie chartplt.pie(sizes, labels=labels)# Adding a titleplt.title("Pie Chart with Equal Aspect Ratio")# Ensuring the pie chart is a circleplt.axis('equal')# Displaying the plotplt.show()Explanation:
plt.axis('equal'): Ensures that the pie chart is displayed as a perfect circle, maintaining equal scaling on both axes.
8. Displaying a Legend
In addition to the labels directly on the slices, you can also add a legend to the pie chart to provide more information.
Example: Pie Chart with Legend
import matplotlib.pyplot as plt# Datalabels = ['A', 'B', 'C', 'D']sizes = [15, 30, 45, 10]# Creating a pie chartplt.pie(sizes, labels=labels)# Adding a titleplt.title("Pie Chart with Legend")# Displaying a legendplt.legend(labels, loc="best")# Displaying the plotplt.show()Explanation:
plt.legend(labels, loc="best"): Displays a legend with the given labels. Theloc="best"option automatically places the legend in the best location.
9. Multiple Pie Charts in One Plot
You can create multiple pie charts in one figure by using subplots.
Example: Multiple Pie Charts in One Plot
import matplotlib.pyplot as plt# Data for two pie chartssizes1 = [15, 30, 45, 10]sizes2 = [20, 20, 30, 30]labels = ['A', 'B', 'C', 'D']# Creating subplotsfig, (ax1, ax2) = plt.subplots(1, 2)# Plotting the first pie chartax1.pie(sizes1, labels=labels)ax1.set_title("Pie Chart 1")# Plotting the second pie chartax2.pie(sizes2, labels=labels)ax2.set_title("Pie Chart 2")# Displaying the plotplt.show()Explanation:
fig, (ax1, ax2) = plt.subplots(1, 2): Creates a figure with 1 row and 2 columns for displaying two pie charts side by side.
Conclusion
Pie charts are a great way to visualize categorical data in a proportional way. Matplotlib offers a wide variety of customizations for pie charts, including options for coloring, adding labels, explosions, shadows, percentages, and legends. You can also control the start angle and aspect ratio to ensure the chart looks the way you want.
Key Functions and Parameters:
plt.pie(sizes, labels=labels): Basic pie chart creation.autopct='%1.1f%%': Adds percentage labels on the slices.explode: Offsets slices from the center.colors: Specifies custom colors for each slice.shadow=True: Adds a shadow effect.startangle=90: Rotates the pie chart.plt.axis('equal'): Ensures the pie chart is circular.plt.legend(): Adds a legend for better readability.
Let me know if you have any further questions or need more examples!