GithubHelp home page GithubHelp logo

annmariew / dash-bootstrap-templates Goto Github PK

View Code? Open in Web Editor NEW
110.0 4.0 20.0 377 KB

A collection of 52 Plotly figure templates with a Bootstrap theme. Two theme switch components. Stylesheet to apply Bootstrap themes to Plotly Dash components.

Home Page: https://hellodash.pythonanywhere.com/

License: MIT License

Python 68.72% CSS 31.28%
plotly-dash bootstrap theme

dash-bootstrap-templates's Introduction

Dash Bootstrap Templates

dash-bootstrap-templates library provides:

  • 52 Bootstrap themed Plotly figure templates

    • You will find a Plotly template for each of the 26 Bootstrap/Bootswatch themes available in the Dash Bootstrap Components Library. These templates will automatically style your figures with Bootstrap theme colors and fonts.
    • As of V1.1 a dark mode is available for each theme. This is ideal for use with the Bootstrap Color Modes available as of Bootstrap 5.3.0
  • Two All-in-One components to change themes in a Dash app.

    • ThemeSwitchAIO toggles between two themes.
    • ThemeChangerAIO select from multiple themes.
  • Examples of a Color Mode Switch to toggle between a light and dark theme.

  • The dbc.css stylesheet which styles Dash AG Grid, Dash Core Components and the Dash DataTable with a Bootstrap theme.

Usage Notes:

  • The ThemeChangerAIO component and the dbc.css stylesheet requires Dash Bootstrap Components>=V1.0.0. It will only work with the themes included in Dash Bootstrap Components>=V1.0.0.

  • As of V1.0.8, the themes in the ThemeSwitchAIO component can be specified as a pathname or a URL. This allows for working off-line and with custom stylesheets.

  • The Bootstrap themed Plotly figure templates can be used with any Plotly figure. It does not require Dash or the Dash Bootstrap Components library.



Figure Template Quickstart

pip install dash-bootstrap-templates

Learn more about Plotly figure templates and themes at: https://plotly.com/python/templates/

"""
A sample of 8 of the 26 Bootstrap themed Plotly figure templates available
in the dash-bootstrap-template library

"""
from dash import Dash, html, dcc
import dash_bootstrap_components as dbc
from dash_bootstrap_templates import load_figure_template
import plotly.express as px

df = px.data.gapminder()

templates = [
    "bootstrap",
    "minty",
    "pulse",
    "flatly",
    "quartz",
    "cyborg",
    "darkly",
    "vapor",
]

load_figure_template(templates)

figures = [
    px.scatter(
        df.query("year==2007"),
        x="gdpPercap",
        y="lifeExp",
        size="pop",
        color="continent",
        log_x=True,
        size_max=60,
        template=template,
        title="Gapminder 2007: '%s' theme" % template,
    )
    for template in templates
]

app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = dbc.Container([dcc.Graph(figure=fig, className="m-4") for fig in figures])

if __name__ == "__main__":
    app.run_server(debug=True)

image image image image

figure_template2



dbc.css stylesheet

The dash-ag-grid, dash-core-components, the Dash DataTable and Plotly figures are not automatically styled with a Bootstrap theme. An easy way to make your Dash components look better with a Bootstrap theme is to use the stylesheet from the dash-bootstrap-templates library. This stylesheet defines the "dbc" class.

Adding className="dbc dbc-ag-grid" minimally styles Dash components with your selected Bootstrap theme:

  • Makes the text readable in both light and dark themes.
  • Uses theme's font-family.
  • Changes the accent color to the theme's primary color

You can add the dbc class as an external stylesheet like this:

dbc_css = ("https://cdn.jsdelivr.net/gh/AnnMarieW/[email protected]/dbc.min.css")
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP, dbc_css])

Add className="dbc dbc-ag-grid" to the outer container of the app or a component like this:

app.layout = dbc.Container(
    [
        ...
    ],
    fluid=True,
    className="dbc dbc-ag-grid"
)

That's it! Simply adding className="dbc dbc-ag-grid" will make Dash AG Grid, Dash Core Components and the DataTable look better with ALL themes included in the dash-bootstrap-components library.

See a live demo at: https://hellodash.pythonanywhere.com/adding-themes/dcc-components

If you have suggestion for improvements or if you find a bug, please let us know on the issue tracker

Requires dash-bootstrap-components>=V1.0.0

Theme Switcher Components

See a live demo at https://hellodash.pythonanywhere.com/theme_change_components

dash-bootstrap-templates has two All-in-One components to change themes. The ThemeSwitchAIO is a switch with icons on the left and right, which is ideal for toggling between a light and a dark theme. The ThemeChangerAIO has a button that opens an dbc.Offcanvas component which by default shows all the available themes.

Note the All-in-One component switches the Bootstrap stylesheet for the app and sets the default Plotly figure template for the theme, however, figures must be updated in a callback in order to render the figure with the new template. See the callback below for an example. The template_from_url is a helper function that returns the template name based on the theme url. For example template_from_ur(dbc.themes.SLATE) returns "slate"



ThemeChangerAIO Quickstart

from dash import Dash, dcc, html, Input, Output
import pandas as pd
import plotly.express as px
import dash_bootstrap_components as dbc
from dash_bootstrap_templates import ThemeChangerAIO, template_from_url


dbc_css = (
    "https://cdn.jsdelivr.net/gh/AnnMarieW/[email protected]/dbc.min.css"
)
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP, dbc_css])


df = pd.DataFrame(
    {
        "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
        "Amount": [4, 1, 2, 2, 4, 5],
        "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"],
    }
)
header = html.H4(
    "ThemeChangerAIO Demo", className="bg-primary text-white p-4 mb-2 text-center"
)
buttons = html.Div(
    [
        dbc.Button("Primary", color="primary"),
        dbc.Button("Secondary", color="secondary"),
        dbc.Button("Success", color="success"),
        dbc.Button("Warning", color="warning"),
        dbc.Button("Danger", color="danger"),
        dbc.Button("Info", color="info"),
        dbc.Button("Light", color="light"),
        dbc.Button("Dark", color="dark"),
        dbc.Button("Link", color="link"),
    ],
    className="m-4",
)
graph = html.Div(dcc.Graph(id="graph"), className="m-4")

app.layout = dbc.Container(
    [
        header,
        dbc.Row(
            [
                dbc.Col(ThemeChangerAIO(aio_id="theme", radio_props={"value":dbc.themes.FLATLY}), width=2,),
                dbc.Col([buttons, graph],width=10),
            ]
        ),
    ],
    className="m-4 dbc",
    fluid=True,
)


@app.callback(
    Output("graph", "figure"), Input(ThemeChangerAIO.ids.radio("theme"), "value"),
)
def update_graph_theme(theme):
    return px.bar(
        df, x="Fruit", y="Amount", color="City", barmode="group", template=template_from_url(theme)
    )


if __name__ == "__main__":
    app.run_server(debug=True)

theme_changer


Here is the same app, but using a the ThemeSwitchAIO component to toggle between two themes. See the (code here).

It's also possible to change the icons. See an example of using Bootstrap icons instead of the default FontAwesome icons here.

theme_toggle



Color Mode Switch

Requires dash-bootstrap-components>=1.5.0

This is the recommended way to switch between a light and a dark mode using Bootstrap Color modes available in Bootstrap 5.3.0.

color-mode-templates

from dash import Dash, html, dcc, Input, Output, clientside_callback, callback
import plotly.express as px
import dash_bootstrap_components as dbc

from dash_bootstrap_templates import load_figure_template
load_figure_template(["minty", "minty_dark"])


df = px.data.gapminder()

app = Dash(__name__, external_stylesheets=[dbc.themes.MINTY, dbc.icons.FONT_AWESOME])

color_mode_switch =  html.Span(
    [
        dbc.Label(className="fa fa-moon", html_for="switch"),
        dbc.Switch( id="switch", value=False, className="d-inline-block ms-1", persistence=True),
        dbc.Label(className="fa fa-sun", html_for="switch"),
    ]
)

app.layout = dbc.Container(
    [
        html.Div(["Bootstrap Light Dark Color Modes Demo"], className="bg-primary text-white h3 p-2"),
        color_mode_switch,
        dcc.Graph(id="graph", className="border"),
    ]

)

