der*_*flo 10 python express plotly yaxis
我如何利用 plotly.express 在一个 Pandas 数据框中的两个 yaxis 上绘制多条线?
我发现这对于绘制包含特定子字符串的所有列非常有用:
fig = px.line(df, y=df.filter(regex="Linear").columns, render_mode="webgl")
Run Code Online (Sandbox Code Playgroud)
因为我不想遍历所有过滤的列并使用以下内容:
fig.add_trace(go.Scattergl(x=df["Time"], y=df["Linear-"]))
Run Code Online (Sandbox Code Playgroud)
在每次迭代中。
der*_*flo 20
我花了一些时间来解决这个问题,但我觉得这可能对某些人有用。
# 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()
Run Code Online (Sandbox Code Playgroud)
诀窍
subfig.for_each_trace(lambda t: t.update(line=dict(color=t.marker.color)))
Run Code Online (Sandbox Code Playgroud)
我从 nicolaskruchten 那里得到:https ://stackoverflow.com/a/60031260
归档时间: |
|
查看次数: |
8090 次 |
最近记录: |