AaronDT
AaronDT

Reputation: 4050

Multiple pie charts from pandas dataframe

I have the following dataframe:

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

which looks like this:

enter image description here

I am trying to create a separate pie chart for each age bin. Currently I am using a hardcoded version, where I need to type in all the available bins. However, I am looking for a solution that does this within a loop or automatically asigns the correct bins. This is my current solution:

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

Output:

enter image description here

Upvotes: 1

Views: 2882

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

I think you want:

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

Update: I take a look and it turns out that groupby.plot does a different thing. So you can try the for loop:

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

which yields:

enter image description here

Upvotes: 2

Related Questions