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
To install Matplotlib, you can use pip as well.
pip install matplotlib
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()
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()
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)
Nice