Skip to main content

Pie Chart

## Introduction

Visualizing data is a crucial part of data analysis. One of the most popular ways to visualize data is by using pie charts. In this tutorial, we'll learn how to create pie charts using the pandas library in Python.

## Prerequisites

You should have Python and pandas installed. Also, you should be familiar with basic pandas operations like creating dataframes and series.

## Getting Started

First, let's import the necessary libraries:

```python
import pandas as pd
import matplotlib.pyplot as plt

Creating a DataFrame

To illustrate the creation of a pie chart, we first need a DataFrame. Let's create a simple one:

data = {
'Fruits': ['Apple', 'Banana', 'Orange', 'Grapes', 'Blueberries'],
'Quantity': [30, 15, 40, 20, 25]
}

df = pd.DataFrame(data)

This DataFrame represents the quantity of different fruits.

Basic Pie Chart

Pandas provides the plot.pie() function to create pie charts. Let's create a basic pie chart of the 'Quantity' column:

df['Quantity'].plot.pie(autopct='%1.1f%%')
plt.show()

The autopct parameter allows us to display the percentage distribution on the pie chart. '%1.1f%%' means that the percentages will be displayed with 1 number after the decimal.

Customizing Your Pie Chart

You might want to customize your chart to make it more informative and visually appealing. Here are some ways to do that:

Adding a Title

You can add a title using plt.title():

df['Quantity'].plot.pie(autopct='%1.1f%%')
plt.title('Fruit Quantity Distribution')
plt.show()

Adding Labels

Currently, our chart only displays the indices of our data. We can replace these with the names of the fruits using the labels parameter:

df['Quantity'].plot.pie(autopct='%1.1f%%', labels=df['Fruits'])
plt.title('Fruit Quantity Distribution')
plt.show()

Exploding Slices

You can "explode" a slice (i.e., draw it slightly out of the pie) to highlight it. To do this, pass a list of fractions to the explode parameter. Each fraction corresponds to the distance to "explode" each slice:

explode = (0.1, 0, 0, 0, 0)  # only "explode" the first slice (i.e., 'Apple')
df['Quantity'].plot.pie(autopct='%1.1f%%', labels=df['Fruits'], explode=explode)
plt.title('Fruit Quantity Distribution')
plt.show()

Conclusion

That's it! You've learned how to visualize data using pie charts in pandas. This is a powerful tool that can help make your data analysis more insightful and understandable. Happy data analyzing!