Controlling the range of the y-axis in Plotly is essential for effectively visualizing your data. This is how to set the y-axis range for various plot types in Plotly.
1. Setting the Y-Axis Range for the Entire Figure
The most common way to set the y-axis range is to use the yaxis
attribute within the layout
of your figure.
import plotly.graph_objects as go
fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[4, 5, 6])])
fig.update_layout(yaxis_range=[2, 8]) # Set y-axis range from 2 to 8
fig.show()
This code creates a simple scatter plot and then uses fig.update_layout(yaxis_range=[2, 8])
to set the y-axis range from 2 to 8. The first value in the list is the minimum, and the second value is the maximum.
2. Setting the Y-Axis Range for Specific Subplots (if applicable)
If you have subplots, you can set the y-axis range for each subplot individually by referencing them by their ID (e.g., ‘yaxis1’, ‘yaxis2’).
import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(rows=2, cols=1)
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1)
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[7, 8, 9]), row=2, col=1)
fig.update_layout(
yaxis1_range=[2, 8], # Range for the first subplot
yaxis2_range=[5, 10] # Range for the second subplot
)
fig.show()
3. Setting the Y-Axis Range Automatically (using autorange)
Plotly can automatically determine the y-axis range based on the data. However, you can also use the autorange attribute to explicitly tell Plotly to recalculate the range. This is useful if you’ve added or modified data and want to update the axis limits.
import plotly.graph_objects as go
fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[4, 5, 6])])
fig.update_layout(yaxis_autorange=True) # Automatically set the y-axis range
fig.show()
You can also set yaxis_autorange to 'reversed'
to reverse the direction of the y-axis.
4. Setting the Y-Axis Range with range (alternative syntax)
You can also use the range attribute directly within the yaxis dictionary:
import plotly.graph_objects as go
fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[4, 5, 6])])
fig.update_layout(yaxis=dict(range=[2, 8]))
fig.show()
5. Setting the Y-Axis Range with fixedrange (to prevent user interaction)
You can use fixedrange to prevent the user from zooming or panning the y-axis. This is useful when you want to ensure the user sees a specific range of data.
import plotly.graph_objects as go
fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[4, 5, 6])])
fig.update_layout(yaxis_fixedrange=[2, 8]) # User can't zoom/pan y-axis
fig.show()
Which Method to Use?
- Use
yaxis_range
(or yaxis=dict(range=[…])) for explicitly setting the y-axis range. This is the most common and direct approach. - Use
yaxis_autorange
to let Plotly automatically determine the range. - Use
yaxis1_range
,yaxis2_range
, etc., for setting ranges of individual subplots. - Use yaxis_fixedrange to prevent user interaction with the y-axis range.