from dash import Dash, dcc, Input, Output, State, callback, _dash_renderer
import plotly.express as px
import dash_mantine_components as dmc
from dash_iconify import DashIconify
_dash_renderer._set_react_version("18.2.0")
df = px.data.gapminder()
app = Dash(__name__)
theme_toggle = dmc.Affix(
dmc.ActionIcon(
[
dmc.Paper(DashIconify(icon="radix-icons:sun", width=25), darkHidden=True),
dmc.Paper(DashIconify(icon="radix-icons:moon", width=25), lightHidden=True),
],
variant="transparent",
color="yellow",
id="color-scheme-toggle",
size="lg",
ms="auto",
),
position={"top": 10, "right": 10}
)
sample_controls = dmc.Box([
dmc.Button("sample button"),
dmc.Button("sample red button", color="red"),
dmc.Button("sample yellow button", color="yellow"),
dmc.Slider(value=25, my="lg"),
], w=600)
layout = dmc.Box(
[
theme_toggle,
dmc.Title("Figure Template Demo", ta="center"),
dmc.Text("Change theme to see 'mantine_light' and 'mantine_dark' figure templates", ta="center"),
sample_controls,
dcc.Loading(dmc.Box(id="output-container"), delay_hide=1000),
],
p="lg"
)
app.layout=dmc.MantineProvider(
layout,
forceColorScheme="light",
id="mantine-provider"
)
@callback(Output("output-container", "children"), Input("mantine-provider", "forceColorScheme"))
def update(color_scheme):
template = "mantine_light" if color_scheme == "light" else "mantine_dark"
line_fig = px.line(
df.query("1952 <= year <= 1982 & continent != 'Asia'"),
x="year",
y="gdpPercap",
color="continent",
line_group="country",
template=template,
)
dff = df[df.year == 2007]
scatter_fig = px.scatter(
dff,
x="gdpPercap",
y="lifeExp",
size="pop",
color="continent",
log_x=True,
size_max=60,
template=template,
title=f"2007 GDP per Capita vs Life Expectancy, Sized by Population ",
)
avg_lifeExp = (dff["lifeExp"] * dff["pop"]).sum() / dff["pop"].sum()
map_fig = px.choropleth(
dff,
locations="iso_alpha",
color="lifeExp",
template=template,
title="%.0f World Average Life Expectancy was %.1f years" % (2007, avg_lifeExp),
)
hist_fig = px.histogram(dff, x='lifeExp', title='2007 Distribution of Life Expectancy', template=template)
return dmc.Grid(
[
dmc.GridCol(dcc.Graph(figure=hist_fig), span={"base": 12, "md":6}),
dmc.GridCol(dcc.Graph(figure=scatter_fig), span={"base": 12, "md":6}),
dmc.GridCol(dcc.Graph(figure=line_fig), span={"base": 12, "md":6}),
dmc.GridCol(dcc.Graph(figure=map_fig), span={"base": 12, "md":6}),
],
gutter="xl",
)
@callback(
Output("mantine-provider", "forceColorScheme"),
Input("color-scheme-toggle", "n_clicks"),
State("mantine-provider", "forceColorScheme"),
prevent_initial_call=True,
)
def switch_theme(_, theme):
return "dark" if theme == "light" else "light"
if __name__ == "__main__":
app.run_server(debug=True)