我不确定是否存在用于 plotly 的相同功能。但是您至少可以构建一个图形,扩展您的数据源,然后只需替换图形的数据,而无需触及任何其他图形元素,如下所示:
for i, col in enumerate(fig.data):
fig.data[i]['y'] = df[df.columns[i]]
fig.data[i]['x'] = df.index
您的图形是使用plotly.express 还是go.Figure 的结果无关紧要,因为这两种方法都会生成可以通过上面的代码sn-p 编辑的图形结构。您可以通过在 JupyterLab 的两个不同单元格中设置以下两个 sn-ps 来自行测试。
单元格 1 的代码
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
# code and plot setup
# settings
pd.options.plotting.backend = "plotly"
# sample dataframe of a wide format
np.random.seed(5); cols = list('abc')
X = np.random.randn(50,len(cols))
df=pd.DataFrame(X, columns=cols)
df.iloc[0]=0;df=df.cumsum()
# plotly figure
fig = df.plot(template = 'plotly_dark')
fig.show()
单元格 2 的代码
# create or retrieve new data
Y = np.random.randn(1,len(cols))
# organize new data in a df
df2 = pd.DataFrame(Y, columns = cols)
# add last row to df to new values
# this step can be skipped if your real world
# data is not a cumulative process like
# in this example
df2.iloc[-1] = df2.iloc[-1] + df.iloc[-1]
# append new data to existing df
df = df.append(df2, ignore_index=True)#.reset_index()
# replace old data in fig with new data
for i, col in enumerate(fig.data):
fig.data[i]['y'] = df[df.columns[i]]
fig.data[i]['x'] = df.index
fig.show()
运行第一个单元格将汇总一些数据并构建一个如下图:
运行第二个单元格将生成一个只有一行的新数据框,将其附加到原始数据框,替换现有图中的数据,然后再次显示该图。您可以根据需要多次运行第二个单元格,以使用扩展数据集重新绘制图形。运行 50 次后,您的图形将如下所示: