Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 31 ยท Plotly

Plotly Styling, Templates and Annotations

Style Plotly charts: titles, axes, color scales, templates and dark mode, hover templates, annotations, shapes and subplots, with runnable JavaScript stand-ins.

A default Plotly chart is already readable, but it rarely says what you want it to say. Styling is how you turn "a chart of the data" into "a chart that makes one point": a title that states the message, axes with units, colors that mean something, a tooltip that shows the right numbers, and a note pointing at the interesting spot.

The Plotly library cannot run on this site, so every Plotly call below is read-only. The runnable examples are stand-ins written in JavaScript: a small color-scale interpolator and a hover-template formatter. They follow the same rules Plotly uses, but they are not Plotly itself, and the exact colors Plotly picks for a named scale will differ from the three-color scale used here. All styling is just paths into the figure you met in Plotly Figures: Data, Layout and Traces, so keep that structure in mind.

Where styling lives

Layout Titles, axes, legend, size, template.
Traces Marker colors, line widths, hover text.
Templates A whole theme applied at once.

Change one thing at a time and keep the rest of the figure untouched.

1 / 2

Titles, axes and size

Titles and axis labels are layout properties. You can set them in the constructor or later with update_layout, update_xaxes and update_yaxes. This is read-only code:

Python
import plotly.express as px

fig = px.line(df, x="month", y="revenue", color="region")

fig.update_layout(
    title={"text": "Revenue grew in every region", "x": 0.02},
    width=900, height=450,
    margin={"l": 60, "r": 20, "t": 70, "b": 50},
    legend={"orientation": "h", "y": -0.2},
)
fig.update_xaxes(title_text="Month", tickformat="%b %Y", showgrid=False)
fig.update_yaxes(title_text="Revenue (USD)", tickprefix="$", separatethousands=True,
                 rangemode="tozero")

A few properties earn their place in almost every chart:

  • title.text and title.x write and align the headline. Write a sentence that states the finding, not just the variable names.
  • tickformat uses d3 formatting: ".0%" for percentages, ",.0f" for thousands separators, "%b %Y" for dates.
  • tickprefix and ticksuffix add units without changing the data.
  • range fixes an axis, rangemode="tozero" forces it to include zero, and type="log" gives a logarithmic axis.
  • showgrid, zeroline and showline control the lines around the plot. Fewer lines usually read better.

Setting width and height fixes the size. If you leave them out, the chart fills its container and resizes with the window, which is usually what a web page wants.

Colors: discrete and continuous

Plotly colors things in two different ways, and it helps to know which one you are using.

Discrete colors assign one color to each category. In Express, color="region" picks a color per region from a sequence. You can supply your own sequence or fix individual categories:

Python
px.bar(df, x="month", y="revenue", color="region",
       color_discrete_sequence=px.colors.qualitative.Safe)

px.bar(df, x="month", y="revenue", color="region",
       color_discrete_map={"North": "#1b9e77", "South": "#d95f02", "West": "#7570b3"})

Use the color_discrete_map form when a category must keep the same color across several charts on a page.

Continuous colors map a number to a color along a color scale. In Express you name it with color_continuous_scale:

Python
px.scatter(df, x="income", y="spend", color="temperature",
           color_continuous_scale="RdBu_r", color_continuous_midpoint=0)

A color scale is just a list of [position, color] pairs, where position runs from 0 to 1. The lowest value in the data maps to 0 and the highest to 1 (or to zmin and zmax if you set them). Any value in between gets a color blended from the two nearest stops. Plotly ships named scales such as Viridis and Blues (sequential, one direction) and RdBu (diverging, with a neutral middle). Add _r to a name to reverse it.

Choose the type to match the data. Order without a meaningful middle calls for a sequential scale. Values that go above and below a meaningful point, such as profit and loss or temperature around freezing, call for a diverging scale with the midpoint pinned to that value. Color, Labels and Accessibility goes deeper into picking palettes that everyone can read.

What a color scale does

The stand-in below is a tiny color-scale engine. It takes a scale of [position, color] stops, normalizes a value between a minimum and a maximum, and blends the two neighboring stops. The second block pins the middle of the scale to zero, the way color_continuous_midpoint does, by making the range symmetric around the midpoint.

JS Interpolating a color scale

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Compare the line for 0. With the plain scale it is a cool blue, because 0 is only a little above the minimum. With the midpoint pinned, 0 lands exactly on the neutral middle color (#ffffbf), so warm and cold values read as above and below zero. That is why diverging data needs a pinned midpoint: without it, the neutral color sits on the middle of the range, not on the value that matters.

Templates and dark mode

Setting twenty properties on every chart is tedious and error-prone. A template bundles default styling for a whole figure: fonts, colors, grid lines, backgrounds and the default color sequence. A template is itself a small piece of figure JSON with a layout and default trace settings, which is why it composes so well with everything else.

Plotly includes several, such as plotly, plotly_white, plotly_dark, ggplot2, seaborn, simple_white, presentation and none. Use one for a single figure or set it for everything:

Python
import plotly.io as pio

px.line(df, x="month", y="revenue", template="plotly_dark")

pio.templates.default = "simple_white"

You can also combine templates with +, for example "plotly_white+presentation", where later names win where they overlap.

Dark mode is a template choice, not a switch. If your page has a dark theme, pick a dark template for the chart and make sure the page background matches, or set paper_bgcolor and plot_bgcolor to "rgba(0,0,0,0)" so the page shows through. Check contrast on both themes; thin gray lines that look fine on white can vanish on a dark background.

Because the figure is JSON, the template travels with it. Two charts that share a template look like a family, which is the cheapest way to make a dashboard feel designed.

Hover templates

Tooltips are where a chart answers the reader's question about one point. By default Plotly shows x, y and the trace name. A hovertemplate lets you write exactly what appears:

Python
fig.update_traces(
    hovertemplate="%{x|%b %Y}<br>Revenue: $%{y:,.0f}<br>Share: %{customdata[0]:.1%}"
                  "<extra>%{fullData.name}</extra>",
    customdata=df[["share"]],
)

The mini-language works like this:

  • %{x}, %{y} and %{text} insert the point's values.
  • After a colon comes a d3 format: %{y:,.0f} is a number with thousands separators and no decimals, %{share:.1%} is a percentage with one decimal.
  • %{x|%b %Y} formats a date with a pipe and a date format.
  • <br> starts a new line.
  • <extra>...</extra> is the secondary box beside the tooltip; leave it empty (<extra></extra>) to hide the trace name.
  • customdata lets you attach extra columns to each point and show them as %{customdata[0]}.

The stand-in below implements the number part of this language, enough to show the idea: values are looked up by name and formatted by the spec after the colon, and the <extra> section is cut off, because it belongs in a separate box.

JS A tiny hovertemplate formatter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first line shows the money format with separators, the second shows a percentage and the side box text, and the third a plain two-decimal number. The real Plotly formatter supports far more (dates, SI prefixes, nested customdata indexes), but you read and write it the same way.

Annotations and shapes

Annotations and shapes mark up the plot area. They are layout properties (layout.annotations and layout.shapes), and Plotly has helper methods to append to them.

An annotation is text, optionally with an arrow, pinned to a spot. Pin it to data coordinates with xref="x", yref="y" (the default), or to the chart area with xref="paper", yref="paper", where 0 to 1 spans the plot from edge to edge:

Python
fig.add_annotation(
    x="2024-06", y=182, text="Product launch",
    showarrow=True, arrowhead=2, ax=0, ay=-50,
)
fig.add_annotation(
    xref="paper", yref="paper", x=0, y=-0.25, showarrow=False,
    text="Source: internal sales database", align="left",
)

A shape is a line, rectangle or circle. The shortcuts add_hline, add_vline, add_hrect and add_vrect cover the common cases:

Python
fig.add_hline(y=100, line_dash="dash", line_color="gray",
              annotation_text="Target", annotation_position="top left")
fig.add_vrect(x0="2024-03", x1="2024-05", fillcolor="orange", opacity=0.15,
              line_width=0, annotation_text="Promo")

The most useful trick is mixing coordinate systems. A rectangle with xref="x" and yref="paper" spans a range of dates from the bottom of the chart to the top, whatever the y values are. Use layer="below" to put a band behind the traces so it does not hide them.

Annotations are for the one or two things a reader must not miss. Ten annotations make a chart noisy, and Storytelling with Charts covers how to choose them.

Several charts in one figure

make_subplots creates a figure with a grid of axes, and you place each trace in a cell with row and col:

Python
from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(
    rows=1, cols=2, shared_yaxes=True,
    column_widths=[0.65, 0.35],
    subplot_titles=("Revenue by month", "Revenue by region"),
)
fig.add_trace(go.Scatter(x=months, y=revenue, name="Revenue"), row=1, col=1)
fig.add_trace(go.Bar(x=regions, y=totals, name="Total"), row=1, col=2)
fig.update_layout(title_text="Revenue overview", showlegend=False)
fig.update_yaxes(title_text="USD", row=1, col=1)

Under the hood, the first subplot uses xaxis and yaxis, and the second uses xaxis2 and yaxis2. Each axis has a domain, a pair of numbers between 0 and 1 saying which slice of the figure it occupies. shared_yaxes=True links the vertical scales, so the two panels are directly comparable.

For two scales on one panel (say revenue as bars and a conversion rate as a line), pass specs=[[{"secondary_y": True}]] and add_trace(..., secondary_y=True). Use dual axes sparingly; they can suggest correlations that are not there, a pitfall covered in Testing Charts and Common Pitfalls.

A styling checklist

Before you call a chart done, run through this list:

  1. Does the title state the point of the chart?
  2. Do both axes have labels, and units where they matter?
  3. Does a bar axis start at zero?
  4. Are the colors meaningful, and consistent with the other charts on the page?
  5. Does the tooltip show the numbers a reader would ask about, formatted?
  6. Is there at most one or two annotations?
  7. Does the chart still read on a dark background and for color-blind readers?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where do axis titles and tick formats belong in a Plotly figure?

    Axes belong to the chart as a whole, so their properties live in layout.xaxis and layout.yaxis.
  2. 2. You show temperatures above and below zero with a diverging color scale. What does color_continuous_midpoint=0 do?

    Without a midpoint, the neutral color sits in the middle of the data range. Pinning it makes values read as above or below zero.
  3. 3. What does %{y:,.0f} do inside a hovertemplate?

    After the colon comes a d3 format. The comma adds separators and .0f means zero decimals.
  4. 4. A rectangle uses xref="x" and yref="paper" with y0=0 and y1=1. What does it cover?

    The x extent uses data coordinates while y uses the plot area, so the band spans the full height whatever the y values are.
  5. 5. How do you apply one consistent look to every chart in a project?

    A template bundles layout and trace defaults, and setting it as the default applies it to every new figure.

Summary

  • Styling is changing paths in the figure: layout for the whole chart, traces for one series.
  • Titles should state the message; tickformat, tickprefix and rangemode make axes honest and readable.
  • Discrete colors map categories to colors; continuous color scales map numbers along [position, color] stops, and diverging data needs a pinned midpoint.
  • Templates bundle a whole theme, and dark mode is a template plus a matching page background.
  • hovertemplate writes the tooltip with %{value:format} fields and <extra> for the side box.
  • Annotations and shapes mark up the plot, and make_subplots places several charts in one figure.
  • The Plotly code is read-only here; the JavaScript examples are stand-ins for the color-scale and hover-format rules.

Next: Statistical Charts in Plotly.