Hiding text annotation when zooming in on a plotly graph

1.1k views Asked by At

The first graph below is the default view where I have inserted a text annotation to mark the line. When I zoom in though to see the (barely visible) bottom area of the graph, the text annotation still sticks but without the line and hence, making no sense. Is there a way I could hide it when the user zooms in?

enter image description here enter image description here

import pandas as pd
import plotly.graph_objects as go
world_df = pd.read_csv('https://raw.githubusercontent.com/vyaduvanshi/helper-files/master/world_df.csv')

fig = go.Figure()
fig.add_scatter(x=world_df.date, y=world_df.population, fill='tozeroy')
fig.add_scatter(x=world_df.date, y=world_df.total_cases, fill='tozeroy', mode='lines', line_color='#0099ff')
fig.add_scatter(x=world_df.date, y=world_df.herd_immunity_threshold)
fig.update_layout(annotations=[dict(x=0.5, y=0.7, xref='paper', yref='paper', showarrow=False,
                                    text='something something line')])
1

There are 1 answers

4
Derek O On BEST ANSWER

The parameters xref='paper' and yref='paper' will place the annotations relative the to chart instead of the actual coordinates. That means because you have y=0.7, your annotation will remain in the position 70% of the way between the bottom and top of the chart no matter how much you zoom. Instead you should set the yref='y' and then pass the coordinate to the parameter y (I set it to 5.222515 billion based on the trace of your original plot).

import pandas as pd
import plotly.graph_objects as go
world_df = pd.read_csv('https://raw.githubusercontent.com/vyaduvanshi/helper-files/master/world_df.csv')

fig = go.Figure()
fig.add_scatter(x=world_df.date, y=world_df.population, fill='tozeroy')
fig.add_scatter(x=world_df.date, y=world_df.total_cases, fill='tozeroy', mode='lines', line_color='#0099ff')
fig.add_scatter(x=world_df.date, y=world_df.herd_immunity_threshold)
fig.update_layout(annotations=[dict(x=0.5, y=5.222515*10**9, xref='paper', yref='y', showarrow=False,
                                    text='something something line')])
fig.show()

enter image description here