Absolute value convertor

Is it possible in Dash or plotly to add a button to a graph that converts one of the traces to its absolute value?

Hi, can’t you just patch the data/trace with the absolute / original version based on the button/state?

I doubt whether there is a functionality like this built-in, as it’s trivial

Reg,
J

Hi @tg550,

@jcuypers refers to something like this. I included two ways of changing the trace. If you know the values of the current_figure, you can use the Patch() method, if not, you will have to use the State() and extract the values first.

import dash
from dash import html, dcc, Input, Output, Patch, State
import plotly.graph_objects as go

x_values = [1, 2, 3]
y_values = [-1, -1, -1]

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        html.Button(
            'change via Patch()',
            id='btn_1',
            style={'margin-right': '5px'}
        ),
        html.Button(
            'change via State()',
            id='btn_2'
        ),
        dcc.Graph(
            id='graph',
            figure=go.Figure(
                go.Scatter(
                    x=x_values,
                    y=y_values
                )
            )
        )
    ]
)


@app.callback(
    Output('graph', 'figure', allow_duplicate=True),
    Input('btn_1', 'n_clicks'),
    prevent_initial_call=True
)
def update_trace(_):
    patched = Patch()
    patched['data'][0]['y'] = [abs(value) for value in y_values]
    return patched


@app.callback(
    Output('graph', 'figure'),
    Input('btn_2', 'n_clicks'),
    State('graph', 'figure'),
    prevent_initial_call=True
)
def update_trace(_, current_figure):
    current_y_values = current_figure['data'][0]['y']
    changed_y_values = [abs(value) for value in current_y_values]

    current_figure['data'][0]['y'] = changed_y_values
    return current_figure


if __name__ == "__main__":
    app.run(debug=True)

mred Patch()