I'm working on bar chart using plotly express. I'd like to use discrete colours and set the opacity of each bar individually. At the moment I'm using the following code:
import plotly.express as px
df1 = pd.DataFrame(dict(score=[93.3, 93.3, 92, 88], model=['model1', 'model2', 'model3', 'model4']))
fig = px.bar(df1, x='score', y='model', color='model',
color_discrete_map={
"model1": "gray",
"model2": "rgb(255, 10, 10)",
"model3": "rgb(255, 10, 10)",
"model4": "rgb(255, 10, 10)"},
opacity=[1, 1, 0.1, 0.1])
fig.update_layout(xaxis_range=[80,100], xaxis_title='Score', yaxis_title='')
fig.show()
To generate the plot below:
I've tried adding separate opacities using a list of values, but that doesn't seem to work. Instead, plotly takes the first value in the list and applies it to all the bar charts.
How can I add opacity to each bar individually?
I have not verified that this technique works for all plotly, but you can set the alpha value in the format 'rgba(255,10,10,0.5)' in the color specification.
import plotly.express as px
import pandas as pd
df1 = pd.DataFrame(dict(score=[93.3, 93.3, 92, 88], model=['model1', 'model2', 'model3', 'model4']))
fig = px.bar(df1, x='score', y='model', color='model',
color_discrete_map={
"model1": "gray",
"model2": "rgb(255, 10, 0)",
"model3": "rgba(255, 10, 10, 0.5)",
"model4": "rgba(255, 10, 10, 0.3)"},
#opacity=[1, 1, 0.1, 0.1]
)
fig.update_layout(xaxis_range=[80,100], xaxis_title='Score', yaxis_title='')
fig.show()