Box Plots and Violin Plots in Plotly

Draw box and violin plots with px.box and px.violin: group by a second column, show every point, set category order, add means, split violins and plot precomputed quartiles.

Draw a box plot in Plotly with px.box(df, x="group", y="value") and a violin plot with px.violin() using the same arguments. Add color= to split each group, and points="all" to show the underlying data.

Quick Example

Page load times for four pages of a sample website, before and after a redesign:

import numpy as np
import pandas as pd
import plotly.express as px

rng = np.random.default_rng(74)
pages = {"Home": (2.4, 1.6), "Search": (3.1, 2.7), "Product": (2.8, 1.9), "Checkout": (3.6, 2.5)}
loads = pd.concat([
    pd.DataFrame({"page": page, "version": version,
                  "seconds": rng.lognormal(np.log(median), 0.28, 90).round(2)})
    for page, medians in pages.items()
    for version, median in zip(["Old design", "New design"], medians)
], ignore_index=True)
colors = {"Old design": "#9ca3af", "New design": "#db2777"}

fig = px.box(loads, x="page", y="seconds", color="version", color_discrete_map=colors,
             template="plotly_white", title="Page load time before and after the redesign",
             labels={"page": "Page", "seconds": "Load time (s)", "version": ""})
fig.update_layout(legend=dict(orientation="h", y=1.02, yanchor="bottom", x=1, xanchor="right"))
fig.show()

Grouped Plotly box plots of load times for four web pages, with the new design boxes lower than the old design boxes on each page

The new design lowers the median on all four pages. Search improves least, from a median of about 3.1 to 2.6 seconds. Hover a box for its quartiles, whisker ends and outliers. The code targets Plotly 6.x.

How to Read the Box

  • The line inside is the median, and the box spans the first to third quartile.
  • Whiskers reach the furthest points within 1.5 times the box height (the interquartile range) of the box.
  • Points beyond the whiskers are drawn individually as outliers.

Show All the Points

points="all" draws every value beside its box. Use points=False to hide outliers too.

checkout = loads[loads["page"] == "Checkout"]
fig = px.box(checkout, x="version", y="seconds", color="version", points="all",
             color_discrete_map=colors, template="plotly_white",
             title="Checkout page: every measurement")
fig.update_traces(jitter=0.5, pointpos=-1.8, marker=dict(size=4, opacity=0.6))
fig.update_layout(showlegend=False)
fig.show()

Box plots of checkout load times for the old and new design with all individual measurements to the left of each box

jitter (0 to 1) spreads the points sideways and pointpos moves them: 0 puts them on top of the box, negative values to the left.

Horizontal Boxes in a Set Order

Swap x and y for horizontal boxes. Sort categories with category_orders, here from the slowest median to the fastest.

new = loads[loads["version"] == "New design"]
order = new.groupby("page")["seconds"].median().sort_values(ascending=False).index.tolist()

fig = px.box(new, x="seconds", y="page", category_orders={"page": order},
             color_discrete_sequence=["#db2777"], template="plotly_white",
             title="New design: pages from slowest to fastest")
fig.show()

Horizontal box plots of new design load times, ordered with Search slowest at the top and Home fastest at the bottom

Add the Mean, Notches, or a Log Axis

boxmean=True adds a dashed mean line ("sd" also marks one standard deviation). notched=True narrows the box around the median: when two notches don't overlap, that's rough evidence the medians differ.

fig = px.box(loads, x="page", y="seconds", color="version", notched=True,
             color_discrete_map=colors, template="plotly_white",
             title="Notched boxes with mean lines, log scale", log_y=True)
fig.update_traces(boxmean=True)
fig.show()

Notched box plots on a log scale with dashed mean lines, where the notches for the old and new design do not overlap on any of the four pages

Quartile Methods: Why the Numbers May Differ

There are several ways to compute quartiles. Plotly's default, quartilemethod="linear", can differ slightly from pandas or NumPy on small samples. The other options are "inclusive" and "exclusive":

import plotly.graph_objects as go

values = [2, 4, 5, 7, 8, 10, 13, 17, 21]
fig = go.Figure([go.Box(y=values, name=m, quartilemethod=m, boxpoints="all")
                 for m in ["linear", "inclusive", "exclusive"]])
fig.update_layout(template="plotly_white", title="Same nine values, three quartile methods",
                  showlegend=False)
fig.show()

Three box plots of the same nine values using the linear, inclusive and exclusive quartile methods

The first quartile is 4.75 with "linear", 5 with "inclusive" (which matches the pandas default) and 4.5 with "exclusive". The difference rarely matters with hundreds of points. If a chart has to match a table exactly, pass the numbers in yourself.

Box Plot from Precomputed Statistics

go.Box accepts q1, median, q3 and the fences directly. This is useful when the raw data is too large to send to the browser or lives in a database.

stats = loads.groupby("page", sort=False)["seconds"].quantile([0.05, 0.25, 0.5, 0.75, 0.95]).unstack()

fig = go.Figure(go.Box(
    x=stats.index.tolist(),
    q1=stats[0.25], median=stats[0.5], q3=stats[0.75],
    lowerfence=stats[0.05], upperfence=stats[0.95],
    marker_color="#0891b2",
))
fig.update_layout(template="plotly_white", yaxis_title="Load time (s)",
                  title="Whiskers at the 5th and 95th percentiles")
fig.show()

Box plots built from precomputed quartiles with whiskers at the 5th and 95th percentiles for four pages

Violin Plot with px.violin

A violin replaces the box with a smoothed density curve, so you can see peaks and skew. box=True draws a small box plot inside.

fig = px.violin(loads, x="page", y="seconds", color="version", box=True,
                color_discrete_map=colors, template="plotly_white",
                title="Violin plot of page load times")
fig.show()

Grouped violin plots with inner box plots of old and new design load times for four pages

The curve extends a little past the smallest and largest values because it's smoothed. Add fig.update_traces(spanmode="hard") to stop it at the data limits, which avoids impossible values such as negative times.

Split Violins

To compare two groups back to back, give each half a side. This needs go.Violin, one trace per group.

fig = go.Figure()
for version, side in [("Old design", "negative"), ("New design", "positive")]:
    part = loads[loads["version"] == version]
    fig.add_violin(x=part["page"], y=part["seconds"], name=version, side=side,
                   line_color=colors[version], meanline_visible=True, spanmode="hard")
fig.update_layout(template="plotly_white", violinmode="overlay", violingap=0.15,
                  title="Split violins: old on the left, new on the right",
                  yaxis_title="Load time (s)")
fig.update_xaxes(range=[-0.6, 3.6])     # keep the first half-violin inside the plot
fig.show()

Split violin plot with the old design on the left half and the new design on the right half for each page, the right halves sitting lower

By default each violin has the same maximum width (scalemode="width"). With unequal group sizes, scalemode="count" makes width reflect the number of points.

Box vs Violin vs Histogram

Chart Best for Weakness
Box Comparing medians and spread across many groups Hides multiple peaks
Violin Seeing the shape of each group Smoothing can mislead with small samples
Histogram One or two distributions in detail Gets crowded beyond that
Strip (px.strip) Small samples, every point visible Overlap with large data

For static versions, see box plots with swarm overlays and violin plots in Seaborn.

Similar Topics