简体   繁体   English

带 plotly 的堆叠条形图

[英]Stacked bar chart with plotly

I am trying to build a stacked bar chart with plotly in Python.我正在尝试使用 Python 中的 plotly 构建堆积条形图。

My goal is to make a bar for each city district in Copenhagen where the different tree types are stacked.我的目标是为哥本哈根的每个城市区制作一个酒吧,其中不同的树木类型堆叠在一起。 I am able to run my code up until the 10th tree, after this I get an IndexError:我可以运行我的代码直到第 10 棵树,之后我得到一个 IndexError:

single positional indexer is out-of-bounds单个位置索引器超出范围

When I do it for just 10 trees or less everything looks fine.当我只为 10 棵树或更少的树做这件事时,一切看起来都很好。

My code looks like the following我的代码如下所示

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

I cannot seem to figure out what the bug is..我似乎无法弄清楚错误是什么..

At first glance, it seems like you you're mixing up columns and rows.乍一看,您似乎在混淆列和行。 If Kaupmannahöfn only has 9 districts, but you have 10 or more tree types, then you should probably use y=df.iloc[i,:] to plot the number of trees by districts.如果 Kaupmannahöfn 只有 9 个区,但您有 10 种或更多的树类型,那么您可能应该使用y=df.iloc[i,:]到 plot 按区划分的树数。 But to be sure, please provide the dimensions of your dataframe, a select few lines from the dataframe and the barchart for the first 9 tree types.但可以肯定的是,请提供 dataframe 的尺寸,select 几行来自 dataframe 和前 9 个树类型的条形图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM