PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, April 23, 2022

[FIXED] How do I create a pie chart using categorical data in matplotlib?

 April 23, 2022     matplotlib, pandas, pie-chart, python     No comments   

Issue

I have data as follows:

ID  Gender  Country  ...
1   Male    UK
2   Female  US
3   Male    NZ
4   Female  UK
...

There are only 2 options for gender and 3 for country. I would like to create a seperate pie chart for both "Gender" and "Country" to show how many times each option shows up in the data but I'm quite confused about how to do so.

The data is stored in a pandas dataframe.

Any and all help is much appreciated!


Solution

Here is an approach using pandas:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

def label_function(val):
    return f'{val / 100 * len(df):.0f}\n{val:.0f}%'

N = 50
df = pd.DataFrame({'country': np.random.choice(['UK', 'US', 'NZ'], N),
                   'gender': np.random.choice(['Male', 'Female'], N)})

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))

df.groupby('country').size().plot(kind='pie', autopct=label_function, textprops={'fontsize': 20},
                                  colors=['tomato', 'gold', 'skyblue'], ax=ax1)
df.groupby('gender').size().plot(kind='pie', autopct=label_function, textprops={'fontsize': 20},
                                 colors=['violet', 'lime'], ax=ax2)
ax1.set_ylabel('Per country', size=22)
ax2.set_ylabel('Per gender', size=22)plt.tight_layout()
plt.show()

example plot

PS: To just show the percentage, use autopct='%1.0f%%'.



Answered By - JohanC
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing