Skip to content

Instantly share code, notes, and snippets.

@CatChenal
Last active October 28, 2021 20:08
Show Gist options
  • Save CatChenal/e060bb88e679b0e31f35425be625d149 to your computer and use it in GitHub Desktop.
Save CatChenal/e060bb88e679b0e31f35425be625d149 to your computer and use it in GitHub Desktop.
Pandas pie plot with percentages and values on wedges

Output:

pie

Code:

import pandas as pd
import matplotlib.pyplot as plt

df1 = pd.DataFrame({'sizes':[75, 30, 45, 10]},
                    index=['Frogs', 'Hogs', 'Dogs', 'Logs'])
tot = df1.sizes.sum()

ax = df1.plot.pie(y='sizes',
                  autopct=lambda p:f'{p/100:.2%}\n({round(p*tot/100.):.0f})',
                  title=f'Proportion of each class (N={tot})',
                  figsize=(5,5),
                  label='',
                  legend=False);

# Save locally:
plt.savefig('pd_pie.png')

Note: The output image appears inline after several steps:

  1. Run the code block locally to obtain the image
  2. Create gist with initial code above (only the code block)
  3. Drop the image file in a comment to the gist & copy the link
  4. Edit the gist file by adding the copied (markdown) link before/after the code block & update
  5. Delete the comment

(I prepended the image link to the code block because I wanted the image visible in my list of gists.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment