How to mapping plot data to grid in dash app

41 Views Asked by At

I have a small one-page dash app, with a dash-ag-grid table based on some va, and a go.Scatter graph (lines+markers), which is also based on data from the same df. Please tell me how to make mapping so that when selecting an area on the graph, the table displays data only for the timestamp selected on this graph.

Grid:

def create_grid(df):
    columnDefs=[{'headerName': col, 'field': col} for col in df.columns]
    ag_grid = dag.AgGrid(
        id="ag-grid",
        rowData=df.to_dict("records"),
        columnDefs=columnDefs,
    )
    return ag_grid

plot:

def plot(df, group_by, param, per=None):
    group_by = 'timestamp'
    fig = go.Figure()
    cum_sum = df.groupby(group_by)[param].sum().reset_index()
    
    fig.add_trace(go.Scatter(x=cum_sum[group_by],y=cum_sum[param],mode='lines',name=param,marker=dict(color=color)),) 
        
    for _, row in cum_sum.iterrows():
        group = row[group_by_label]
        fig.add_scatter(x=[group], y=[row[param]], mode='markers', name='', 
            showlegend=False,marker=dict(color=color),)  

    fig.update_layout(title='Title',xaxis=dict(type='category'),height=height,)
    return fig

app:

app.layout = html.Div([
    html.Div([grid]),
    dcc.Graph(id='scatter',figure=fig1)])
1

There are 1 best solutions below

0
ADITYA On

You can use a callback in Dash.

import dash
from dash import dcc, html, callback_context
import dash_ag_grid as dag
import pandas as pd
import plotly.graph_objs as go

# Sample DataFrame
df = pd.DataFrame({
    'timestamp': pd.date_range(start='2024-03-01', end='2024-03-10'),
    'value': range(10)
})

# Define your color and other constants
color = 'blue'
height = 500

# Function to create the grid
def create_grid(df):
    columnDefs = [{'headerName': col, 'field': col} for col in df.columns]
    ag_grid = dag.AgGrid(
        id="ag-grid",
        rowData=df.to_dict("records"),
        columnDefs=columnDefs,
    )
    return ag_grid

# Function to create the scatter plot
def plot(df, param):
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=df['timestamp'], y=df[param], mode='lines+markers', name=param, marker=dict(color=color)))
    fig.update_layout(title='Title', xaxis=dict(type='category'), height=height)
    return fig

# Initialize Dash app
app = dash.Dash(__name__)

# Define layout
app.layout = html.Div([
    html.Div(id='table-container', children=[create_grid(df)]),
    dcc.Graph(id='scatter', figure=plot(df, 'value'))
])

# Callback to update table data based on selected area in scatter plot
@app.callback(
    dash.dependencies.Output('ag-grid', 'rowData'),
    [dash.dependencies.Input('scatter', 'selectedData')]
)
def update_table(selected_data):
    if selected_data is None:
        # No area selected, return original data
        return df.to_dict("records")
    else:
        # Filter data based on selected area
        selected_points = selected_data['points']
        timestamps = [point['x'] for point in selected_points]
        filtered_df = df[df['timestamp'].isin(timestamps)]
        return filtered_df.to_dict("records")

# Run the app
if __name__ == '__main__':
    app.run_server(debug=True)

Now, when you select an area on the scatter plot, the table will update to display data only for the selected timestamps.