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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
#import datetime
import json
#import math

# data analysis
import numpy as np
import pandas as pd

# dashboard
import panel as pn

# plotting
import altair as alt
import holoviews as hv
import hvplot.pandas  # noqa
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
import plotly.express as px
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure as b_figure
from matplotlib.figure import Figure
from plotnine import ggplot, aes, geom_line, theme_matplotlib, theme_set


# configure panel and plots
pn.extension('ipywidgets', 'plotly', 'vega', 'vizzu',
             design='material', sizing_mode='fixed')
hv.extension('bokeh', 'matplotlib', 'plotly')
matplotlib.use('agg')

# configure app
DATA_DIR = 'data'
JSON_FILE = 'tensorflow.timeline.purpose-to-type.json'

# get data, cached
@pn.cache
def get_timeline_data():
    with open(f'{DATA_DIR}/{JSON_FILE}', mode='r') as json_fp:
        return json.load(json_fp)

# TODO: include the rest of the app

# widgets
repos_widget = pn.widgets.Select(
    name="repository",
    value="tensorflow", options=["tensorflow"],
    disabled=True
)


# -----------------------------------------------------------
def create_figure_matplotlib(figsize=(4,3)):
    # data
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)

    # figure
    if figsize is None:
        fig = Figure()
    else:
        fig = Figure(figsize=figsize)
    ax = fig.subplots()

    # plot
    ax.plot(t, s)

    # decorations
    ax.set(xlabel='time (s)', ylabel='voltage (mV)',
           title='Voltage')
    ax.grid()
    # https://matplotlib.org/ipympl/examples/full-example.html
    # NOTE: might require ipympl to be installed
    # Hide the Figure name at the top of the figure
    fig.canvas.header_visible = False
    # Disable the resizing feature
    fig.canvas.resizable = False

    return fig


def create_figure_seaborn(figsize=(4,3)):
    # data
    t = np.arange(0.0, 2.0, 0.01)
    df = pd.DataFrame({
        'x': t,
        'y': 1 + np.sin(2 * np.pi * t),
    })

    # figure
    fig = Figure(figsize=figsize)
    ax = fig.subplots()

    # configure
    sns.set_theme()  # 'default' theme

    # plot
    sns.lineplot(data=df, x='x', y='y',
                 ax=ax)

    return fig


def create_figure_pandas(figsize=(4,3)):
    # data
    t = np.arange(0.0, 2.0, 0.01)
    df = pd.DataFrame({
        'x': t,
        'y': 1 + np.sin(2 * np.pi * t),
    })

    # figure
    fig = Figure(figsize=figsize)
    ax = fig.subplots()

    # plot
    df.plot(x='x', y='y', legend=False,
            xlabel='time (s)', ylabel='voltage (mV)', title='Voltage',
            ax=ax)

    return fig


def create_figure_plotnine():
    # data
    t = np.arange(0.0, 2.0, 0.01)
    df = pd.DataFrame({
        'x': t,
        'y': 1 + np.sin(2 * np.pi * t),
    })

    # Set default theme for all the plots
    theme_set(theme_matplotlib())

    # Basic Scatter Plot
    # - Gallery, points
    plot = (
        ggplot(df, aes("x", "y"))
        + geom_line(color="blue")
    )

    # draw the plot
    fig = plot.draw()
    plt.close(fig)  # REMEMBER TO CLOSE THE FIGURE!

    return fig


def create_figure_bokeh():
    # data
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)

    # wrapped data
    source = ColumnDataSource(data=dict(x=t, y=s))

    # configuring the plot
    # https://docs.bokeh.org/en/latest/docs/user_guide/interaction/tools.html#inspectors
    tooltips = [
        ("index", "$index"),
        ("(x,y)", "($x, $y)"),
    ]

    # set up plot
    plot = b_figure(height=400, width=400, title="my sine wave",
                    tools="crosshair,pan,reset,save,wheel_zoom,hover",
                    tooltips=tooltips,
                    x_range=[-0.1, 2.1], y_range=[-0.1, 2.1])

    plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

    return plot


def create_figure_hvplot_pandas():
    # data
    t = np.arange(0.0, 2.0, 0.01)
    df = pd.DataFrame({
        'x': t,
        'y': 1 + np.sin(2 * np.pi * t),
    })

    # plot
    plot = df.hvplot(x='x', y='y',
                     value_label='sin(2πt)+1',
                     #responsive = True,  # incompatible with fixed size
                     height = 500, width = 620,  # incompatible with responsive mode
                     title='f(t) = sin(2πt)+1',
                     legend='top')

    return plot


def create_figure_hv():
    # data
    t = np.arange(0.0, 2.0, 0.01)
    data = {
        "x": t,
        "y": 1 + np.sin(2 * np.pi * t),
    }

    # plot
    hv_box = hv.Scatter(data, kdims="x", vdims="y").opts()

    return hv_box


def create_figure_plotly():
    # data
    t = np.arange(0.0, 2.0, 0.01)
    data = {
        "x": t,
        "y": 1 + np.sin(2 * np.pi * t),
    }

    # create plot
    fig = px.line(
        data, x="x", y="y",
        # ??? 'fixed' sizing mode requires width and height to be set: PlotlyPlot(id='p1275', ...)
        width=500, height=420,  # required for 'fixed' sizing mode
    )

    # configure plot
    fig.update_traces(mode="lines", line=dict(width=1))

    return fig


