使用Plotly绘制堆叠条形图报错hasattr(): attribute name must be string
解决Plotly堆叠条形图报错"hasattr(): attribute name must be string"的方案
错误根源:访问多级索引列的方式有误。当数据框为多级列索引时,不能直接用
gdp['IMF[1][13]', 'Estimate'],需将列名组合成元组进行访问。修改后的代码:
import plotly.express as px # 用元组指定多级列索引 fig = px.bar(gdp, x='UN Region', y=('IMF[1][13]', 'Estimate'), color='Country/Territory') fig.show()
- 备选写法(更清晰定位列):
import plotly.express as px # 明确指定目标列 target_column = ('IMF[1][13]', 'Estimate') fig = px.bar(gdp, x='UN Region', y=gdp.loc[:, target_column], color='Country/Territory') fig.show()
- 额外提示:可通过
print(gdp.columns)查看数据框的列结构,确认是否为多级索引,避免因列名格式问题引发错误。
内容的提问来源于stack exchange,提问作者rerecodes
相关产品推荐
相关产品推荐

