You haven't provided a dataset, but I've been able to reproduce your problem with a subset of a similar dataset px.data.stocks
and an approach that resembles your use of px.scatter
. And I'm assuming that your data has a long format, but that's not too important. What's important is this:
- You're absolutely right, the text will be cut using
px.Scatter([...] text = <text>)
- There does surprisingly not seem to be a direct way to fix this.
- I've produced a work-around that's more than a bit hacky.
- The work-around turns this:
...into this:
The following snippet will reproduce the plot above. If this is something you can use, I'd be happy to elaborate on the details. But the short story is this: Faceted plots makes room for annotations made from add_annotations()
, but not from annotations using px.Scatter([...] text = <text>)
.
Complete code:
# imports
import pandas as pd
import plotly.express as px
import plotly.io as pio
# data
df = px.data.stocks()
df = df[df.columns[:4]]
df2 = pd.melt(df.iloc[0:3],
id_vars=['date'],
value_vars=df.columns[1:],
var_name='stock',
value_name='value')
# your approach
fig = px.scatter(df2, x="date", y="value", facet_col="stock", text = 'stock')
fig.update_layout(width=1200,title_text='Spread por rating y duración en el sector Utilities')
fig.update_traces(textfont_size=8, textposition='top right')
# annotations
for c, d in enumerate(fig.data):
for i, y in enumerate(d.y):
fig.add_annotation(x=d.x[i], y=d.y[i], text = str(d.x[i]),
font=dict(color="rgba(0,0,0,0)",size=10),
showarrow = False,
xanchor = 'left',
row = 1, col = c + 1
)
fig.write_image('c:plotlyplotssubnotation.pdf')
fig.show()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…