我有以下代码使用Plotly创建线图。如何将Y轴的范围设置为始终在[0; 10]?

layout = go.Layout(
        title=go.layout.Title(
            text="Test",
            xref='paper',
            x=0
        ),
        xaxis=go.layout.XAxis(
            tickmode='linear',
            tickfont=dict(
                size=10
            ),
            title=go.layout.xaxis.Title(
                font=dict(
                    size=14,
                    color='#7f7f7f'
                )
            )
        ),
        yaxis=go.layout.YAxis(
            title=go.layout.yaxis.Title(
                text=y,
                font=dict(
                    size=14,
                    color='#7f7f7f'
                )
            )
        )
    )

    data = [go.Scatter(x=x1, y=y1)]

最佳答案

使用layout = go.Layout(yaxis=dict(range=[fromValue, toValue])



情节:

python - 如何在Plotly线图中设置Y轴的范围?-LMLPHP

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。因此
  出现错误。


看看这个:

情节:

python - 如何在Plotly线图中设置Y轴的范围?-LMLPHP

具有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)

关于python - 如何在Plotly线图中设置Y轴的范围?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55704058/

10-12 23:14