How to prevent axis rescale when trace hidden

I have a graph with multiple traces. When you click a trace in the legend to hide it or double click to hide all the other traces, the graph axes rescale their limits based on the trace(s) still visible. I would like to prevent this behavior. I still wish to allow panning, zooming, etc…

1 Like

Hi @millercommamatt, if you set explicitely the range of axis as below then the axis won’t change when hiding traces in the legend

import plotly.graph_objects as go
fig = go.Figure()
fig.add_scatter(x=[1, 3], y=[5, 4])
fig.add_scatter(x=[1, 10], y=[5, 4])
fig.update_layout(xaxis_range=(0, 11))

Is there really no other solution than to loop through 20+ traces to find the absolute minimum and maximum values?

Just following up this question as I’m facing this issue when plotting a timeline with plotly express. When I try and hide items using the legend so that I can focus on the items I want to see, the whole plot rescales making it hard to work with.

I see that you can set the axis ranges, but can’t see anywhere how I set the axis range with a categorical axis that I have with my timeline.

Any help suggestions here would be appreciated.

To set ranges for a categorical axis, the ranges work as follows:

If the axis type is “category”, it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears.

So if you had 10 categories and you wanted to fix that range: layout.xaxis.range = [0, 9]

Hi @millercommamatt, thanks for the info. I found this shortly after posting my message and then ran into another problem. If hiding legend entries causes one of the categories to disappear, the mapping from category → number resets and whilst the axis size stays the same, everything moves around.

Using the example from the docs

import as px
import pandas as pd

df = pd.DataFrame([
dict(Task=“Job A”, Start=‘2009-01-01’, Finish=‘2009-02-28’, Resource=“Alex”),
dict(Task=“Job B”, Start=‘2009-03-05’, Finish=‘2009-04-15’, Resource=“Alex”),
dict(Task=“Job C”, Start=‘2009-02-20’, Finish=‘2009-05-30’, Resource=“Max”)

fig = px.timeline(df, x_start=“Start”, x_end=“Finish”, y=“Task”, color=“Resource”)
fig.update_xaxes(range=[“2008-12-25”, “2009-07-01”])

The y range is shifted by 0.5 as 0, 1, 2 seems to be the middle of the horizontal bars so the range needs to begin a bit lower.

For my use case, I’ve turned off interactivity with the legend for now.