0

I have a simple .csv that I'd like to render PNG files of pie charts from, which from other StackOverflow questions I've gotten mostly working.

The one change I can't figure out is how to show both values and percentages on the pie slices. There's a similar answer here, but not for a CSV dataframe and I can't grok how to adapt this to fit my dataframe.

My interactive session commands to generate the pie chart follow:

import pandas as pd
from matplotlib.pyplot import pie, axis, show
df = pd.read_csv('syntheticdata.csv')
# show the csv: print(df.head())
sums = df.groupby(df["category"])["capacity-tb"].sum()
axis('equal');
pie(sums, labels=sums.index, autopct='%.0f%%');
show()

My pie chart is almost how I want it aside from missing the actual numbers behind the percentages.
pie chart example

My synthetic test data csv is available below:

svm,capacity-tb,available-tb,category
cifs-share,54,28,Fileshare
foo-cifs,19,4,Project Data
VM02,109,49,Virtual Machine Storage
nfs01,40,22,Project Data
VM-02,65,31,Virtual Machine Storage
VM-01,65,44,Virtual Machine Storage
nfs-foo-01,43,29,Project Data
cifs-project-01,20,1,Project Data
nfs-foo-01_dest_0,21,3,Replication & Disaster Recovery
cifs-project-01_dest_0,19,1,Replication & Disaster Recovery
nfs01-dr,27,7,Replication & Disaster Recovery
cifs-share-dr,60,20,Replication & Disaster Recovery
VM02-dr,123,52,Replication & Disaster Recovery
foo-cifs-dr,19,4,Replication & Disaster Recovery

1 Answers1

1

Modify the absolute_value function:

import matplotlib.pyplot as plt
import numpy as np

sums = df.groupby(df["category"])["capacity-tb"].sum()
pie, ax = plt.subplots(figsize=[10, 6])


def absolute_value(val):
    return f'{np.round(val/100.*sums.values.sum(), 0)} {round(val,1)}%'


plt.pie(x=sums, autopct=absolute_value, explode=[
        0.05]*4, labels=sums.index, pctdistance=0.5)

OUTPUT:

enter image description here

Nk03
  • 14,699
  • 2
  • 8
  • 22