Plotly并列饼图子图异常:第二列子图重复显示
问题解决:Plotly并列饼图子图重复问题
错误原因分析
- 嵌套循环导致重复添加:你在外层遍历食物营养分组
lst的同时,又嵌套遍历了性别热量摄入分组gen,这会导致每个食物对应的行,都重复添加了所有性别分组的饼图,最终第二列每个子图都是最后一次添加的内容,看起来完全重复。 - 行数设置错误:
rows=22完全不符合实际数据量,你的数据只有2种食物,应该设置为rows=len(lst)。 - 列名拼写错误:代码里写的
d['Nutritients']多了一个字母,原DataFrame的列名是Nutrients,不修正会报错。
修改后的完整代码
import plotly.graph_objects as go from plotly.subplots import make_subplots # 假设ax和daily_calories_intake数据已正确加载 lst = list(ax.groupby('Item')) gen = list(daily_calories_intake.groupby('Item')) rows = len(lst) # 实际行数等于食物种类数 cols = 2 subplot_titles = [l[0] for l in lst] # 生成对应行数的specs,避免重复引用问题 specs = [[{'type':'domain'}, {'type':'domain'}] for _ in range(rows)] fig = make_subplots( rows=rows, cols=cols, subplot_titles=subplot_titles, specs=specs) # 去掉内层循环,按索引对应两个分组的数据 for i, (food_nutrient, gender_intake) in enumerate(zip(lst, gen)): d = food_nutrient[1] m = gender_intake[1] # 修正列名拼写:Nutritients -> Nutrients 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 ) fig.update_layout( autosize=True, height=800*rows, # 根据行数动态调整高度 showlegend=True, margin={"l":0,"r":0,"t":100,"b":0} ) fig.show()
关键修改点
- 用
zip(lst, gen)同时遍历两个分组列表,确保每个食物对应正确的性别摄入数据,去掉多余的内层循环。 - 行数改为动态获取
len(lst),适配数据量。 - 修正列名拼写错误,避免KeyError。
- 高度设置为
800*rows,根据实际行数调整,避免原代码中8000的过高高度。
内容的提问来源于stack exchange,提问作者sarah444
相关产品推荐
相关产品推荐

