简体   繁体   English

Plotly 如何 plot 在同一 Y 轴上使用不同 X 数组的多行

[英]Plotly How to plot multiple lines with different X-arrays on the same Y-axis

I try to use plotly in python to plot several lines having their own X-values on the same graph for example.例如,我尝试在 python 到 plot 中使用 plotly 在同一张图上有自己的 X 值的几行。

x1 = [1, 3, 5, 7, 9]
y1 = np.random.random(5)

x2 = [2, 4, 6, 8, 10]
y2 = np.random.random(5)

I want to plot this on the one x-axis from 1 to 10.我想要 plot 在从 1 到 10 的一个 x 轴上。
All answers on StackOverFlow (like this ) describe the solution with a pandas dataframe where all lines (y1 and y2) have the same array of x-values corresponding to each line. StackOverFlow 上的所有答案(如this )都用 pandas dataframe 描述了解决方案,其中所有行(y1 和 y2)都具有与每一行对应的相同 x 值数组。 However, in my case y1 and y2 have different (though in the same units) corresponding x-values.但是,在我的例子中,y1 和 y2 具有不同的(尽管单位相同)对应的 x 值。

What can I do to make such a plot in plotly?我该怎么做才能在 plotly 中创建这样一个 plot?

When you don't have a dataframe, I argue that the easiest way is to use plotly.graph_objects .当您没有 dataframe 时,我认为最简单的方法是使用plotly.graph_objects

import plotly.graph_objects as go

x1 = [1, 3, 5, 7, 9]
y1 = np.random.random(5)
x2 = [2, 4, 6, 8, 10]
y2 = np.random.random(5)

f1 = go.Figure(
    data = [
        go.Scatter(x=x1, y=y1, name="first"),
        go.Scatter(x=x2, y=y2, name="second"),
    ],
    layout = {"xaxis": {"title": "x axis"}, "yaxis": {"title": "y axis"}, "title": "My title"}
)
f1

在此处输入图像描述

You can also use the plotly.express module, however it requires a bit more code to set the names on the legends.您也可以使用plotly.express模块,但是它需要更多的代码来设置图例上的名称。

Learn more at this documentation page .在此文档页面上了解更多信息。

With just a little bit of data wrangling on your example data, you can just use this single line:只需对示例数据进行一些数据整理,您就可以使用这一行:

fig = px.line(df, x = 'x', y = 'y', color = 'name', markers = True)

And get this:得到这个:

在此处输入图像描述

The wrangling is just building two dataframes out of your categegories and stacking the into a so-called long-form which plotly express handles beautifully .争论只是从您的类别中构建两个数据框,并将其堆叠成一个所谓的长格式,plotly express 可以很好地处理它 Contrary to so-called wide-form data, it won't matter if the different categories have a different number of observations.与所谓的宽表数据相反,不同类别的观察值数量是否不同并不重要。

Complete code:完整代码:

import plotly.express as px
import pandas as pd
import numpy as np

x1 = [1, 3, 5, 7, 9]
y1 = np.random.random(5)

x2 = [2, 4, 6, 8, 10]
y2 = np.random.random(5)

df1 = pd.DataFrame({'name': ['1']*len(x1),
                    'x': x1,
                    'y': y1})

df2 = pd.DataFrame({'name': ['2']*len(x2),
                    'x': x2,
                    'y': y2})

df = pd.concat([df1, df2])

fig = px.line(df, x = 'x', y = 'y', color = 'name', markers = True)
fig.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM