Search code examples
pythonannotationsplotlyplotly-pythonangle

Plotly: How to adjust annotation text angle for rectangles using `add_vrect()`?


In the following MWE:

import plotly.graph_objects as go

fig = go.Figure()
fig.add_vrect(
    x0 = 0,
    x1 = 1,
    opacity = .25,
    line_width = 0,
    fillcolor = 'black',
    annotation_text = 'Hola, cómo estás? Este es un texto muy largo y va mejor en vertical',
)
fig.show()

how can I rotate the text, like this?

enter image description here

I have tried adding textangle = -90 as an argument to add_vrect but it does not work.


Solution

  • You're close, but you'll have to use annotation_textangle like this:

    fig.add_vrect(x0=0.9, x1=2, annotation_text="vertical rectangle", annotation_position="top left", annotation_textangle = 90)

    Plot:

    enter image description here

    Complete code:

    import plotly.express as px
    
    df = px.data.iris()
    fig = px.scatter(df, x="petal_length", y="petal_width")
    fig.add_hline(y=0.9)
    fig.add_vrect(x0=0.9, x1=2, annotation_text="vertical rectangle",
                  annotation_position="top left",
                  annotation_textangle = 90,
                 )
    fig.show()