I am trying to make a what is a simple plot in excel but can’t figure out how to do it in plotly.
I’ve tried
px.bar(df, x=['A','B','D','E'], color='date')
but gives a key error.
I am trying to make a what is a simple plot in excel but can’t figure out how to do it in plotly.
px.bar(df, x=['A','B','D','E'], color='date')
but gives a key error.
If your data was in a long format, you could use this:
import pandas as pd
import plotly.express as px
categories = ['A','A','B','B','D','D','E','E']
values = [0,20,0,20,80,40,20,0]
dates = ['2022-12-05','2022-12-08','2022-12-05','2022-12-08','2022-12-05','2022-12-08','2022-12-05','2022-12-08']
df = pd.DataFrame({'date':dates,
'cat':categories,
'val':values
})
print (df)
fig = px.bar(df, x='cat', y='val', color='date', barmode='group')
fig.show()
To convert your data from wide to long you can do:
df_melted = pd.melt(df,
id_vars=['date'],
var_name='cat',
value_name='val')
print (df_melted)
So the full code with the current data would be:
import pandas as pd
import plotly.express as px
Acol = [0,20]
Bcol = [0,20]
Dcol = [80,40]
Ecol = [20,0]
dates = ['2022-12-05','2022-12-08']
df = pd.DataFrame({'date':dates,
'A':Acol,
'B':Bcol,
'D':Dcol,
'E':Ecol
})
print(df)
df_melted = pd.melt(df,
id_vars=['date'],
var_name='cat',
value_name='val')
print (df_melted)
fig = px.bar(df_melted, x='cat', y='val', color='date', barmode='group')
fig.show()
Resulting in:
Hi Adam, thanks for your answer, seems like melting the DF is the way to go.
I still get a key error for the Timestamp as if they were not recognized by plotly, do you know why?
I fixed this by parsing the date to str with .astype()