
Creating pie charts in Python can be an intuitive process, especially with libraries like Matplotlib. To start with, you’ll want to ensure you have Matplotlib installed. If you don’t have it yet, you can install it using pip.
pip install matplotlib
Once you have Matplotlib set up, you can begin by importing the necessary modules. Here’s a simple example to illustrate how to create a basic pie chart:
import matplotlib.pyplot as plt
# Data to plot
sizes = [15, 30, 45, 10]
labels = ['A', 'B', 'C', 'D']
# Create a pie chart
plt.pie(sizes, labels=labels)
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
This code snippet creates a pie chart representing the proportions of categories A, B, C, and D. The plt.pie() function is quite versatile, allowing for various customizations, but let’s keep it simple for now.
Understanding the parameters very important. The sizes list defines the relative sizes of each pie slice, while the labels list assigns names to those slices. The plt.axis('equal') line is important for maintaining the circle’s shape; otherwise, it might display as an ellipse depending on the figure size.
As you get more comfortable with basic pie charts, you might want to explore additional features, such as exploding slices or adding percentages. Here’s how you can explode a slice to emphasize it:
explode = (0.1, 0, 0, 0) # only "explode" the 1st slice (A)
plt.pie(sizes, labels=labels, explode=explode)
plt.axis('equal')
plt.show()
In this example, the first slice (A) is “exploded” outwards. This visual cue draws attention to that specific slice, which can be useful when you want to highlight certain data points.
Another important aspect of pie charts is color. By default, Matplotlib assigns colors automatically, but you can specify your own color palette as well. Here’s how:
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
plt.pie(sizes, labels=labels, colors=colors)
plt.axis('equal')
plt.show()
In this example, we define a list of colors that correspond to each slice. This can help in making your chart visually appealing and aligned with any specific branding or thematic requirements.
Exploring these basics will set a solid foundation for more complex visualizations. Once you’re comfortable with the fundamentals, you can move on to more advanced techniques, such as adding legends, customizing fonts, or integrating with other data visualization libraries for enhanced functionality. It’s all about understanding how to manipulate the data and present it in a way that tells a story.
As you delve deeper into pie charts, consider how they fit within the broader context of your data visualizations. Are they the best choice for your data? Sometimes, bar charts or line graphs might provide clearer insights. Always think critically about the best visual representation for your data sets.
Anker USB C to USB C Cable, Type-C 60W Fast Charging Cable (6 FT, 2Pack) for iPhone 17 Series, iPad mini 6 and More (Black)
Now retrieving the price.
(as of July 9, 2026 13:58 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Customizing your pie charts for better visualization
To enhance readability, adding percentage labels to each slice is a common step. Matplotlib allows you to do this easily by using the autopct parameter. You can specify a format string or a function to customize how the percentages appear.
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%')
plt.axis('equal')
plt.show()
This will place the percentage value inside each slice, formatted to one decimal place. If you want more control, such as rounding differently or adding suffixes, you can define a function:
def make_autopct(values):
def my_autopct(pct):
total = sum(values)
val = int(round(pct*total/100.0))
return f'{pct:.1f}%n({val})'
return my_autopct
plt.pie(sizes, labels=labels, colors=colors, autopct=make_autopct(sizes))
plt.axis('equal')
plt.show()
This function shows both the percentage and the absolute value inside each slice, which can be more informative depending on your audience.
Another way to enhance your pie chart is by adding a shadow or changing the start angle to rotate the chart for better alignment. Shadows add depth, making the chart appear less flat:
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)
plt.axis('equal')
plt.show()
Here, startangle=140 rotates the pie chart so that the first slice starts at 140 degrees, which can help in positioning the largest slice or making the chart more visually balanced.
Sometimes, the default font size for labels and percentages might be too small or large for your needs. You can customize font properties by passing a dictionary to the textprops parameter:
text_props = {'fontsize': 14, 'color': 'navy'}
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', textprops=text_props)
plt.axis('equal')
plt.show()
This adjusts the font size and color for all text elements in the pie chart, making it easier to match your chart’s style to the rest of your presentation or report.
If your dataset has many categories, the pie chart can become cluttered. One technique to keep it clean is to group smaller slices into an “Other” category. Here’s a quick example of how to do that:
import numpy as np
sizes = [15, 30, 45, 5, 3, 2]
labels = ['A', 'B', 'C', 'D', 'E', 'F']
threshold = 5
sizes_grouped = []
labels_grouped = []
other_sum = 0
for size, label in zip(sizes, labels):
if size < threshold:
other_sum += size
else:
sizes_grouped.append(size)
labels_grouped.append(label)
if other_sum > 0:
sizes_grouped.append(other_sum)
labels_grouped.append('Other')
colors_grouped = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'gray']
plt.pie(sizes_grouped, labels=labels_grouped, colors=colors_grouped, autopct='%1.1f%%')
plt.axis('equal')
plt.show()
This method consolidates all categories below the threshold into one slice labeled “Other,” preserving clarity without losing the overall picture.
Finally, when integrating pie charts into larger dashboards or reports, consider exporting them with higher resolution or vector formats. Matplotlib supports saving figures in formats like PNG, SVG, or PDF, which maintain quality across different display sizes:
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
ax.axis('equal')
plt.savefig('pie_chart.svg') # Vector format for scalability
plt.savefig('pie_chart.png', dpi=300) # High-res raster image
plt.show()
These options ensure your visualizations remain sharp whether they are viewed on a screen or printed in a report. The choice between raster and vector depends on your specific use case, but vector formats are generally preferable for professional presentations.
