Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

plotly

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

like image 539
Steve.Gao Avatar asked Nov 15 '25 13:11

Steve.Gao


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.

like image 164
vestland Avatar answered Nov 17 '25 08:11

vestland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!