Distributions and part-of-whole charts

Plotly · Essentials · 10 min

Choosing the right chart type for the question is half of good visualization, and Express offers dozens with a consistent API.

Plotly Express uses the same arguments across many chart types, so learning one teaches them all.

For distributions:

  • px.histogram(df, x="total_bill", nbins=30) bins and counts. It can also aggregate: px.histogram(df, x="day", y="tip", histfunc="sum") sums tips per day, which is often the quickest way to make a bar chart of totals. histnorm="percent" normalizes.
  • px.box, px.violin and px.strip compare distributions across categories; points="all" overlays raw observations on a box or violin.
  • px.ecdf shows cumulative proportions without binning choices.
  • marginal="box" (or "violin", "rug", "histogram") on scatter or histogram adds a small distribution plot on the edge.

For parts of a whole:

  • px.pie(df, names="category", values="amount"); use hole=0.4 for a donut. Pies only work with a handful of slices.
  • px.sunburst and px.treemap show hierarchies: path=["region", "country"] nests the levels, and clicking a segment zooms in.

Other families include px.density_heatmap and px.density_contour for many points, px.imshow for matrices and images, px.scatter_3d, polar, ternary and geographic charts, and px.timeline for Gantt charts.

Prefer bars to pies when comparing similar values: people judge lengths more accurately than angles.

Example

import plotly.express as px

tips = px.data.tips()
print(tips.shape)                                    # (244, 7)

fig = px.histogram(tips, x="total_bill", nbins=20, marginal="box")
print(len(fig.data), fig.data[1].type)               # 2 box

totals = px.histogram(tips, x="day", y="tip", histfunc="sum")
print(totals.data[0].histfunc)                       # sum

box = px.box(tips, x="day", y="total_bill", points="all")
print(box.data[0].boxpoints)                         # all

tree = px.treemap(tips, path=["day", "time"], values="total_bill")
print(tree.data[0].type)                             # treemap
fig.write_html("bills.html")

Remember

  • histogram, box, violin, strip and ecdf cover distributions
  • histogram with y and histfunc aggregates, like a quick group-by bar chart
  • sunburst and treemap show hierarchies via path=

Watch out for

  • Using a pie with many similar slices, which is much harder to read than a sorted bar chart.

Check yourself

  1. Which call gives a bar per day with the total tip amount?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: plotly.com/python/histograms/