hi guys,
how can i reproduce the following graph in plotly?
my data looks like:
i have tried the following:
import plotly.express as px
fig = px.bar(df, x="year", y=["predicted","actual"], color='risk, barmode='stack',
height=400)
fig.show()
but i am not getting two separate bar plots for predicted vs actual. how can i do this??
@Emanuele would appreciate your help
To my knowledge you cannot do multi-category axis directly with plotly.express
and youβll have to go through the plotly.graph_objects
api.
If you reshape your data to look like this:
df = df.melt(id_vars=["year", "risk"], value_vars=["predicted", "actual"])
You could then use the following:
import plotly.graph_objs as go
fig = go.Figure()
for risk in ["low", "medium", "high"]:
tmp_df = df.query(f"risk == '{risk}'")
fig.add_trace(
go.Bar(
x=[tmp_df["year"], tmp_df["variable"]], y=tmp_df["value"], name=risk,
)
)
fig.update_layout(barmode="stack", height=400, width=800, margin=dict(b=60, t=20, l=20, r=20))
fig.show()
Which would give you the expected figure:
@RenaudLN many thanks for this! for some reason i do not get solid colours like you have above, i get faint lines through my bar chart - how can i remove this?
You can set the traces marker opacity:
fig.update_traces(marker_opacity=1)
@RenaudLN thank you it does not work though:
Then set the opacity in go.Bar?
go.Bar(..., marker=dict(opacity=1))
@RenaudLN i tried that i stil get the above graph
Both options work for me, maybe try updating your version of plotly?
@RenaudLN thanks i have the latest oneβ¦ i think what is happening is that when i hover over the bar the fainter parts of the barchart refer to a lower value and the more dense the colour i.e more opaque the stronger the fillβ¦