how to label bins in pie chart?

192 views Asked by At

Participants could choose to which age group they belonged.

1 = '<18', 
2 = '18-24', 
3 = '25-34',
4 = '35-44',
5 = '45-54',
6 ='55-60', 
7 = '>60'

data_age_sum = [(2:193), (3:126), (4:16), (5:6), (1:3), (6:1), (7:0)]



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

labels = '<18', '18-24', '25-34', '35-44', '45-54', '55-60', '>60'
fig, ax = plt.subplots(1, 1)
ax.hist(data_age_group_sum, bins=7)
ax.set_xlabel('age groups')
ax.set_ylabel('y-label')
plt.title('What age group do you belong to?')
plt.show()

I would like to label the bins (on the x-axis): bin1 = '<18' and so on. On top of the bins I would like the percentage of the people that have actually chosen the corresponding bin.

1

There are 1 answers

2
Abhishek Pawar On
1 = '<18', 
2 = '18-24', 
3 = '25-34',
4 = '35-44',
5 = '45-54',
6 ='55-60', 
7 = '>60'

data_age_sum = [(2:193), (3:126), (4:16), (5:6), (1:3), (6:1), (7:0)]

First thing is that's this is wrong way to create dataframe in python. If you want to create a pie chart, you need list of values and list of labels.

import matplotlib.pyplot as plt
sizes = [3, 193, 126, 16, 6, 1, 0]
labels = ['<18', '18-24', '25-34', '35-44', '45-54', '55-60', '>60']

And then you give these arguments to following function.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, autopct='%1.1f%%')

Output

If you want the histgram :

import matplotlib.pyplot as plt
import seaborn as sns

labels = ['<18', '18-24', '25-34', '35-44', '45-54', '55-60', '>60']
values = [3, 193, 126, 16, 6, 1, 0]
percentage = [x/sum(sizes)*100 for x in values]
ax = sns.barplot(x=labels, y=values)
patches = ax.patches
for i in range(len(patches)):
   x = patches[i].get_x() + patches[i].get_width()/2
   y = patches[i].get_height()+.05
   ax.annotate('{:.1f}%'.format(percentage[i]), (x, y), ha='center')
plt.show()

Output2