簡體   English   中英

Plotly 如何 plot 在同一 Y 軸上使用不同 X 數組的多行

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

例如,我嘗試在 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)

我想要 plot 在從 1 到 10 的一個 x 軸上。
StackOverFlow 上的所有答案(如this )都用 pandas dataframe 描述了解決方案,其中所有行(y1 和 y2)都具有與每一行對應的相同 x 值數組。 但是,在我的例子中,y1 和 y2 具有不同的(盡管單位相同)對應的 x 值。

我該怎么做才能在 plotly 中創建這樣一個 plot?

當您沒有 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

在此處輸入圖像描述

您也可以使用plotly.express模塊,但是它需要更多的代碼來設置圖例上的名稱。

在此文檔頁面上了解更多信息。

只需對示例數據進行一些數據整理,您就可以使用這一行:

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

得到這個:

在此處輸入圖像描述

爭論只是從您的類別中構建兩個數據框,並將其堆疊成一個所謂的長格式,plotly express 可以很好地處理它 與所謂的寬表數據相反,不同類別的觀察值數量是否不同並不重要。

完整代碼:

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