情节:如何用新数据更新/重画情节表达图?

时间:2020-09-03 03:49:51

标签: python plot plotly redraw plotly-express

在调试或计算繁重的循环过程中,我想看看我的数据处理如何发展(例如,在线条图中或图像中)。

在matplotlib中,代码可以使用plt.cla()然后plt.draw()plt.pause(0.001)重绘/更新图形,以便我可以实时或在调试时跟踪计算进度。我该如何用情节地表达(或情节地)?

2 个答案:

答案 0 :(得分:1)

我不确定是否存在密谋性功能。但是您至少可以构建一个图形,扩展您的数据源,然后仅替换该图形的数据,而无需触摸其他任何图形元素,例如:

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的结果都没有关系,因为两种方法都会产生一个图形结构,可以通过上面的代码片段进行编辑。您可以通过在JupyterLab的两个不同单元中设置以下两个摘要来自己进行测试。

单元格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()

运行第一个单元格将汇总一些数据并构建如下图:

enter image description here

运行第二个单元格将生成仅一行的新数据框,将其附加到原始数据框,替换现有图形中的数据,然后再次显示该图形。您可以根据需要运行第二个单元多次,以使用扩展的数据集重绘图形。运行50次后,您的身材将如下所示:

enter image description here

答案 1 :(得分:1)

所以我想我基本上是想通了。诀窍是不要使用go.Figure()来创建人物,而要使用go.FigureWidget()来创建人物,这在视觉上是一样的,但是在幕后却不是。

documentation

youtube video demonstration

随着新数据的传入,这些FigureWidget完全可以在那里进行更新。它们保持动态,以后的调用可以对其进行修改。

一个FigureWidget可以由一个Figure制成:

figure = go.Figure(data=data, layout=layout)

f2 = go.FigureWidget(figure)
f2                                          #display the figure

这是实用的,因为它使得可以使用简化的绘图表达接口来创建图形,然后使用该接口来构造FigureWidget。不幸的是,plotly express似乎没有自己的简化FigureWidget模块。因此,需要使用更复杂的go.FigureWidget

相关问题