如何在饼图中标记垃圾箱?

问题描述 投票:0回答:1

参与者可以选择他们所属的年龄组

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()

我想标记垃圾箱(在 x 轴上):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.

python pie-chart bins
1个回答
1
投票
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)]

首先,这是在 python 中创建数据框的错误方法。 如果要创建饼图,则需要值列表和标签列表。

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']

然后将这些参数传递给以下函数。

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

Output

如果你想要直方图:

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()

© www.soinside.com 2019 - 2024. All rights reserved.