Py.Cafe

antonymilne/

sparkline-2-solution

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
import vizro.plotly.express as px
from vizro import Vizro
import vizro.models as vm
from vizro.models.types import capture

stocks = px.data.stocks(indexed=True)

# TODO: for the next challenge, go to https://py.cafe/antonymilne/sparkline-2.

# We put the sparkline chart inside a custom figure function.
@capture("graph")
# SOLUTION: added highlight_company parameter.
def sparkline(data_frame, highlight_company=None):
    # Compared to the version in the notebook, we have removed template, height, and row 
    # from this function call.
    fig = px.line(data_frame, facet_row="company")

    fig.add_vrect(
        x0="2018-07-01",
        x1="2018-12-31",
        fillcolor="grey",
        opacity=0.1,
        layer="below",
        line_width=0,
    )

    fig.update_layout(showlegend=False)
    fig.update_xaxes(dict(visible=False))
    fig.update_yaxes(dict(visible=False))

    # We use grey for all lines apart from the highlighted one. The highlight color comes from the 
    # Vizro plotly template but could be hardcoded to a hex value if you prefer.
    # SOLUTION: selected trace now depends on highlight_company.
    highlight_color = fig.layout.template.layout.colorway[0]
    fig.update_traces(line_color="grey")
    fig.update_traces(line_color=highlight_color, selector={"name": highlight_company})
    return fig

page = vm.Page(
    title="Tech stocks in 2018-19",
    components=[
       vm.Graph(id="sparkline", figure=sparkline(stocks)),
    ],
    # SOLUTION: added Parameter to control highlight_company.
    controls=[
        vm.Parameter(
            targets=["sparkline.highlight_company"],
            selector=vm.RadioItems(options=stocks.columns)
        )
    ],
)

dashboard = vm.Dashboard(pages=[page])
Vizro().build(dashboard).run()