Plotly: How to set the range of the y axis?
Update for newer versions
When setting up a figure you can use plotly's magic underscore notation and specify layout_yaxis_range=[<from_value>, <to_value>]
like this:
fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'), layout_yaxis_range=[-4,4])
Or if you've already got a figure named fig
, you can use:
fig.update_layout(yaxis_range=[-4,4])
And:
fig.update(layout_yaxis_range = [-4,4])
Or:
fig.update_yaxes(range = [-4,4])
Figure:
Complete code:
# importsimport pandas as pdimport plotly.graph_objs as goimport numpy as np# datanp.random.seed(4)x = np.linspace(0, 1, 50)y = np.cumsum(np.random.randn(50))# plotly line chartfig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'), layout_yaxis_range=[-4,4]) fig.update_layout(yaxis_range=[-4,4])fig.show()
Original answer using plotly.offline
, iplot
and no magic underscore notation:
When setting up a figure, use:
layout = go.Layout(yaxis=dict(range=[fromValue, toValue])
Or if you've already got a figure named fig
, you can use:
fig.update_layout(yaxis=dict(range=[fromValue,toValue]))
Plot:
Complete code for Jupyter Notebook:
# importsfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotimport pandas as pdimport plotly.graph_objs as goimport numpy as np# setupinit_notebook_mode(connected=True)# datanp.random.seed(4)x = np.linspace(0, 1, 50)y = np.cumsum(np.random.randn(50))# linetrace = go.Scatter( x=x, y=y,)# layoutlayout = go.Layout(yaxis=dict(range=[-4,4]))# Plotfig = go.Figure(data=[trace], layout=layout)iplot(fig)
Some important details:
With this setup, you can easily add an y axis title like this:
# layoutlayout = go.Layout(yaxis=dict(range=[-4,4]), title='y Axis'))
It's a little more tricky if you'd like to format that title further. I find it easiest to actually add another element with title = go.layout.yaxis.Title(text='y Axis', font=dict(size=14, color='#7f7f7f')
. As long as you do it the right way, you should not experience the situation in your comment above:
Thanks. I tried it. But then I have 2 definitions of yaxis in theLayout: yaxis=dict(range=[0, 10]) and yaxis=go.layout.YAxis. Thereforean error appears.
Take a look at this:
Plot:
Complete code with y-axis text formatting:
# importsfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotimport pandas as pdimport plotly.graph_objs as goimport numpy as np# setupinit_notebook_mode(connected=True)# datanp.random.seed(4)x = np.linspace(0, 1, 50)y = np.cumsum(np.random.randn(50))# linetrace = go.Scatter( x=x, y=y,)# layoutlayout = go.Layout( yaxis=dict(range=[-4,4], title = go.layout.yaxis.Title(text='y Axis', font=dict(size=14, color='#7f7f7f'))))# Plotfig = go.Figure(data=[trace], layout=layout)iplot(fig)
If I understand you right you want to limit the range of the y-axis itself. You can pass a dict in the keyword argument yaxis
. It could be something like go.Layout(yaxis=dict(range=[0, 10]))
I hope this helps you.