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

时间:2019-04-16 08:46:30

标签: python plotly plotly-python

我有以下代码用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)]

2 个答案:

答案 0 :(得分:0)

如果我理解的正确,您想限制y轴本身的范围。您可以在关键字参数yaxis中传递字典。可能像go.Layout(yaxis=dict(range=[0, 10]))之类的东西,希望对您有所帮助。

答案 1 :(得分:0)

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


情节:

enter image description here

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

看看这个:

情节:

enter image description here

使用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)