【问题标题】:Stacked bar chart with plotly带有 plotly 的堆积条形图
【发布时间】:2020-04-04 09:03:51
【问题描述】:

我正在尝试在 Python 中使用 plotly 构建堆积条形图。

我的目标是为哥本哈根的每个城市区域制作一个酒吧,将不同的树木类型堆叠在一起。我可以一直运行我的代码直到第 10 棵树,之后我得到一个 IndexError:

单个位置索引器超出范围

当我只为 10 棵树或更少的树做这件事时,一切看起来都很好。

我的代码如下所示

    ## df is a dataframe where each row is a tree type
    ## and each column a city district

    x = df.columns ## district names
    trees = df.index ## tree names

    for i in range(0,len(trees)):
        if i == 0:
            fig = go.Figure(go.Bar(x=x, y=df.iloc[:,i].values, name = trees[i]))
        else:
            fig.add_trace(go.Bar(x=x, y=df.iloc[:,i].values, name = trees[i]))

    fig.update_layout(barmode='stack')
    fig.show()

我似乎无法弄清楚错误是什么..

【问题讨论】:

  • 请同时提供 DataFrame。谢谢。

标签: python python-3.x plotly bar-chart stacked-chart


【解决方案1】:

乍一看,您似乎在混淆列和行。如果 Kaupmannahöfn 只有 9 个区,但您有 10 种或更多的树类型,那么您可能应该使用 y=df.iloc[i,:] 来按区绘制树的数量。但可以肯定的是,请提供数据框的尺寸、从数据框中选择的几行以及前 9 种树类型的条形图。

【讨论】:

  • 太棒了!切换到y=df.iloc[i,:] 解决了问题!一定是盯着它看太久了,太感谢了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 2021-03-09
  • 2015-09-28
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
相关资源
最近更新 更多