Creating stacked bar chart from dataframe

69 views Asked by At

I have a table with different scenarios in rows, and values associated with them in columns

Like this

| Scenario   |    A |     B |   C |
|:-----------|-----:|------:|----:|
| Scen1      |  6.5 | 0.125 |  52 |
| Scen2      | 16.5 | 1.125 | 152 |
| Scen3      | 26.5 | 2.125 | 252 |

I want to produce a stacked bar chart similar to this

i.e. I want three bars (one for each scenario Scen1, Scen2, Scen3), and for each bar to have three sections (to represent values from A, B, C)

I've tried the following, but can't work out how to pass the dataframe to px.bar correctly.

import pandas as pd
import plotly.express as px

df = pd.DataFrame()
dict1 = {'A': 6.5, 'B': 0.125, 'C': 52}
series1 = pd.Series(data=dict1, name='Scen1')
df = df.append(series1)
dict2 = {'A': 16.5, 'B': 1.125, 'C': 152}
series2 = pd.Series(data=dict2, name='Scen2')
df = df.append(series2)
dict3 = {'A': 26.5, 'B': 2.125, 'C': 252}
series3 = pd.Series(data=dict3, name='Scen3')
df = df.append(series3)
df.index.name = "Scenario"


fig = px.bar(df, x="Scenario", y=["A","B", "C"], title="Test")
fig.show()
1

There are 1 answers

0
jezrael On BEST ANSWER

Use DataFrame.melt for preprocessing data:

df = df.reset_index().melt('Scenario')
print (df)
  Scenario variable    value
0    Scen1        A    6.500
1    Scen2        A   16.500
2    Scen3        A   26.500
3    Scen1        B    0.125
4    Scen2        B    1.125
5    Scen3        B    2.125
6    Scen1        C   52.000
7    Scen2        C  152.000
8    Scen3        C  252.000


import plotly.express as px

fig = px.bar(df, x="Scenario", y="value", color="variable", title="Test")
fig.show()