Zimt

Multiple Pie Charts in Matplotlib: A Step-by-Step Guide

· 5 min read · Pastry and Pies

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To make multiple pie charts in Matplotlib, you must use the plt.subplots() function to create a grid of axes and then call the .pie() method on each specific axis object. This approach allows you to compare different datasets side-by-side within a single figure, ensuring that each chart remains independent while sharing the same overall canvas.

What You'll Need

  • Python installed on your system.
  • The Matplotlib library (install via pip install matplotlib).
  • A dataset (lists, NumPy arrays, or Pandas Series) containing the numerical values and corresponding labels for each chart.
  • A code editor or Jupyter Notebook for execution.

Step-by-Step

  1. Import the Necessary Modules: Start by importing matplotlib.pyplot. This module provides the interface needed to create figures and axes. Use the standard alias plt for brevity.
  2. Prepare Your Data: Organize your data into a structure that is easy to iterate through. For multiple charts, it is most efficient to use a list of dictionaries or a list of tuples where each entry contains the labels and the values for one specific pie chart.
  3. Initialize the Subplot Grid: Use fig, axes = plt.subplots(nrows, ncols). For example, if you want two charts side-by-side, use nrows=1, ncols=2. This returns a Figure object and an axes object. Note that if you create more than one plot, axes becomes a NumPy array containing the individual axis objects.
  4. Flatten the Axes Array: If you created a grid (e.g., 2x2), the axes object is a 2D array. To make it easier to loop through, use axes.flatten(). This converts the grid into a 1D list, allowing you to access each subplot using a single index.
  5. Iterate and Plot: Use a for loop to iterate through your data and the flattened axes array simultaneously using the zip() function. Inside the loop, call ax.pie(values, labels=labels, autopct='%1.1f%%'). The autopct parameter is crucial as it automatically calculates and formats the percentage labels on the slices.
  6. Ensure Circularity: By default, Matplotlib may render pie charts as ellipses if the figure aspect ratio is not square. To fix this, call ax.axis('equal') inside your loop for every axis object.
  7. Add Titles and Layout Adjustments: Use ax.set_title('Chart Name') within the loop to give each pie chart a descriptive heading. Finally, call plt.tight_layout(). This is a critical step that prevents the labels and titles of adjacent charts from overlapping.
  8. Display the Figure: Call plt.show() to render the final visualization on your screen.

Common Mistakes

  • Using plt.pie() instead of ax.pie(): When working with subplots, plt.pie() will always draw on the last active axis. To place charts in specific grid positions, you must use the axis-specific method ax.pie().
  • Forgetting tight_layout(): Without this, the percentage labels of the first chart often collide with the title of the second chart, making the visualization unreadable.
  • Incorrect Array Indexing: Attempting to access axes[0][1] when you only have a single row of plots will result in an IndexError. Always check if your axes object is a single axis, a 1D array, or a 2D array.
  • Overloading the Chart: Trying to fit too many slices (more than 6-8) into multiple small pie charts leads to visual clutter and illegible text.

Tips

  • Use a Consistent Color Palette: To make comparisons easier, use the same color for the same category across all pie charts. You can define a custom color list and pass it to the colors parameter in ax.pie().
  • Implement Donut Charts: You can turn your pie charts into donut charts by adding a white circle at the center. Use centre_circle = plt.Circle((0,0), 0.70, fc='white') and add it to the axis using ax.add_artist(centre_circle).
  • Explode Slices: To highlight a specific piece of data, use the explode parameter. Pass a tuple of values (e.g., (0.1, 0, 0, 0)) where the non-zero value indicates the slice that should be shifted outward.
  • Legend Placement: If labels are too crowded, remove the labels parameter from ax.pie() and instead use fig.legend() to create a single shared legend for the entire figure.

Troubleshooting

  • Charts look like ovals: This happens when the figure window is rectangular. Ensure you call ax.axis('equal') or set the figure size using plt.subplots(figsize=(width, height)) to a ratio that accommodates the number of charts.
  • Labels are cut off: This usually means the margins are too tight. Increase the padding using plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1) or use plt.tight_layout().
  • IndexError: too many indices for array: This occurs when you treat axes as a 2D array (e.g., axes[0][0]) but you only created one row or one column of plots. Use axes.flatten() to standardize the array regardless of the grid dimensions.
  • Percentages overlap: If the slices are too small, the autopct text will overlap. Try increasing the figure size or reducing the number of categories by grouping small values into an "Others" category.

Frequently Asked Questions

Can I have different sizes for each pie chart in the grid?

While plt.subplots() creates uniform grids, you can use plt.subplot2grid() or GridSpec from matplotlib.gridspec to create a layout where some charts occupy more space than others.

How do I save multiple pie charts to a file?

Use plt.savefig('filename.png') after calling plt.tight_layout() but before plt.show(). This saves the entire figure containing all the subplots.

Is it possible to share one legend for all pie charts?

Yes. Avoid adding labels to the individual ax.pie() calls. Instead, collect the handles and labels from one chart and call fig.legend(handles, labels, loc='upper right') to place a single legend on the figure canvas.

How do I change the start angle of the slices?

Use the startangle parameter in the ax.pie() method. For example, startangle=90 will rotate the first slice to start at the top (12 o'clock position) instead of the default 3 o'clock position.

Can I use a Pandas DataFrame to generate these charts?

Yes. You can iterate through the columns of a DataFrame and use the column names as titles and the column values as the data for each ax.pie() call.