Py.Cafe

physiksdoc/

solara-plotly-figure-transition-key-fix

Solara-Plotly Figure Transition (with Key Fix)

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# -*- coding: utf-8 -*-
"""

Demonstrate the odd transition when updating a figure using
Plotly in Solara.

Created: 11 September 2024
Revised:

"""
import solara
import plotly.graph_objects as pgo
from scipy.signal import sweep_poly
from numpy import linspace, poly1d

DARK_SAGE = "#8da375"
LIGHT_GRAY = "#bbbbbb"

plotly_figure = solara.Reactive(pgo.Figure)


def get_figure(xrange: list | None = None) -> pgo.Figure:
    """ Build the basic figure and common layout (minus the data) """
    empty_fig = pgo.Figure()
    empty_fig.update_layout(paper_bgcolor=LIGHT_GRAY,
                            showlegend=False,
                            legend={"borderwidth": 1,
                                    "bordercolor": "black"},
                            hovermode="closest")
    empty_fig.update_xaxes(title_text="Time", gridcolor="gray",
                           range=xrange, ticks="outside")
    empty_fig.update_yaxes(title_text="Amplitude", gridcolor="gray",
                           ticks="outside")
    return empty_fig


def add_figure_data(p_fig: pgo.Figure, data: dict) -> pgo.Figure:
    """ Add a data trace to the prepared figure """
    marker = {"color": data["color"],
              "size": 3,
              "symbol": "circle"}
    trace_x = pgo.Scatter(x=data["time"], y=data["amplitude"],
                          marker=marker, mode="markers",
                          line={"width": 0})
    p_fig.add_trace(trace_x)
    return p_fig


# ============================================================================

def get_data(samples: int, xper: int, subsample: int,
             offset: int, color: str) -> dict:
    """ Build a dataset """
    data = dict(time=linspace(0, samples-1, samples).astype(int),
                amplitude=(sweep_poly(linspace(0, subsample, samples),
                                      poly1d(1), 45) * xper) + offset,
                color=color)
    return data


data_1 = get_data(7057, 29, 19, 353, "green")
data_2 = get_data(2311,  61, 11, 241, "blue")

# ============================================================================


def button_handler1():
    fig = get_figure(xrange=[data_1["time"][0], data_1["time"][-1]])
    add_figure_data(fig, data_1)
    fig.update_layout(title="Plot 1")
    plotly_figure.value = fig


def button_handler2():
    fig = get_figure(xrange=[data_2["time"][0], data_2["time"][-1]])
    add_figure_data(fig, data_2)
    fig.update_layout(title="Plot 2")
    plotly_figure.value = fig


@solara.component
def Page():
    solara.use_memo(button_handler1)
    with solara.Card(title="Solara-Plotly Transition Example (with Key Fix)",
                     elevation=3,
                     style={'background-color': DARK_SAGE,
                            'width': '900px'}):

        with solara.Column(gap='20px',
                           style={'background-color': DARK_SAGE}):

            solara.FigurePlotly(plotly_figure.value,
                                dependencies=[plotly_figure.value['data']]).key(id(plotly_figure.value))

            with solara.Row(margin=2,
                            style={"background-color": LIGHT_GRAY,
                                   "padding": "5px"}):
                solara.Button("Plot 1", on_click=button_handler1)
                solara.Button("Plot 2", on_click=button_handler2)