更新新版本
设置图形时,您可以使用 plotly 的 magic underscore notation 并指定 layout_yaxis_range=[<from_value>, <to_value>],如下所示:
fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'), layout_yaxis_range=[-4,4])
或者如果你已经有一个名为fig的人物,你可以使用:
fig.update_layout(yaxis_range=[-4,4])
还有:
fig.update(layout_yaxis_range = [-4,4])
或者:
fig.update_yaxes(range = [-4,4])
图:
完整代码:
# imports
import pandas as pd
import plotly.graph_objs as go
import numpy as np
# data
np.random.seed(4)
x = np.linspace(0, 1, 50)
y = np.cumsum(np.random.randn(50))
# plotly line chart
fig = 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()
原始答案使用plotly.offline、iplot 并且没有神奇的下划线符号:
设置图形时,使用:
layout = go.Layout(yaxis=dict(range=[fromValue, toValue])
或者如果你已经有一个名为fig的人物,你可以使用:
fig.update_layout(yaxis=dict(range=[fromValue,toValue]))
剧情:
Jupyter Notebook 的完整代码:
# imports
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import pandas as pd
import plotly.graph_objs as go
import numpy as np
# setup
init_notebook_mode(connected=True)
# data
np.random.seed(4)
x = np.linspace(0, 1, 50)
y = np.cumsum(np.random.randn(50))
# line
trace = go.Scatter(
x=x,
y=y,
)
# layout
layout = go.Layout(yaxis=dict(range=[-4,4])
)
# Plot
fig = go.Figure(data=[trace], layout=layout)
iplot(fig)
一些重要细节:
通过此设置,您可以轻松添加 y 轴标题,如下所示:
# layout
layout = go.Layout(yaxis=dict(range=[-4,4]), title='y Axis')
)
如果您想进一步格式化该标题,这有点更棘手。我发现用title = go.layout.yaxis.Title(text='y Axis', font=dict(size=14, color='#7f7f7f') 添加另一个元素是最容易的。只要你做对了,你就不应该遇到上面评论中的情况:
谢谢。我尝试过这个。但是我在 yaxis 中有 2 个定义
布局:yaxis=dict(range=[0, 10]) 和 yaxis=go.layout.YAxis。所以
出现错误。
看看这个:
剧情:
带有 y 轴文本格式的完整代码:
# imports
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import pandas as pd
import plotly.graph_objs as go
import numpy as np
# setup
init_notebook_mode(connected=True)
# data
np.random.seed(4)
x = np.linspace(0, 1, 50)
y = np.cumsum(np.random.randn(50))
# line
trace = go.Scatter(
x=x,
y=y,
)
# layout
layout = go.Layout(
yaxis=dict(range=[-4,4],
title = go.layout.yaxis.Title(text='y Axis', font=dict(size=14, color='#7f7f7f')))
)
# Plot
fig = go.Figure(data=[trace], layout=layout)
iplot(fig)