Responsiveness of the charts
Over time, we observed that the charts were not responsive when viewed on smaller screens. To tackle this issue, we implemented the following approach:
- Get the screen width and height and store it.
- Pass the stored width and height in each page callback.
- process the chart legend orientation and wrapping the chart title accordingly.
The steps show as fallow:
1. Get the screen width and height and store it
A clientside_callback (opens in a new tab) was defined in the app.py
file. This callback retrieves the current screen width and height from the browser when the dashboard loads and stores this information. This is done using a dcc.Store (opens in a new tab) component within the Dash framework, which allows data to be stored in the client’s browser in JSON format.
app.layout = dcc.Loading(
id="loading-general",
fullscreen=True,
children=[
dcc.Location(id="url"),
dcc.Store(id="viewport_container"),
html.Div(dash.page_container),
],
type="circle",
)
app.clientside_callback(
"""
function (href) {
var w = window.innerWidth;
var h = window.innerHeight;
return {'height': h, 'width': w};
}
""",
Output("viewport_container", "data"),
Input("url", "href"),
)
2. Pass the stored width and height in each page callback.
The stored width and height are then used in each callback function on every page. For example in home.py
file:
@callback(
Output("graph_literature_dataset", "figure"),
Input("viewport_container", "data"),
)
def update_graph_home_figures(viewport_size):
viewport_size_width = viewport_size["width"]
try:
return change_legend_according_viewport_size(
chart(viewport_size_width), viewport_size_width
)
except (RuntimeError, TypeError, NameError, AttributeError):
return None
or in
warp_graph_title_according_viewport_size(
fig1, i18n.t("home.chartTitle"), viewport_size_width
)
3. Process the chart legend orientation and chart title.
Now according to the width and height of the screen we are able to render the charts components differently, such as adjusting the chart legend orientation and wrapping the chart title, through our custom helper functions:
def change_legend_according_viewport_size(
graph,
viewport_size_width,
):
if viewport_size_width < 600:
graph.update_layout(
legend={"orientation": "h", "y": -0.2, "x": 0},
)
return graph
def warp_graph_title_according_viewport_size(
graph, title, viewport_size_width=599, width=50
):
if viewport_size_width < 600:
graph.update_layout(
title={
"text": "<br>".join(textwrap.wrap(title, width=width)),
"xanchor": "center",
"yanchor": "top",
}
)
return graph
Directories and files
In regard to the aforementioned subject, all relevant directories and files can be found in the following locations:
- charts.py
- charts.py
- charts.py
- charts.py
- helper.py
- data_in_helmholtz.py
- fair_by_repository.py
- home.py