how can I get colorbar for each facet_col? currently I am getting only one colorbar common for all facetcol.
Hi @sujeetomar, you can do so but itβs a bit cumbersome. First you have to tell plotly to use a different coloraxis for each facet and then you have to assign the colorbar itself. The following code works for two facets, since the y-position and the length of the colorbar is hard coded.
import plotly.express as px
# data
df = px.data.tips()
#create bas figure
fig = px.scatter(
df, x=df.index,
y='total_bill',
facet_row='sex',
color='total_bill'
)
#update traces --> each trace uses a different coloraxis
for trace, c_axis in zip(fig.data, ['coloraxis', 'coloraxis2']):
trace.update(marker={'coloraxis': c_axis})
# update layout --> plot colorbar for each trace, define colorscale
fig.update_layout(
coloraxis={
"colorbar": {
"x": 1,
"len": 0.5,
"y": 0.75,
'title': 'Female'
},
"colorscale": 'Blues'
},
coloraxis2={
"colorbar": {
"x": 1,
"len": 0.5,
"y": 0.25,
'title': 'Male'
},
"colorscale": 'Reds'
},
height=500,
width=700
)
creates:
I just noticed you asked for facet_colsβ¦
import plotly.express as px
# data
df = px.data.tips()
#create bas figure
fig = px.scatter(
df, x=df.index,
y='total_bill',
facet_col='sex',
color='total_bill',
facet_col_spacing=0.2
)
#update traces --> each trace uses a different coloraxis
for trace, c_axis in zip(fig.data, ['coloraxis', 'coloraxis2']):
trace.update(marker={'coloraxis': c_axis})
# update layout --> plot colorbar for each trace, define colorscale
fig.update_layout(
coloraxis={
"colorbar": {
"x": 0.4,
"len": 1.0,
"y": 0.5,
'title': 'Female'
},
"colorscale": 'Blues'
},
coloraxis2={
"colorbar": {
"x": 1,
"len": 1.0,
"y": 0.5,
'title': 'Male'
},
"colorscale": 'Reds'
},
height=500,
width=700
)
creates:
Thanks a lot for sharing the solution.
However this is too much of code. One of main USP of px is that, we can do more with less code.
looks like we need this enhancement. What is the way to do this.
Hi @sujeetomar
if you find a way to do that with less code, please let us know and post the solution here.
You could:
- search in the
plotly.express
docs for a solution, maybe I missed something and there is a built in function - create a function from of the given solution generalizing a bit.
- wait for a forum member to find a solution which involves less code
- open a feature request here and hope that this functionality gets developed