DEV Community

Cover image for How to Create Pie Chart in Python with Pandas
saim
saim

Posted on • Originally published at pleypot.com

How to Create Pie Chart in Python with Pandas

To create a pie chart in Python Pandas, you'll need to use the visualization library Matplotlib or another plotting library like Seaborn. First you need to install pandas and Matplotlib.

install python panda using pip.

pip install pandas
Enter fullscreen mode Exit fullscreen mode

To install Matplotlib, you can use pip as well.

pip install matplotlib
Enter fullscreen mode Exit fullscreen mode

Example 1

Creates a basic pie chart using the plt.pie() function from Matplotlib. The labels parameter is used to label each slice with the corresponding category, and autopct displays the percentage value for each slice.

import pandas as pd
import matplotlib.pyplot as plt

# Create a sample DataFrame
data = {'Category': ['A', 'B', 'C', 'D'], 'Value': [25, 35, 20, 15]}
df = pd.DataFrame(data)

# Plot the pie chart
plt.figure(figsize=(6, 6))
plt.pie(df['Value'], labels=df['Category'], autopct='%1.1f%%')
plt.axis('equal') # Ensure the pie chart is circular
plt.title('Sample Pie Chart')
plt.show()
Enter fullscreen mode Exit fullscreen mode

Pie Chart in Python with Pandas

Example 2

Pie Chart with Custom Colors.

import pandas as pd
import matplotlib.pyplot as plt

# Create a sample DataFrame
data = {'Category': ['Apple', 'Banana', 'Orange', 'Kiwi'], 'Value': [40, 25, 20, 15]}
df = pd.DataFrame(data)

# Define custom colors
colors = ['gold', 'yellowgreen', 'lightskyblue', 'lightcoral']

# Plot the pie chart
plt.figure(figsize=(8, 8))
patches, texts, autotexts = plt.pie(df['Value'], labels=df['Category'], colors=colors,
                  autopct='%1.1f%%', startangle=90)
plt.legend(patches, df['Category'], loc="best")
plt.axis('equal')
plt.tight_layout()
plt.title('Fruit Pie Chart')
plt.show()
Enter fullscreen mode Exit fullscreen mode

Pie Chart in Python with Pandas colors

Read Also

📝how to use python shlex subprocess with example
📝how to use python shlex quote with example
📝How to Get Index in Python For Loop

Top comments (1)

Collapse
 
sreno77 profile image
Scott Reno

Nice