vestland
vestland

Reputation: 61114

How to refresh a plotly figure after dataframe update?

Let's say that you've built a figure using px.line() using a dataframe, and the dataframe later has new data added to it. What's a good approach to refresh your figure with new data? An example could be px.data.stocks, where you start out with a subset of the columns ['GOOG', 'AAPL', 'AMZN', 'FB', 'NFLX', 'MSFT'], for example ['GOOG', 'AAPL'], and that after building the figure, ['AMZN', 'FB', 'NFLX', 'MSFT'] is added to the dataframe.

Example plot

enter image description here

Example code

# 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])
fig.show()

Upvotes: 2

Views: 3564

Answers (1)

vestland
vestland

Reputation: 61114

Short answer:

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]

The details:

Often, just rebuilding the figure with a new call to px.line() with the new dataset will do just fine. But you can also retrieve the names of the traces in your fig using:

exist = []
fig.for_each_trace(lambda t: exist.append(t.name))

And then check which of the trace names in your updated dataset are not already in the figure and include those as well with fig.add_scatter() like this:

[fig.add_scatter(x=df.index, y = df[col], mode = 'lines', name = col) for col in df.columns if col not in exist]

Plot

enter image description here

Complete code

# 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()

Upvotes: 2

Related Questions