pandas 用两个 Dataframe 并排绘制饼图子图

xkftehaa  于 2023-01-19  发布在  其他
关注(0)|答案(1)|浏览(156)

我有两个表,我试图并排创建子情节,第一个数字工作正常,但第二个数字是相同的每一行。

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

每日卡路里摄入量

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

我试着把饼图并排,这是我的代码:

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

我想不出怎么解决这个问题。

v8wbuo2f

v8wbuo2f1#

嵌套循环在这里不起作用,因为你要覆盖图形。用zip创建一个单一的循环会起作用:

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)

编辑:你的标题看起来不对,调换一下情节,把图表放在相应的标题下:

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)

输出:

相关问题