Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to set the range of Y-axis in Python Plotly?
Plotly is a powerful Python library for creating interactive visualizations. One common requirement is controlling the Y-axis range to better display your data or focus on specific value ranges.
Setting Y-axis Range with update_layout()
The most straightforward way to set the Y-axis range is using the update_layout() method with the yaxis_range parameter ?
import plotly.graph_objs as go import numpy as np # Set random seed for reproducible results np.random.seed(3) # Generate X-axis data (0 to 18, step 2) x_values = list(range(0, 20, 2)) # Generate random Y-axis data y_values = np.random.randn(10) # Create scatter plot with line mode fig = go.Figure(data=go.Scatter(x=x_values, y=y_values, mode='lines')) # Set Y-axis range from -3 to 3 fig.update_layout(yaxis_range=[-3, 3]) # Display the plot fig.show()
Alternative Method Using yaxis Dictionary
You can also set the Y-axis range using the yaxis dictionary approach ?
import plotly.graph_objs as go
import numpy as np
np.random.seed(3)
x_values = list(range(0, 20, 2))
y_values = np.random.randn(10)
# Create figure and set Y-axis range using yaxis dictionary
fig = go.Figure(data=go.Scatter(x=x_values, y=y_values, mode='lines'))
fig.update_layout(
yaxis=dict(range=[-2, 2])
)
fig.show()
Setting Range During Figure Creation
You can also specify the Y-axis range when creating the figure layout ?
import plotly.graph_objs as go
import numpy as np
np.random.seed(3)
x_values = list(range(0, 20, 2))
y_values = np.random.randn(10)
# Create figure with Y-axis range specified in layout
fig = go.Figure(
data=go.Scatter(x=x_values, y=y_values, mode='lines'),
layout=go.Layout(yaxis=dict(range=[-1, 1]))
)
fig.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
yaxis_range |
Sets min and max Y values | [-3, 3] |
yaxis=dict(range=[]) |
Alternative syntax | dict(range=[0, 10]) |
autorange |
Enable/disable auto-ranging |
True or False
|
Conclusion
Use update_layout(yaxis_range=[min, max]) to set Y-axis range in Plotly. This method gives you precise control over the visible data range and improves chart readability for your specific use case.
Advertisements