@callback(
    Output("graph", "figure"),
    Input("switch", "value"),
)
def update_figure_template(switch_on):
    template = "minty" if switch_on else "minty_dark"
    fig = px.scatter(
        df.query("year==2007"),
        x="gdpPercap",
        y="lifeExp",
        size="pop",
        color="continent",
        log_x=True,
        size_max=60,
        template=template,
    )
    return fig



clientside_callback(
    """
    (switchOn) => {
       switchOn
         ? document.documentElement.setAttribute('data-bs-theme', 'light')
         : document.documentElement.setAttribute('data-bs-theme', 'dark')
       return window.dash_clientside.no_update
    }
    """,
    Output("switch", "id"),
    Input("switch", "value"),
)


if __name__ == "__main__":
    app.run_server(debug=True)


Dash AG Grid with a Bootstrap theme

Here is an example of the theme change component to show different Bootstrap themes with Dash AG Grid:

See live demo https://hellodash.pythonanywhere.com/adding-themes/ag-grid

ag-grid-dbc-theme



Background

Dash Labs is Plotly library that explores new features for future releases of Dash. In Dash Labs V0.4.0, there was a cool feature where Bootstrap themed figure templates were created "on the fly". This was a part of the layout templates project that is no longer being developed.

Even though these Bootstrap themed figure templates will not be included in Dash, the dash-bootstrap-templates makes them available to you. The figure templates are created using the Dash Labs' algorithms and saved in json format. When you use load_figure_template() in your app, it loads the json file, adds it to plotly.io and sets it as the default figure template for an app. See more information about Plotly figure templates here.



Available Themes

This library provides a figure template for the following Bootstrap/Bootswatch themes:

templates = [ "bootstrap", "cerulean", "cosmo", "cyborg", "darkly", "flatly", "journal", "litera", "lumen", "lux", "materia", "minty", "morph", "pulse", "quartz", "sandstone", "simplex", "sketchy", "slate", "solar", "spacelab", "superhero", "united", "vapor", "yeti", "zephyr" ]

templates_dark = ['bootstrap_dark', 'cerulean_dark', 'cosmo_dark', 'cyborg_dark', 'darkly_dark', 'flatly_dark', 'journal_dark', 'litera_dark', 'lumen_dark', 'lux_dark', 'materia_dark', 'minty_dark', 'morph_dark', 'pulse_dark', 'quartz_dark', 'sandstone_dark', 'simplex_dark', 'sketchy_dark', 'slate_dark', 'solar_dark', 'spacelab_dark', 'superhero_dark', 'united_dark', 'vapor_dark', 'yeti_dark', 'zephyr_dark']

Note in dark themes ["cyborg", "darkly", "slate", "solar", "superhero", "vapor"], there is not much difference in the figure templates in light or dark color modes.

ThemeChangerAIO Reference

ThemeChangerAIO is an All-in-One component composed of a parent html.Div with the following components as children:

  • dbc.Button ("switch") Opens the Offcanvas component for user to select a theme.
  • dbc.Offcanvas ("offcanvas")
  • dbc.RadioItems ("radio"). The themes are displayed as RadioItems inside the dbc.Offcanvas component. The value is a url for the theme
  • html.Div is used as the Output of the clientside callbacks.

The ThemeChangerAIO component updates the stylesheet when the value of radio changes. (ie the user selects a new theme)

  • param: radio_props A dictionary of properties passed into the dbc.RadioItems component. The default value is dbc.themes.BOOTSTRAP
  • param: button_props A dictionary of properties passed into the dbc.Button component.
  • param: offcanvas_props. A dictionary of properties passed into the dbc.Offcanvas component
  • param: aio_id The All-in-One component ID used to generate components' dictionary IDs.

The All-in-One component dictionary IDs are available as:

  • ThemeChangerAIO.ids.radio(aio_id)
  • ThemeChangerAIO.ids.offcanvas(aio_id)
  • ThemeChangerAIO.ids.button(aio_id)

ThemeSwitchAIO Reference

