**Python Interactive Data Visualization Framework: Dash (part 1) **

Styles the Dash application

Dash gives you a lot of flexibility to customize the look and feel of your application. You can use your own CSS or JavaScript files, set ICONS (small ICONS that appear in a Web browser), and embed images with advanced options.

In this section, you’ll learn how to apply custom styles to components and then set styles for the dashboards you built in the previous section.

How do I apply custom styles to components

You can style components in two ways:

1. Use style parameters for individual components

2. Provide an external CSS file

Customizing the dashboard with the style parameter is simple. This parameter takes a Python dictionary with key-value pairs consisting of the name of the CSS property and the value to be set.

If you want to change the size and color of the H1 element in app.py, you can set the style parameter of the element as follows:

HTML.H1 (children = "Avocado Analytics", style = {" fontSize ":"48Px ", "color" : "red"},),Copy the code

Here, you can style the dictionary using properties and the values to be set for them. In this case, the specified style should have a red title with a font size of 48 pixels.

The downside of using the style parameter is that it doesn’t scale well as the code base grows. If you have multiple components in your information center that you want to look the same, you will have to write a lot of code over and over again. Instead, you can use custom CSS files.

If you want to include your own native CSS or JavaScript files, you need to create a folder called Asset/in the root of your project, where the files to be added will be stored. By default, Dash automatically provides any files contained in Asset /. As shown later, this can also be used to add favorites ICONS or embed images.

You can then style the component using CSS using its className or ID parameter. These parameters, when converted to HTML tags, correspond to the class and ID attributes.

If you want to adjust the font size and text color of the H1 element in app.py, you can use the className parameter, as follows:

html.H1(
    children="Avocado Analytics",
    className="header-title",),Copy the code

Setting the className parameter defines the class attribute of the H1 element. You can then specify the look and feel using a CSS file in the Assets folder:

.header-title {
  font-size: 48px;
  color: red;
}
Copy the code

You can use class selectors to format titles in CSS files. This selector will adjust the title format. You can also use it with other elements that need to share formats by setting className = “header-title.”

Next, you will set styles for the dashboard.

How to improve the appearance of the dashboard

The basics of styling in Dash were introduced earlier. Now you’ll learn how to customize the look and feel of the dashboard. You will make the following improvements:

  • Add an icon and a title to the page
  • Change the font family for the dashboard
  • Style Dash components using external CSS files

First, you’ll learn how to use external resources in your application. This way, you can add ICONS, customize font families, and CSS stylesheets. Then, you’ll learn how to apply custom styles to Dash components using the className parameter.

Add external resources to your application

Create a folder called Asset/in the root directory of your project. Download an icon from the Twemoji open source project and save it as Favicon.ico in Asset /. Finally, create a CSS file named style.css in assets/and create the following code.

body {
    font-family: "Lato", sans-serif;
    margin: 0;
    background-color: #F7F7F7;
}

.header {
    background-color: #222222;
    height: 256px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.header-emoji {
    font-size: 48px;
    margin: 0 auto;
    text-align: center;
}

.header-title {
    color: #FFFFFF;
    font-size: 48px;
    font-weight: bold;
    text-align: center;
    margin: 0 auto;
}

.header-description {
    color: #CFCFCF;
    margin: 4px auto;
    text-align: center;
    max-width: 384px;
}

.wrapper {
    margin-right: auto;
    margin-left: auto;
    max-width: 1024px;
    padding-right: 10px;
    padding-left: 10px;
    margin-top: 32px;
}

.card {
    margin-bottom: 24px;
    box-shadow: 0 4px 6px 0 rgba(0.0.0.0.18);
}
Copy the code

Assets/files contain component styles that you will apply to the layout of your APP. Your project structure should now look like this:

Avocado_exercises / │ ├─ ├─ vrivo.txt/vrivo.txt/vrivo.txt/vrivo.txt/vrivo.txt/vrivo.txtCopy the code

After starting the server, Dash automatically provides the files located in Assets /. You include two files in asset/ : favicon.ico and style.css. You do not need to take any additional steps to set the default icon. To use the style you defined in style.css, you need to use the className parameter in the Dash component.

App.py needs some changes. This includes an external stylesheet to add headers to the dashboard and to style components using style.css files. View the changes below. Then, at the end of this section, you’ll find the full code for the updated version of app.py.

You can add an external stylesheet and a title to the dashboard by:

external_stylesheets = [
    {
        "href""https://fonts.googleapis.com/css2?"
                "family=Lato:wght@400; 700&display=swap"."rel""stylesheet",
    },
]
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.title = "Avocado Analytics: Understand Your Avocados!"
Copy the code

On lines 11 through 18, specify the external CSS file, the font family, that you want to load in your application. External files are added to the application’s head tag and loaded before the application body is loaded. You can use the external_stylesheets parameter to add external CSS files or external_scripts to external JavaScript files such as Google Analytics.

In line 19, set the title of the application. This is the text that appears in the title bar of web browsers, in Google search results and on social media cards when sharing websites.

Custom component styles

To use styles in style.css, you need to use the className parameter in the Dash component. The following code adds a className with the corresponding class selector to each component that makes up the dashboard title:

app.layout = html.Div(
    children=[
        html.Div(
            children=[
                html.P(children="??????", className="header-emoji"),
                html.H1(
                    children="Avocado Analytics", className="header-title"
                ),
                html.P(
                    children="Analyze the behavior of avocado prices"
                    " and the number of avocados sold in the US"
                    " between 2015 and 2018",
                    className="header-description",
                ),
            ],
            className="header",),Copy the code

In lines 21 through 37, you can see that two changes have been made to the initial version of the dashboard:

1. The new paragraph element with the avocado emoji will be used as the logo.

2. Each component has a className parameter. These class names should match the class selector in style.css, which defines the appearance of each component.

For example, a header-description class assigned to a paragraph component beginning with “Analyze the behavior of avocado prices” has the corresponding selector in style.css:

.header-description {
    color: #CFCFCF;
    margin: 4px auto;
    text-align: center;
    max-width: 384px;
}
Copy the code

Lines 29 through 34 of style.css define the format of the header-description class selector. These change the color, margins, alignment, and maximum width of any component with className = “header-description.” All components have corresponding class selectors in the CSS file.

Another important change is in the diagram. Here’s the new code for the price chart:

html.Div(
    children=[
        html.Div(
            children=dcc.Graph(
                id="price-chart",
                config={"displayModeBar": False},#43Line figure = {"data": [{"x": data["Date"]."y": data["AveragePrice"]."type""lines"."hovertemplate""$%{y:.2f}"#50line"<extra></extra>"#,51},],"layout": {#54line"title": {
                            "text""Average Price of Avocados"."x"0.05."xanchor""left",},"xaxis": {"fixedrange": True},
                        "yaxis": {
                            "tickprefix""$"."fixedrange": True,
                        },
                        "colorway": ["#17B897"#]}66Line}), the className ="card"#,69Line),Copy the code

In this code, you will define a className and some customizations for the config and Figure parameters of the diagram. The changes are as follows:

  • Line 43: You remove the float bar that Plotly displays by default.
  • Lines 50 and 51: Set up the hover template so that it displays the price in dollars when the user hovers over the data-point. Instead of 2.5, it appears asThe $2.5.
  • Lines 54 through 66: In the layout section of the chart, you can adjust the axis, color of the graph, and title format.
  • Line 69: Use"Card"Class wraps the graph inhtml.DivIn the. This will give the figure a white background and add a small shadow underneath it. Similar adjustments were made to the sales and quantity charts.

You can view the updated app.py in full code in the collapsible section below.

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

data = pd.read_csv("avocado.csv")
data = data.query("type == 'conventional' and region == 'Albany'")
data["Date"] = pd.to_datetime(data["Date"], format="%Y-%m-%d")
data.sort_values("Date", inplace=True)

external_stylesheets = [
    {
        "href""https://fonts.googleapis.com/css2?"
        "family=Lato:wght@400; 700&display=swap"."rel""stylesheet",
    },
]
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.title = "Avocado Analytics: Understand Your Avocados!"

app.layout = html.Div(
    children=[
        html.Div(
            children=[
                html.P(children="??????", className="header-emoji"),
                html.H1(
                    children="Avocado Analytics", className="header-title"
                ),
                html.P(
                    children="Analyze the behavior of avocado prices"
                    " and the number of avocados sold in the US"
                    " between 2015 and 2018",
                    className="header-description",
                ),
            ],
            className="header",
        ),
        html.Div(
            children=[
                html.Div(
                    children=dcc.Graph(
                        id="price-chart",
                        config={"displayModeBar": False},
                        figure={
                            "data": [{"x": data["Date"]."y": data["AveragePrice"]."type""lines"."hovertemplate""$%{y:.2f}"
                                                     "<extra></extra>"],},"layout": {
                                "title": {
                                    "text""Average Price of Avocados"."x"0.05."xanchor""left",},"xaxis": {"fixedrange": True},
                                "yaxis": {
                                    "tickprefix""$"."fixedrange": True,
                                },
                                "colorway": ["#17B897"],
                            },
                        },
                    ),
                    className="card",
                ),
                html.Div(
                    children=dcc.Graph(
                        id="volume-chart",
                        config={"displayModeBar": False},
                        figure={
                            "data": [{"x": data["Date"]."y": data["Total Volume"]."type""lines"],},"layout": {
                                "title": {
                                    "text""Avocados Sold"."x"0.05."xanchor""left",},"xaxis": {"fixedrange": True},
                                "yaxis": {"fixedrange": True},
                                "colorway": ["#E12D39"],
                            },
                        },
                    ),
                    className="card",
                ),
            ],
            className="wrapper",),)if __name__ == "__main__":
    app.run_server(debug=True)
Copy the code

This is an updated version of app.py. It makes the necessary changes to the code to add favorites ICONS and page titles, update font families, and use external CSS files. After making these changes, the dashboard should look like this:

In the next section, you’ll learn how to add interactive components to your dashboard.

Python Interactive Data Visualization Framework: Dash (part 1) \

Read more

Top 10 Best Popular Python Libraries of 2020 \

2020 Python Chinese Community Top 10 Articles \

5 minutes to quickly master the Python timed task framework \

Special recommendation \

\

Click below to read the article and join the community