Pandas数据框中的多个饼图

2024-04-26 22:50:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

df = pd.DataFrame({'REC2': {0: '18-24',
  1: '18-24',
  2: '25-34',
  3: '25-34',
  4: '35-44',
  5: '35-44',
  6: '45-54',
  7: '45-54',
  8: '55-64',
  9: '55-64',
  10: '65+',
  11: '65+'},
 'Q8_1': {0: 'No',
  1: 'Yes',
  2: 'No',
  3: 'Yes',
  4: 'No',
  5: 'Yes',
  6: 'No',
  7: 'Yes',
  8: 'No',
  9: 'Yes',
  10: 'No',
  11: 'Yes'},
 'val': {0: 0.9642857142857143,
  1: 0.03571428571428571,
  2: 0.8208955223880597,
  3: 0.1791044776119403,
  4: 0.8507462686567164,
  5: 0.14925373134328357,
  6: 0.8484848484848485,
  7: 0.15151515151515152,
  8: 0.8653846153846154,
  9: 0.1346153846153846,
  10: 0.9375,
  11: 0.0625}})

看起来是这样的:

enter image description here

我试图为每个年龄段创建一个单独的饼图。目前我使用的是硬编码版本,在那里我需要输入所有可用的箱子。然而,我正在寻找一个解决方案,可以在一个循环内完成这一点,或者自动分配正确的垃圾箱。这是我目前的解决方案:

df = data.pivot_table(values="val",index=["REC2","Q8_1"])
rcParams['figure.figsize'] = (6,10)
f, a = plt.subplots(3,2)
df.xs('18-24').plot(kind='pie',ax=a[0,0],y="val")
df.xs('25-34').plot(kind='pie',ax=a[1,0],y="val")
df.xs('35-44').plot(kind='pie',ax=a[2,0],y="val")
df.xs('45-54').plot(kind='pie',ax=a[0,1],y="val")
df.xs('55-64').plot(kind='pie',ax=a[1,1],y="val")
df.xs('65+').plot(kind='pie',ax=a[2,1],y="val")

输出:

enter image description here


Tags: 数据nodataframedfplotval解决方案ax
1条回答
网友
1楼 · 发布于 2024-04-26 22:50:47

我想你想要:

df.groupby('REC2').plot.pie(x='Q8_1', y='val', layout=(2,3))

更新:我看了一下,发现groupby.plot做了一件不同的事情。所以你可以试试for循环:

df = df.set_index("Q8_1")

f, a = plt.subplots(3,2)
for age, ax in zip(set(df.REC2), a.ravel()):
    df[df.REC2.eq(age)].plot.pie( y='val', ax=ax)

plt.show()

由此产生:

enter image description here

相关问题 更多 >