data visualization
pie chart
Python
dictionary
plotting

Plotting a pie chart out of a dictionary

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

A Python dictionary is a natural source for a pie chart because it already maps category names to numeric values. The main job is turning the dictionary into a list of labels and a list of sizes, then passing those to matplotlib.pyplot.pie with options that make the chart readable.

Converting a Dictionary Into Pie Chart Inputs

Suppose you have category totals stored in a dictionary:

python
1sales = {
2    "Books": 35,
3    "Games": 25,
4    "Music": 15,
5    "Movies": 25,
6}

matplotlib does not plot dictionaries directly. It wants sequences, so extract keys and values in matching order.

python
1import matplotlib.pyplot as plt
2
3sales = {
4    "Books": 35,
5    "Games": 25,
6    "Music": 15,
7    "Movies": 25,
8}
9
10labels = list(sales.keys())
11sizes = list(sales.values())
12
13plt.pie(sizes, labels=labels)
14plt.show()

That is the minimum working example. The order of the keys and values stays aligned because both lists come from the same dictionary in the same iteration order.

Making the Pie Chart More Readable

Most real charts need at least percentages and equal aspect ratio.

python
1import matplotlib.pyplot as plt
2
3sales = {
4    "Books": 35,
5    "Games": 25,
6    "Music": 15,
7    "Movies": 25,
8}
9
10labels = list(sales.keys())
11sizes = list(sales.values())
12
13plt.figure(figsize=(6, 6))
14plt.pie(
15    sizes,
16    labels=labels,
17    autopct="%1.1f%%",
18    startangle=90,
19)
20plt.axis("equal")
21plt.title("Sales by category")
22plt.show()

The important options are:

  • 'autopct to display percentages'
  • 'startangle to rotate the chart into a cleaner position'
  • 'axis("equal") to keep the pie circular instead of stretched'

Sorting or Highlighting Important Categories

If the dictionary is large or built from aggregated data, it is often helpful to sort it before plotting.

python
1import matplotlib.pyplot as plt
2
3sales = {
4    "Books": 35,
5    "Games": 25,
6    "Music": 15,
7    "Movies": 25,
8}
9
10sorted_items = sorted(sales.items(), key=lambda item: item[1], reverse=True)
11labels = [label for label, _ in sorted_items]
12sizes = [value for _, value in sorted_items]
13explode = [0.08 if label == "Books" else 0 for label in labels]
14
15plt.figure(figsize=(6, 6))
16plt.pie(
17    sizes,
18    labels=labels,
19    explode=explode,
20    autopct="%1.1f%%",
21    startangle=90,
22)
23plt.axis("equal")
24plt.show()

The explode list offsets one slice from the center, which can be useful when one category deserves emphasis.

Handling Small or Many Categories

Pie charts become hard to read when there are too many categories or many tiny slices. In that case, combine small values into an Other bucket before plotting.

python
1def group_small_categories(data, threshold):
2    grouped = {}
3    other_total = 0
4
5    for label, value in data.items():
6        if value < threshold:
7            other_total += value
8        else:
9            grouped[label] = value
10
11    if other_total:
12        grouped["Other"] = other_total
13
14    return grouped
15
16sales = {
17    "Books": 35,
18    "Games": 25,
19    "Music": 15,
20    "Movies": 25,
21    "Posters": 3,
22    "Pins": 2,
23}
24
25plot_data = group_small_categories(sales, threshold=5)
26print(plot_data)

That preprocessing step often improves the final chart more than any styling option.

When a Pie Chart Is the Wrong Choice

A pie chart works best for a small number of parts that represent a whole. If you need accurate comparison across many categories, a bar chart is usually easier to read.

python
1import matplotlib.pyplot as plt
2
3sales = {
4    "Books": 35,
5    "Games": 25,
6    "Music": 15,
7    "Movies": 25,
8}
9
10plt.bar(sales.keys(), sales.values())
11plt.title("Sales by category")
12plt.show()

This is worth mentioning because many pie chart problems are really chart-selection problems.

Common Pitfalls

A common mistake is passing the dictionary itself to plt.pie and expecting it to understand labels automatically. Convert the dictionary into separate sequences first.

Another issue is misaligned labels and values. Always derive both from the same ordered sequence of items so category names match the correct slice sizes.

Too many slices is another frequent problem. Even technically correct pie charts can become unreadable when there are many tiny categories.

Finally, remember that pie charts represent proportions. Negative values or unrelated magnitudes usually indicate that a different chart type would be more appropriate.

Summary

  • Convert dictionary keys and values into label and size lists before plotting.
  • Use autopct, startangle, and axis("equal") for a cleaner result.
  • Sort or explode slices when one category should stand out.
  • Group tiny categories into Other when the chart gets crowded.
  • Prefer a bar chart when comparison matters more than part-to-whole display.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.