Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 31 ยท Plotly

Statistical Charts in Plotly

Build histograms, box plots, violins, density heatmaps, trendlines, marginal plots and error bars in Plotly, and see how the numbers behind them are computed.

Some charts show your data as it is: one mark per row. Statistical charts do something different. They summarize many rows into a shape: a histogram counts values in bins, a box plot reduces a column to five numbers, a violin draws an estimated density, and a trendline draws a fitted model. The chart you see is the output of a small calculation, and knowing that calculation tells you what the picture can and cannot claim.

Plotly makes these charts a one-line job. In Plotly Express you call px.histogram, px.box, px.violin, px.density_heatmap and so on, and the summary is computed for you. This lesson shows the calls, explains what is computed, and uses runnable Python to reproduce the key calculations so the charts stop being magic. If you need the basics first, read Plotly Express Basics and Plotly Figures: Data, Layout and Traces.

The Plotly library itself cannot run on this site: it needs a Python environment with a package install, and it renders with a JavaScript engine that is not loaded here. The Plotly code in this lesson is read-only. The runnable examples are stand-ins: plain Python with NumPy that performs the same statistics Plotly performs, so you can check numbers and see the logic. They draw text bars, not real Plotly output.

Histograms: counting values in bins

A histogram answers "how are the values of one column distributed?" Plotly Express does the binning for you:

Python
import plotly.express as px

df = px.data.tips()  # a small sample dataset that ships with Plotly

fig = px.histogram(df, x="total_bill", nbins=20)
fig.show()

The bars are bins, and the bar height is a count by default. Three arguments change that:

  • nbins sets the maximum number of bins (Plotly may pick a slightly different count so the edges land on round numbers).
  • histnorm rescales the heights: "percent", "probability", "density" or "probability density".
  • histfunc replaces counting with another summary of a second column, for example histfunc="avg" together with y="tip" to show the average tip per bill bin.

Adding color="day" splits the bars by category, and barmode="overlay" with opacity=0.6 lets you compare the shapes. The bin edges are the key to reading the chart. Too few bins hide structure; too many turn the picture into noise. Always try two or three values of nbins before you believe a pattern.

The runnable example below does the counting by hand. It uses equal-width bins and prints a text bar for each, once as counts and once as a probability density. A density is chosen so that the total area of the bars is 1, which makes histograms with different bin widths comparable.