ThemeSwitchAIO is an All-in-One component composed of a parent html.Div with the following components as children:

  • dbc.Switch ("switch") with icons to the left and right of the switch.
  • dcc.Store ("store") The themes are stored in the data prop.
  • html.Div is used as the Output of the clientside callbacks.

The ThemeSwitchAIO component updates the stylesheet when triggered by changes to the value of switch or when the themes are updated in the "store" component. The themes in the switch may be updated in a callback by changing the theme urls in the "store" component.

  • param: switch_props A dictionary of properties passed into the dbc.Switch component.
  • param: themes A list of two urls for the external stylesheets or pathnames to files.
  • param: icons A dict of the icons to the left and right of the switch. The default is
    {"left" :"fa fa-moon", "right" :"fa fa-sun"}.
  • param: aio_id The All-in-One component ID used to generate component's dictionary IDs.

The All-in-One component dictionary IDs are available as

  • ThemeSwitchAIO.ids.switch(aio_id)
  • ThemeSwitchAIO.ids.store(aio_id)

Contributors

Special thanks to @tcbegley and @emilhe for their help with this project.

dash-bootstrap-templates's People

Contributors

ann-marie-ward avatar annmariew avatar bsd3v avatar oliverb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

dash-bootstrap-templates's Issues

Placeholder wrong color?

https://cdn.jsdelivr.net/gh/AnnMarieW/dash-bootstrap-templates@master/dbc.css

.dbc input::placeholder {
  color: var(--bs-body-color) !important;
  background-color: var(--bs-body-bg) !important;
}
.form-control::placeholder {
  color: var(--bs-secondary-color);
  opacity: 1;
}

Shoudn't the placeholder be gray insted of black?

Screenshot_20231002_170802

Also could the placeholder color for dbc.Input and dcc.Dropdown be synced. It seems that they are different even if it's bs-secondary-color?

.Select-placeholder {
  color: var(--bs-secondary-color) !important;
  background-color: var(--bs-body-bg) !important;
}

Seems to fix it but brobably need .dbc tags.

Regression bug: Background color of graph no longer transparent

There seems to be a regression from version 1.0.8 to version 1.1.0. I have created this tiny example to show the difference:

#!/usr/bin/env python
from dash import Dash, html, dcc
import dash_bootstrap_components as dbc
from dash_bootstrap_templates import load_figure_template
import plotly.graph_objects as go


load_figure_template('darkly')

app = Dash(__name__, external_stylesheets=[dbc.themes.DARKLY])

app.layout = html.Div([
    dbc.Card(
        dbc.CardBody(
            dcc.Graph(figure=go.Figure(go.Scatter(x=[1, 2, 3], y=[2, 5, 3]))),
        )
    )
])


if __name__ == '__main__':
    app.run(debug=True, port=8080)

When running on version 1.1.0, it looks like this:
image

But prior to this version, e.g. version 1.0.8, it looked like this:
image

The difference might seem small, but when you add labels on the axes, titles, etc. the old version looks much better.
Do you agree that this is a regression or is it intended behavior? It there an easy fix or workaround?

ModuleNotFoundError: No module named 'dash_bootstrap_templates'

My code:

from dash import Dash, callback, callback_context, dcc, dash_table, html, Input, Output, State
import dash_bootstrap_components as dbc
from dash_bootstrap_templates import load_figure_template
load_figure_template("darkly")

app = Dash(
    __name__,
    external_stylesheets=[
        dbc.themes.DARKLY,
        dbc.icons.FONT_AWESOME,
    ],
)

if __name__ == "__main__":
    app.run_server(debug=True)

The error:

Traceback (most recent call last):
  File "/Users/mi/Downloads/app.py", line 3, in <module>
    from dash_bootstrap_templates import load_figure_template
ModuleNotFoundError: No module named 'dash_bootstrap_templates'

I do have dash-bootstrap-templates installed:

pip show dash-bootstrap-templates

Name: dash-bootstrap-templates
Version: 1.1.0
Summary: A collection of Plotly figure templates with a Bootstrap theme
Home-page: https://github.com/AnnMarieW/dash-bootstrap-templates
Author: AnnMarieW
Author-email: 
License: MIT
Location: /opt/homebrew/lib/python3.11/site-packages
Requires: dash, dash-bootstrap-components, numpy
Required-by: 

