Home > Software design >  plotly pie subplots side by side with two dataframes
plotly pie subplots side by side with two dataframes

Time:01-18

I have two tables, and I am trying to create subplots side by side, the first figure works fine but the second figure is same in each row.

ax

          Item                                   Nutrients      value

0 Bacon & Cheese Whopper® Sandwich             Fat Calories     460.0
1 Bacon & Cheese Whopper® Sandwich             Total Carb (g)   50.0
2 Bacon & Cheese Whopper® Sandwich             Protein (g)      35.0
3 Bacon Cheeseburger                           Fat Calories     140.0
4 Bacon Cheeseburger                           Total Carb (g)   27.0
5 Bacon Cheeseburger                           Protein (g)      17.0

daily_calories_intake

          Item                               Gender_dv            value

0 Bacon & Cheese Whopper® Sandwich           dv_calories_men      48.8
1 Bacon & Cheese Whopper® Sandwich           dv_calories_women    47.7
2 Bacon Cheeseburger                         dv_calories_men      46.0
3 Bacon Cheeseburger                         dv_calories_women    45.2

I have tried to make pie plots side by side, this is my code:

lst = list(ax.groupby('Item'))
gen = list(daily_calories_intake.groupby('Item'))

rows = 22
cols = 2

subplot_titles = [l[0] for l in lst]
specs = [[{'type':'domain'},{'type':'domain'}]]*rows

fig = make_subplots(
        rows=rows,
        cols=cols,
        subplot_titles=subplot_titles,
        specs=specs)

for i, l in enumerate(lst):
    for j,k in enumerate(gen):
        d = l[1]
        m = k[1]
        fig.add_trace(
            go.Pie(labels = d['Nutritients'],
                   values = d['value']),row = i 1,col=1)
        fig.add_trace(
            go.Pie(labels = m['Gender_dv'],
                   values = m['value']),row = i 1,col=2)


fig.update_layout(autosize=True,height=8000, showlegend=True, margin= 
    {"l":0,"r":0,"t":100,"b":0})
fig.show()

I can't figure out how to solve this.

CodePudding user response:

The nested loop doesn't work here because you're overwriting the graph. Creating a single loop with zip would work:

for i, (l,k) in enumerate(zip(lst, gen)):
    d = l[1]
    m = k[1]
    fig.add_trace(
        go.Pie(labels = d['Nutrients'],
              values = d['value']),row = i 1,col=1)
    fig.add_trace(
        go.Pie(labels = m['Gender_dv'],
               values = m['value']),row = i 1,col=2)

Edit: your titles seem off, transpose the plots to get the charts under the corresponding titles:

for i, (l,k) in enumerate(zip(lst, gen)):
    d = l[1]
    m = k[1]
    fig.add_trace(go.Pie(labels=d['Nutrients'], values=d['value']), row=1, col=i 1)
    fig.add_trace(go.Pie(labels=m['Gender_dv'], values=m['value']), row=2, col=i 1)

Output:

enter image description here

  • Related