Skip to content Skip to sidebar Skip to footer

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 dat

Solution 1:

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

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

Post a Comment for "How To Refresh A Plotly Figure After Dataframe Update?"