簡體   English   中英

Plotly:如何使用 plotly 表示在輔助 y 軸上的 plot

[英]Plotly: How to plot on secondary y-Axis with plotly express

如何利用 plotly.express 到 plot 兩個 y 軸上的多行 Pandas Z6A8064B5DF479455550055C?

我發現這對 plot 所有包含特定 substring 的列非常有用:

    fig = px.line(df, y=df.filter(regex="Linear").columns, render_mode="webgl")

因為我不想遍歷所有過濾的列並使用類似的東西:

    fig.add_trace(go.Scattergl(x=df["Time"], y=df["Linear-"]))

在每次迭代中。

我花了一些時間來解決這個問題,但我覺得這對某些人可能有用。

# import some stuff
import plotly.express as px
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np

# create some data
df = pd.DataFrame()
n = 50
df["Time"] = np.arange(n)
df["Linear-"] = np.arange(n)+np.random.rand(n)
df["Linear+"] = np.arange(n)+np.random.rand(n)
df["Log-"] = np.arange(n)+np.random.rand(n)
df["Log+"] = np.arange(n)+np.random.rand(n)
df.set_index("Time", inplace=True)

subfig = make_subplots(specs=[[{"secondary_y": True}]])

# create two independent figures with px.line each containing data from multiple columns
fig = px.line(df, y=df.filter(regex="Linear").columns, render_mode="webgl",)
fig2 = px.line(df, y=df.filter(regex="Log").columns, render_mode="webgl",)

fig2.update_traces(yaxis="y2")

subfig.add_traces(fig.data + fig2.data)
subfig.layout.xaxis.title="Time"
subfig.layout.yaxis.title="Linear Y"
subfig.layout.yaxis2.type="log"
subfig.layout.yaxis2.title="Log Y"
# recoloring is necessary otherwise lines from fig und fig2 would share each color
# e.g. Linear-, Log- = blue; Linear+, Log+ = red... we don't want this
subfig.for_each_trace(lambda t: t.update(line=dict(color=t.marker.color)))
subfig.show()

成品圖

訣竅

subfig.for_each_trace(lambda t: t.update(line=dict(color=t.marker.color)))

我從 nicolaskruchten 那里得到: https://stackoverflow.com/a/60031260

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM