Plotly Dash Python > Delete previous point data

Hello! I just created my first Plotly Dash app that takes data from a csv in real time and plots it to a graph. Is there any way I could delete the previous (first data input) data point and only plot the incoming one (last one added to the csv)?
This my code:

import pandas as pd
import dash
import plotly.graph_objects as go
import dash_core_components as dcc
import dash_html_components as html


app = dash.Dash(__name__)
app.title = "Title"
def _create_fig():
    df = pd.read_csv('/home/pi/tflite1/csv_data_file.csv')
    df.columns=['x','y']
    return go.Figure(
        data=go.Scatter(
            x=df['x'],
            y=df['y'], mode = 'markers'))



app.layout = html.Div([
    dcc.Graph(
        id='g1',
        animate = True,
        figure=_create_fig()),
    dcc.Interval(
        id='interval-component',
        interval=1*1000, # in milliseconds
        n_intervals=0
    )
])
# 
# 
@app.callback(
    dash.dependencies.Output('g1', 'figure'),
    dash.dependencies.Input('interval-component', 'n_intervals')
    )

def refresh_data(n_clicks):
    return _create_fig()


if __name__ == "__main__":
    app.run_server(host='0.0.0.0', debug=True, port=8099)

Hi @LauraR,

Welcome to the community! :slightly_smiling_face:

There are a few ways to do that, but it requires some changes in your code. The simplest approach is to compare the points currently in the Figure with the dataframe imported from the csv, so you have to decouple the function that generates the figure with the csv reader. It goes more or less like this:

@app.callback(
    dash.dependencies.Output('g1', 'figure'),
    dash.dependencies.Input('interval-component', 'n_intervals'),
    dash.dependencies.State('g1', 'figure')
    )

def refresh_data(n_clicks, current_fig):
    current_trace = current_fig["data"][0]
    curr_x, curr_y = current_trace["x"], current_trace["y"]
 
     # Import csv and filter newer values only
     # ....
     # Add newer values to the current figure
    current_fig["data"][0]["x"] = x_new
    current_fig["data"][0]["y"] = y_new

    return current_fig

Note that you don’t have to recreate the go.Figure if you just manipulate the points in the trace. You might have to handle cases where current_fig is None, but it shouldn’t happen if you initialize the component with a figure.

1 Like

Hello @jlfsjunior ! OMG, Thank you!! It works perfectly!