Plotting a Pie Chart Out of a Dictionary

Pie charts are a visually appealing way to represent data, especially when dealing with proportions or percentages of a whole. In this article, we will explore how to create a pie chart directly from a dictionary using Python’s popular library, Matplotlib.

1. Setting up the Environment

Before we dive into the code, ensure you have Matplotlib installed in your Python environment. If not, you can install it using pip:

pip install matplotlib

2. Preparing the Data

Let’s start with our dictionary containing data for the pie chart. In this example, we’ll represent the distribution of fruits in a basket:

fruit_counts = {"Apples": 5, "Oranges": 3, "Bananas": 7, "Grapes": 2}

3. Plotting the Pie Chart

Now, we will use Matplotlib to create our pie chart. The key is to extract the labels (fruit names) and the values (counts) from the dictionary.

import matplotlib.pyplot as plt

labels = list(fruit_counts.keys())
sizes = list(fruit_counts.values())

plt.pie(sizes, labels=labels, autopct="%1.1f%%", startangle=90)
plt.axis("equal")
plt.title("Fruit Distribution in the Basket")
plt.show()

4. Breakdown of the Code

  • **import matplotlib.pyplot as plt:** Import the pyplot module from Matplotlib, commonly aliased as ‘plt’.
  • **labels = list(fruit_counts.keys()):** Extract the keys (fruit names) from the dictionary and convert them to a list.
  • **sizes = list(fruit_counts.values()):** Extract the values (fruit counts) from the dictionary and convert them to a list.
  • **plt.pie(...):** This is the core function for creating the pie chart:
    • sizes: Provides the numerical data for each slice.
    • labels: Defines the labels for each slice.
    • autopct="%1.1f%%": Formats the percentage values displayed inside each slice (1 decimal place).
    • startangle=90: Sets the starting angle for the first slice (90 degrees is typically a good choice).
  • **plt.axis("equal"):** Ensures that the pie chart is drawn in a circle rather than an ellipse.
  • **plt.title(...):** Sets the title of the pie chart.
  • **plt.show():** Displays the created pie chart.

5. Output

Executing this code will produce a pie chart like this (the exact appearance might vary slightly depending on your environment):

  (Image of the pie chart showing fruit distribution with labels and percentages)

Conclusion

You’ve learned how to create a visually appealing pie chart from a dictionary using Matplotlib in Python. The flexibility of dictionaries makes it easy to store and represent diverse data sets, making pie charts a powerful tool for data visualization.

Leave a Reply

Your email address will not be published. Required fields are marked *