I am creating a simple script which reads over a CSV file column, creates a new column with categories and then produces a piechart. Currently the piechart has percents attached to each wedge.
How do I move the percents to the legend?
Is there a way to move the autopct='%1.1f%%'
parameter to the legend?
Here is an image showing the current pi chart output:
My python code along with the sample data are below.
import pandas as pd
import matplotlib.pyplot as plt
import os
# Setup file paths
file_name = "Software.csv"
dirname = os.getcwd()
file_path = os.getcwd() + "\" + file_name
df = pd.read_csv(file_path)
# Name output file
split_path = file_path[:-4]
output_file = split_path + "_output.csv"
def check_lines(x):
if 'Microsoft' in x:
return 'Microsoft'
elif 'Google' in x:
return 'Google'
elif 'Adobe' in x:
return 'Adobe'
elif 'Mozilla' in x:
return 'Mozilla'
elif 'Apple' in x:
return 'Apple'
elif 'Amazon' in x:
return 'Amazon'
else:
return 'Other'
# Create a new column series; Apply the function to it.
df['Category'] = df['Title'].apply(check_lines)
# Create output file
df.to_csv(output_file)
# -- Pi Chart Version 2 --
df2 = pd.read_csv(output_file)
df2val = df2.value_counts('Category')
# Create PI Chart
plot = df2val.plot.pie(y='Category', autopct='%1.1f%%', labeldistance=None, startangle=0)
plt.ylabel('')
plt.legend(title="Categories", bbox_to_anchor=(1.05,0.5), loc="center right", fontsize=10, bbox_transform=plt.gcf().transFigure)
# Save Pi Chart
plt.savefig(split_path + "_chart.png", bbox_inches="tight")
plt.show()
Sample Data:
Title
Amazon Chime
Mozilla Firefox
Adobe Photoshop
Adobe Photoshop
Adobe Photoshop
Adobe Photoshop
Adobe Reader
Adobe Reader
Adobe Reader
Adobe Reader
Adobe Reader
Adobe Reader
Adobe Reader
Apple Safari
Apple Safari
Apple Safari
Google Drive
Microsoft Word
Microsoft OneDrive
Wireshark
Notepad
Notepad
Notepad
7zip
7zip
7zip
7zip
7zip
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe InDesign
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
Adobe Bridge
2
Answers
You can compute the percentages as follows and add them to the legend:
You can store the index and values of your
df2
in string format and use it as yourplt.legend()
labels argument (e.g. assign the labels in a variable named legend and use it later).