Plotly: How to set position of plotly.express chart with facet?

Viewed 3257

Is there a way to change the title position chart plotted with

fig=px.histogram(df,x='x',facet_row='Date',color='c',
             barmode='overlay',facet_col='number',height=500)
for a in fig.layout.annotations:
    a.text = a.text.split("=")[1]
fig.show()

from right to middle of each subplots?

enter image description here

1 Answers

I'm not 100% sure what you want to move where, but it sounds like you'd like the dates to the right there to pop up in the middle of the chart between the facets. In the structure of the figure, those are annotations. And you can put them anywhere you'd like, but how and where will depend on the structure of your particular figure. Since you haven't provided a dataset, I'll show you some general principals using an example from the plotly epress docs that should help you out. If you provide a dataset and fully working code, I'll be able to help you with the details.

Plot 1:

enter image description here

Code 1:

import plotly.express as px
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", facet_row="time", facet_col="day", color="smoker", trendline="ols",
          category_orders={"day": ["Thur", "Fri", "Sat", "Sun"], "time": ["Lunch", "Dinner"]})
fig.show()

Here, the elements corresponding to the ones you'd like to move are 'time=Lunch' and 'time=Dinner'. So in this case, the elements can be placed wherever you'd like along the x-axis like this:

Code: 2

for i, a in enumerate(fig['layout']['annotations']):
  if a['text'][:4]=='time':
    a['x']=0.475
    a['font']=dict(size = 10, color='rgba(255,0,200,0.8)')
    print(a)
fig.show()

Plot: 2

enter image description here

I know this is a bit hacky approach, but I hope you'll find it useful.

Related