May I ask why dash-bootstrap-templates is not recognized by python?

App Images

demo_minty.py
image

demo cyborg
image

demo superhero
image

demo_quickstart.py
image

Dash Labs figure_template=True theme = Slate

image

Dash-Bootstrap-Templates theme-Slate - V1

image

Dash-Bootstrap-Templates theme-Slate - V2

image

Dash Bootstrap Templates -- Theme=MINTY V1

image

Dash Bootstrap Templates -- Theme=MINTY V2

image

theme_toggle


theme_changer

Select-Control should have border 1px instead of 2px

The border attribute in the .dbc .Select-control { css class should have a pixel of 1 instead of the 2. The image below compares the dcc dropdown component to the dbc select component.

image

Code to re-create:

# package imports
import dash
from dash import html, dcc
import dash_bootstrap_components as dbc

dbc_css = 'https://cdn.jsdelivr.net/gh/AnnMarieW/dash-bootstrap-templates/dbc.css'

app = dash.Dash(
    __name__,
    external_stylesheets=[
        dbc_css,
        dbc.themes.BOOTSTRAP
    ]
)

app.layout = html.Div(
    [
        'dcc Dropdown',
        dcc.Dropdown(placeholder='dcc Dropdown'),
        'dbc Select',
        dbc.Select(placeholder='dbc Select')
    ],
    className='dbc w-25 m-auto'
)

if __name__ == "__main__":
    app.run_server(debug=True)

Hover text font

Great library thanks!!

Wondering if there's a way to get the font in the figure hover text to update according to the template? Currently the remainder of the figure is correct font except for hover items.

Background of input elements in dark mode does not stand out

Thanks for making this library, it's incredibly helpful to have a consistent background when using Plotly figures! I'm currently noticing an issue where the background of input elements is the same as the container background when using dark backgrounds. If I remove the custom dash-bootstrap-templates CSS, the background of the input returns to white for contrast. In the image below, the input element is followed by a select element to show the difference.

Screenshot 2023-09-15 at 9 54 15 AM
from dash import Dash
import dash_bootstrap_components as dbc

dbc_css = ("https://cdn.jsdelivr.net/gh/AnnMarieW/[email protected]/dbc.min.css")
app = Dash(__name__, external_stylesheets=[dbc.themes.DARKLY, dbc_css])

app.layout = dbc.Container(
    [
        dbc.Input(placeholder="Test", class_name="mt-3"),
        dbc.Select(class_name="mt-3", options=[{
            "label": "Sample", "value": "sample"
        }]),
    ],
    fluid=True,
    class_name="dbc"
)

if __name__ == "__main__":
    app.run_server(debug=True)

It looks like line 64 of the stylesheet is causing this, is it intentional?

/* Use this classname for dcc.Input */
.dbc input:not([type=radio]):not([type=checkbox]) {
  color: var(--bs-body-color) !important;
  background-color: var(--bs-body-bg) !important;
}

How to make ThemeSwitchAIO change the css class?

Hi @AnnMarieW

thanks for these useful templates! I am kinda new to all this ๐Ÿ˜„

I would like to add a dark mode to my web app.

I added a ThemeSwitchAIO component to the layout (without changing the graph template yet).

It changes the default settings (background, primary colour, etc.) as expected. However, some of my components have custom css where the background colour is set to white. Also the dcc.Tabs component seems unaffected. See screenshots below.

surely there is something I'm not doing right.

Do you have any idea?

Thanks in advance for your support!

Remi

light mode
image

"dark" mode
image

Update dash-bootstrap-templates 1.0.4, update importlib-metadata to the latest version.

Error dash-bootstrap-templates 1.0.4 depends on importlib-metadata<4.0.0 and >=3.4.0

I am looking to deploy an app that uses dash-bootstrap-templates however my requirements.txt requires importlib-metadata==4.2.0. & dash-bootstrap-templates is dependent on importlib=metadata<4.00. Since the requirement isn't updated to the latest version I get a build error. Looking to update the dependency of importlib-metadata to the latest version for dash-bootstrap-templates.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.