IVR
IVR

Reputation: 1858

Dash: how to control graph style via CSS?

I have a simple Dash application and I would like to set fonts and colours of my plots via CSS. Here is what my app.py looks like:

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go

def generate_plot():
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=[1, 2, 3], y=[1, 2, 3]))
    return fig

app = dash.Dash(__name__)
app.layout = html.Div(children=[
    html.H1(children="title", className="title"),
    dcc.Graph(figure=generate_plot(), class="plot")
])

I also have a file assets/style.css and i deally, I would like to extend this file with content that describes how my dcc.Graph objects should look. Is this possible? If it is, then how would I do it? I would like to be able to set fonts, background colours, line/marker colours, etc. Unfortunately, something like .plot { background-color: aqua; } in CSS has no effect. Also, html, body {font-family: serif; } has no effect too.

Upvotes: 9

Views: 5211

Answers (1)

Joel Aufrecht
Joel Aufrecht

Reputation: 463

I have addressed some of these problems, on a development-only basis, via the following:

  1. I host the CSS file on a different webserver than the dash Flask server. This seems reasonable for production architecture, but in a dev environment it's messy because the webserver address has to be specified in the url in order to use a different port than the dev Flask server (e.g., the :8050 default).

app.css.append_css(dict(external_url='http://localhost/style.css'))

  1. using this css file I can set some style-based elements of the Dash page, such as

html { background-color: aqua;}

  1. I haven't been able to find or set CSS styles in all of the auto-generated components yet, but there are hooks to set many of the style elements directly. See https://plotly.com/python/reference/#scatter for more. Splicing in code that works for me into your example, this should work:

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[1, 2, 3], textfont={'family': 'serif'}))

Upvotes: 1

Related Questions