Python Histogram bins, counts and density (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Run it and compare the two tables. The shape of the distribution is the same, but with 12 bins you can see detail that 6 bins smooth away. The area line always prints 1.0, which is the definition of a density. (NumPy puts the last value on the right edge into the final bin; Plotly's rules for edges are similar but not guaranteed to match in every corner case.)

Box plots: five numbers and the outliers

A box plot reduces a column to its quartiles. The box spans the first quartile (Q1, a quarter of the values are below it) to the third quartile (Q3), with a line at the median. The whiskers extend to the most extreme values within 1.5 times the interquartile range (IQR = Q3 - Q1) from the box. Points beyond the whiskers are drawn individually as outliers.

Python
fig = px.box(df, x="day", y="total_bill", color="smoker", points="outliers")
fig.show()

The points argument controls the dots: "outliers" (default), "all" to show every row next to the box, "suspectedoutliers" or False. Showing all points is a good habit for small datasets, because a box can hide that there are only six values.

There is a subtle detail: there is more than one way to compute a quartile. The quartilemethod argument of the box trace accepts "linear" (the default), "exclusive" and "inclusive". The exclusive and inclusive methods split the sorted data at the median and take the median of each half; they differ only in whether the median value itself belongs to both halves when the count is odd. For a large dataset the differences vanish, but for ten or twenty points the box can move visibly. The next example computes all three.

Python Quartiles three ways, whiskers and outliers (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With twelve values (an even count) the exclusive and inclusive methods agree, but interpolation gives a slightly different Q1 and Q3. Add or remove one value to make the count odd and all three can differ. Also notice how the value 41 ends up beyond the upper fence and becomes an outlier dot. Plotly's own "linear" method may differ from NumPy's default in the last decimal on small samples, so when you must match an exact number, set the method explicitly and check.

Violin plots and density estimates

A violin plot replaces the box with a smooth outline of the distribution. The outline comes from a kernel density estimate (KDE): put a small bell curve on every data point and add them up. The width of those curves, the bandwidth, controls smoothness, just like the number of histogram bins.

Python
fig = px.violin(df, x="day", y="tip", box=True, points="all")
fig.show()

With box=True a miniature box plot sits inside each violin, so you get both the summary and the shape. Plotly picks a bandwidth automatically; the trace attribute bandwidth overrides it. Violins shine when the distribution is bimodal (two humps), which a box plot cannot show at all. They mislead on very small samples, because a smooth curve suggests more certainty than six points deserve. The KDE also extends beyond the data range unless you set span, so a violin of positive-only values can seem to include negatives.

Density heatmaps and marginal plots

When both axes are numeric and there are too many points for a scatter plot, count the points in a grid of cells and color each cell by its count:

Python
fig = px.density_heatmap(df, x="total_bill", y="tip", nbinsx=15, nbinsy=10)
fig.show()

A scatter plot can also carry the distributions of its two variables along the edges. The marginal_x and marginal_y arguments accept "histogram", "rug", "box" and "violin":

Python
fig = px.scatter(
    df, x="total_bill", y="tip",
    marginal_x="histogram", marginal_y="box",
)
fig.show()

Marginal plots are a good default for exploration: one figure shows the relationship in the middle and each variable on its own at the edges. Under the hood, Plotly builds a subplot grid and links the axes, which is why zooming the main plot also zooms the margins.

flowchart LR
    A["Raw rows<br/>one value per row"] --> B["Summary step<br/>bin, quartile or KDE"]
    B --> C["Few numbers<br/>counts, Q1/median/Q3, density"]
    C --> D["Marks<br/>bars, boxes, outlines"]

A statistical chart is a normal chart drawn after a summary step.

Trendlines and error bars

px.scatter can fit a model for you through the trendline argument. "ols" draws an ordinary least squares line and "lowess" draws a locally weighted smooth curve; both need the statsmodels package installed. There are also "rolling", "expanding" and "ewm" options for time series, which use trendline_options such as dict(window=5).

Python
fig = px.scatter(df, x="total_bill", y="tip", trendline="ols")
results = px.get_trendline_results(fig)
print(results.iloc[0]["px_fit_results"].summary())
fig.show()

The function px.get_trendline_results returns the fitted statsmodels objects, so you can read the slope, the R-squared and the p-values instead of eyeballing the line. A trendline is a claim: "a straight line describes this relationship". Check that the points actually look straight.

Error bars show uncertainty. Most Plotly Express functions take error_y (and error_x) as the name of a column holding the size of the bar, or error_y_minus for asymmetric ones. A common choice is the standard error of the mean, the standard deviation divided by the square root of the number of observations. The last example fits a line with plain NumPy and computes the standard errors that you would pass as error_y.

Python OLS trendline, R-squared and error bars (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The standard error column is what you would feed to error_y after building a small summary table with the group means. Remember that error bars need a stated meaning (standard error, standard deviation, 95% confidence interval) and the caption should say which one you used.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does px.histogram compute before it draws the bars?

    A histogram groups values into bins and draws one bar per bin. The height is a count by default, or another summary if you set histfunc or histnorm.
  2. 2. In a box plot, which points are drawn as individual outlier dots?

    The whiskers end at the most extreme values inside the 1.5 x IQR fences. Anything beyond the fences is shown as a separate point.
  3. 3. When is a violin plot more informative than a box plot?

    A box plot cannot show two peaks, but the density outline of a violin can. With tiny samples the smooth outline can mislead.
  4. 4. What do you need to install to use trendline='ols' in px.scatter?

    The ols and lowess trendlines are fitted with statsmodels, so Plotly Express needs it installed. px.get_trendline_results then gives you the fitted models.
  5. 5. What should accompany error bars on a chart?

    Standard deviation, standard error and confidence intervals have very different sizes. The caption must say which one the bars show.

Summary

  • Statistical charts summarize rows (bins, quartiles, densities, fits) before drawing marks.
  • px.histogram bins one column; nbins, histnorm and histfunc control counts and heights. Try several bin counts.
  • px.box draws Q1, median, Q3, whiskers at 1.5 x IQR and outlier dots; the quartile method can change small-sample boxes.
  • px.violin adds a kernel density outline; box=True and points="all" show the summary and the raw data.
  • px.density_heatmap and marginal_x/marginal_y handle many points and show each variable's distribution.
  • trendline="ols" needs statsmodels; error bars need a stated meaning.
  • The code for Plotly itself is read-only here; the runnable examples are NumPy stand-ins.

Next: Plotly.js in the Browser, where the same figures run as plain JavaScript.