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: add a Parameter so that the dashboard user can change which company is highlighted.
# Refer to https://vizro.readthedocs.io/en/stable/pages/user-guides/parameters/.
# Solution given in https://py.cafe/antonymilne/sparkline-solution.
# We put the sparkline chart inside a custom figure function.
@capture("graph")
def sparkline(data_frame):
# 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.
highlight_color = fig.layout.template.layout.colorway[0]
fig.update_traces(line_color="grey")
fig.update_traces(line_color=highlight_color, selector={"name": "AMZN"})
fig.for_each_annotation(lambda annotation: annotation.update(text=annotation.text.split("=")[-1]))
return fig
page = vm.Page(
title="Tech stocks in 2018-19",
components=[
vm.Graph(id="sparkline", figure=sparkline(stocks)),
],
)
dashboard = vm.Dashboard(pages=[page])
Vizro().build(dashboard).run()