简短回答:
exist = []
fig.for_each_trace(lambda t: exist.append(t.name))
[fig.add_scatter(x=df.index, y = df[col], mode = 'lines', name = col) for col in df.columns if col not in exist]
细节:
通常,只需通过新的调用来重建图形px.line()
使用新的数据集就可以了。但您也可以检索您的跟踪名称fig
using:
exist = []
fig.for_each_trace(lambda t: exist.append(t.name))
然后检查更新的数据集中哪些跟踪名称尚未出现在图中,并将这些名称也包含在fig.add_scatter()
像这样:
[fig.add_scatter(x=df.index, y = df[col], mode = 'lines', name = col) for col in df.columns if col not in exist]
Plot
完整代码
# imports
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
# data
df = px.data.stocks().set_index('date')
df.index = pd.to_datetime(df.index)
# figure
fig = px.line(df, x = df.index, y = df.columns[:2])
# refresh figure with updated dataset
exist = []
fig.for_each_trace(lambda t: exist.append(t.name))
[fig.add_scatter(x=df.index, y = df[col], mode = 'lines', name = col) for col in df.columns if col not in exist]
fig.show()