DEV Community

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

Posted on • Originally published at pleypot.com

2

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

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (1)

Collapse
 
sreno77 profile image
Scott Reno

Nice

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay