Inspired by the FiscalData.treasury.gov website, I set out to create a clean-looking line chart template that I can insert either as a tooltip or directly into a KPI card.
Example:
Here’s the code for the figure, using some dummy random data:
import numpy as np
import plotly.express as px
1)
np.random.seed(= np.arange(len(y))
x = np.random.random_sample(24) * 100
y
= px.line(x, y)
fig = x[0]
xmin = x[-1]
xmax = round(y[0], 1)
ymin = round(y[-1], 1)
ymax
= {
layout "plot_bgcolor": "rgba(0, 0, 0, 0)",
"paper_bgcolor": "rgba(0, 0, 0, 0)",
"yaxis": {"visible": False},
"xaxis": {
"nticks": 2,
"tickmode": "array",
"tickvals": [xmin, xmax],
"ticktext": [f"{ymin} <br> {xmin}", f"{ymax} <br> {xmax}"],
"title_text": None
},"showlegend": False,
"margin": {"l":4,"r":4,"t":0, "b":0, "pad": 4}
}= {'displayModeBar': False}
config
fig.update_layout(layout)# fig.show(config = config)
# dcc.Graph(figure=fig, config = config)
I like having the layout as a dictionary so we can reuse it if we end up using a bunch of these.
Breaking down the layout
Hide the plot background:
"plot_bgcolor": "rgba(0, 0, 0, 0)",
"paper_bgcolor": "rgba(0, 0, 0, 0)",
Hide the y-axis entirely:
"yaxis": {"visible": False},
For the x-axis, show only the first and last ticks, and set the tick text to have that 2-level effect, and hide the x-axis title.
"xaxis": {
"nticks": 2,
"tickmode": "array",
"tickvals": [xmin, xmax],
"ticktext": [f"{ymin} <br> {xmin}", f"{ymax} <br> {xmax}"],
"title_text": None
},
And finally, hide the legend and clean up the margins to reduce whitespace in the card. If you don’t do this it makes for a really small plot.
"showlegend": False,
"margin": {"l":4,"r":4,"t":0, "b":0, "pad": 4}
We also need to set up the config to hide the annoying modebar, and this goes either in the fig.show()
call or the dcc.Graph()
call, depending if you’re just using Plotly or using this in Dash.
= {'displayModeBar': False} config
And here’s the code for the card:
= dbc.Card(
card
[
dbc.CardBody(
["Card title", className="card-title"),
html.H4(
html.P("$10.5 M",
="card-value",
className
),
html.P("Target: $10.0 M",
="card-target",
className
),=fig, config=config),
dcc.Graph(figure
html.Span("Up ",
="card-diff-up",
className
),
html.Span("5.5% vs Last Year",
="card-diff-up",
className
),
]
),
], )