0
votes

I am trying to build a stacked bar chart with plotly in Python.

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:

single positional indexer is out-of-bounds

When I do it for just 10 trees or less everything looks fine.

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..

1
Please, provide the DataFrame, as well. Thanks.sentence

1 Answers

0
votes

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. 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.