def create_figure_altair():
    # data
    t = np.arange(0.0, 2.0, 0.01)
    df = pd.DataFrame({
        "x": t,
        "y": 1 + np.sin(2 * np.pi * t),
    })

    # create plot
    # https://altair-viz.github.io/user_guide/marks/line.html
    chart = alt.Chart(df).mark_line(
        point=alt.OverlayMarkDef(opacity=0, size=1),
    ).encode(
        x='x',
        y='y',
        tooltip=['x', 'y'],  # not used?
    ).properties(
        # ??? 'fixed' sizing mode requires width and height to be set: VegaPlot(id='p1282', ...)
        width =500,
        height=420,
    ).interactive()

    return chart


# https://panel.holoviz.org/reference/panes/HoloViews.html#dynamic
def hvplot_widgeted(height = 300):
    plot = create_figure_hvplot_pandas()

    plot_pane = pn.pane.HoloViews(plot,
                                  backend='bokeh',
                                  sizing_mode="fixed", height=height)

    backend_widget = pn.widgets.RadioButtonGroup.from_param(
        plot_pane.param.backend,
        button_type="primary", button_style="outline",
    )

    return pn.Column(backend_widget, plot_pane)


def wizzu_pane():
    # data (may use DataFrame instead)
    t = np.arange(0.0, 2.0, 0.01)
    data = {
        "x": t,
        "y": 1 + np.sin(2 * np.pi * t),
    }
    df = pd.DataFrame(data)

    # plot configuration
    config = {
        'geometry': 'line',
        'x': 'x', 'y': 'y',
        'title': 'sin(2πt)+1',
    }
    animate = {
        'config': {
            'channels': {
                'x': {
                    'range': {
                        'min': 'auto',
                        'max': 'auto'
                    }
                },
                'y': {
                    'range': {
                        'min': 'auto',
                        'max': 'auto',
                    }
                }
            }
        }
    }

    # pane
    vizzu = pn.pane.Vizzu(
        df, config=config, animation=animate,
        duration=400, tooltip=True,
        sizing_mode='fixed', width=500, height=425,
    )

    return vizzu


# the application
pn.template.MaterialTemplate(
    site="Panel",
    title="Demo of various plotting solutions",
    sidebar_width=300,
    sidebar=[
        repos_widget,  # disabled, and UNBOUND!
    ],
    main=[
        pn.pane.Str("Plots would be shown here"),
        pn.FlexBox(
            pn.Card(
                pn.pane.Matplotlib(create_figure_matplotlib(),
                                   format="svg", tight=True,
                                   width=500, height=425),
                header="Matplotlib (svg)",
            ),
            pn.Card(
                pn.pane.Matplotlib(create_figure_matplotlib(figsize=None),
                                   interactive=True, tight=True,
                                   width=500, height=425),
                header="interactive Matplotlib (via ipympl) - BUGGY!!!",
            ),
            pn.Card(
                pn.pane.Matplotlib(create_figure_seaborn(),
                                   format="png", tight=True,
                                   width=500, height=425),
                header="seaborn (png)",
            ),
            pn.Card(
                pn.pane.Matplotlib(create_figure_pandas(),
                                   format="png", tight=True,
                                   width=500, height=425),
                header="pandas (png)",
            ),
            # TODO: https://panel.holoviz.org/reference/panes/Perspective.html
            pn.Card(
                pn.pane.Matplotlib(create_figure_plotnine(),
                                   format="svg", tight=True,
                                   width=500, height=425),
                header="plotnine / ggplot2 (png)",
            ),
            pn.Card(
                pn.Row(
                    pn.pane.Bokeh(create_figure_bokeh(), theme="dark_minimal", height=600),
                    pn.pane.Markdown(r"""
                    - Pan/Drag Tools
                        - 'box_select'
                        - 'box_zoom'
                        - 'lasso_select'
                        - **'pan'**, 'xpan', 'ypan'
                    - Click/Tap Tools
                        - 'poly_select'
                        - 'tap'
                    - Scroll/Pinch Tools
                        - **'wheel_zoom'**, 'xwheel_zoom', 'ywheel_zoom'
                        - 'xwheel_pan', 'ywheel_pan'
                    - Actions
                        - 'examine'
                        - 'undo'
                        - 'redo'
                        - **'reset'**
                        - **'save'**
                        - 'zoom_in', 'xzoom_in', 'yzoom_in'
                        - 'zoom_out', 'xzoom_out', 'yzoom_out'
                    - Inspectors
                        - **'crosshair'**
                        - **'hover'** (figure configurable with `tooltips=`)
                    - Edit Tools
                        - ...
                    """),
                ),
                header="Bokeh (theme='dark_minimal')",
            ),
            # TODO?: https://panel.holoviz.org/reference/panes/ECharts.html
            pn.Card(
                create_figure_hvplot_pandas(),
                header="hvPlot (pandas.hvplot)",
            ),
            pn.Card(
                hvplot_widgeted(height=600),
                header="hvPlot - select backend",
            ),
            pn.Card(
                pn.pane.HoloViews(create_figure_hv(),
                                  sizing_mode='fixed', height=600),
                header="HoloViews (hv.Scatter)",
            ),
            pn.Card(
                pn.pane.Plotly(create_figure_plotly(),
                               sizing_mode='fixed', width=500, height=425),
                header="Plotly.Express",
            ),
            pn.Card(
                pn.pane.Vega(create_figure_altair(),
                             sizing_mode='fixed', width=500, height=425),
                # ALTERNATIVE: pn.panel(create_figure_altair())
                header="Vega (using Altair)",
            ),
            pn.Card(
                wizzu_pane(),
                header="Vizzu JavaScript library - not configured!!!",
            ),
        ),
    ],
).servable()