import matplotlib.pyplot as plt
import numpy as np
import plotly.plotly as py
from plotly.graph_objs import *

py.sign_in('uname', 'pass')


trace1 = Scatter(
    x=[1,2,3,4,5,6,7,8],
    y=[24,25,30,21,33,31,30,29],
    mode='lines',
    xaxis='x1',
    )

layout = Layout(
    title="My first plot",
    yaxis=YAxis(
        title = "y1"
        ),
    xaxis=XAxis(
        title= 'x1',
        anchor = 'x2'
        ),
    xaxis2=XAxis(
        title= 'x2',
        side = 'top',
        overlaying = 'y'
        ),
    )

data = [trace1]

fig = Figure(data=data, layout=layout)

plot_url = py.plot(fig)


我正在尝试在图的顶部创建第二个X轴(我们称之为x2)。我希望它通过公式x2 = x1 * 0.3链接到x1值。在matplotlib中,我只需要定义另一个轴并重新定义它的范围,就算我放大/缩小也可以保持该比率:

ax2 = ax1.twiny()
start, end = ax1.get_xlim()
ax2.set_xlim(start*0.3, end*0.3)


因此效果应如下所示:

我如何在情节上达到相同的效果?

最佳答案

八九不离十!这是Plotly中多个x轴的简单示例,改编自this example of multiple y-axes in Plotly with Python

import plotly.plotly as py
from plotly.graph_objs import *

trace1 = Scatter(
    x=[1,2,3],
    y=[24,30,25],
    mode='lines',
    xaxis='x1',
)

trace2 = Scatter(
    x=[10,20,30],
    y=[24,25,30],
    mode='lines',
    xaxis='x2',
)

layout = Layout(
    title="Multiple X-Axes",
    yaxis=YAxis(
        title = "y1"
        ),
    xaxis=XAxis(
        title= 'x-axis 1'
    ),
    xaxis2=XAxis(
        title= 'x-axis 2',
        side = 'top',
        overlaying='x1'
    )
)

data = [trace1, trace2]

fig = Figure(data=data, layout=layout)

py.plot(fig, filename='multiple x axes')


会创建此图:(交互式版本:https://plot.ly/~chris/3285

请注意,您可以在各个轴上缩放和平移:

您可以使用Range parameter手动指定这些轴的范围,当您通过滚动放大和缩小时,该比例将保持比率。这是一个简单的示例:

import plotly.plotly as py
from plotly.graph_objs import *

trace1 = Scatter(
    x=[1,2,3],
    y=[24,30,25],
    mode='lines',
    xaxis='x1',
)

trace2 = Scatter(
    x=[10,20,30],
    y=[24,25,30],
    mode='lines',
    xaxis='x2',
)

layout = Layout(
    title="Multiple X-Axes",
    yaxis=YAxis(
        title = "y1"
        ),
    xaxis=XAxis(
        title= 'x-axis 1',
        range=[1, 3]
    ),
    xaxis2=XAxis(
        title= 'x-axis 2',
        side = 'top',
        overlaying='x1',
        range=[10, 30]
    )
)

data = [trace1, trace2]

fig = Figure(data=data, layout=layout)

py.plot(fig, filename='multiple x axes with custom range')


And here is the graph

关于python - 在绘图中,如何创建链接的X轴?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27334585/

10-13 02:34