IFI 8410 — Session 9: Visualization and Descriptive Statistics

Numbers and Pictures

Describing data honestly

The problem

Nobody can read ten thousand rows

A few numbers

An average, a spread, a correlation. Exact, and fits in a sentence. Hides the shape: two very different columns can have the same mean.

A picture

A histogram, bars, a scatter plot, a line. Shows the shape. Cannot be quoted, and can mislead through the choice of an axis.

Three failures this session is organised around:

  1. reporting a mean for data where the mean describes almost no one;
  2. deleting unusual values because they are unusual;
  3. a chart that is technically correct and gives a false impression.

The tools

Three packages

pandas

tables

mean, median, std, quantile, describe, corr, and per-group summaries.

NumPy

arrays

The same reductions on arrays; np.quantile; np.geomspace for logarithmic bins.

matplotlib

drawing

Figures and axes; histograms, bars, scatter plots, lines; labels, scales, layout; saving to PNG, PDF, SVG.

seaborn and the .plot methods of pandas are conveniences built on matplotlib. What you learn about figures and axes applies to them too.

Concept 1

Centre: mean and median

salaries.mean()      # 47.8   nine employees, 38 to 60 thousand
salaries.median()    # 47.0

# add the owner, at 400
salaries.mean()      # 83.0   nine of ten now earn less than "the average"
salaries.median()    # 48.5
QuestionUseBecause
what does a typical one look like?medianhalf are below, half above, whatever the extremes do
what is the total, spread evenly?meanmean × count is the total

Incomes, prices, review counts and waiting times are skewed to the right. A large gap between mean and median is itself a finding.

Concept 2

Spread, and a trap

Variance and standard deviation

waits.var()    # variance
waits.std()    # standard deviation
divides by
x.var() in pandascount − 1
np.var(x) in NumPycount
np.var(x, ddof=1)count − 1

Quartiles and the IQR

q1 = values.quantile(0.25)
q3 = values.quantile(0.75)
iqr = q3 - q1
values.describe()
CentreSpread
built on sumsmeanvariance, std
built on ordermedianquartiles, IQR

Same data, same function name, two answers, no warning. One extreme value moves everything built on sums and hardly touches what is built on order.

Concept 3

Outliers are questions

outside = (values < q1 - 1.5 * iqr) | (values > q3 + 1.5 * iqr)

A column of True and False. Nothing is removed. A flagged value can be three different things:

It isExampleDo
a mistakea salary typed with an extra zerocorrect it or make it missing, and say so
a different kind of thingthe owner among the employeesdecide whether it belongs to the question
the most important rowthe customer who brings half the revenuekeep it and report it

Concept 4

Two columns: correlation

table["temperature"].corr(table["cups"])    # r, from -1 to 1
  • r measures straight-line association only: a clear curve can have r near 0.
  • It says nothing about cause.

Anscombe's quartet

Four small datasets with the same means, the same standard deviations, and the same correlation, 0.82.

Drawn, they are…

a loose cloud, a curve, a line with one point off it, and a vertical stack with one point that creates the whole correlation.

Sums cannot tell shapes apart. Always draw the data.

Concept 4, continued

Anscombe’s quartet, drawn

Anscombe's quartet: four scatter plots with the same fitted line y = 3 + 0.5x but very different shapes

Same mean of x (9) and y (7.50), same variances, same r = 0.82, same line y = 3.00 + 0.500x.
Figure: Anscombe's quartet, Wikipedia (F. J. Anscombe, 1973).

Concept 5

A figure is an object

fig, ax = plt.subplots(figsize=(7, 4))          # a Figure, with one Axes
ax.hist(waits, bins=20)
ax.axvline(waits.mean(), linestyle="--", label="mean")
ax.axvline(waits.median(), linestyle=":", label="median")
ax.set_xlabel("waiting time (minutes)")
ax.set_ylabel("customers")
ax.set_title("A typical wait is four minutes; a few wait three times as long")
ax.legend()
fig.savefig("waits.png", dpi=150, bbox_inches="tight")
  • A Figure is the whole picture; an Axes is one plot inside it.
  • Everything is done by calling methods of the Axes: the object interface.

Concept 5, continued

Functions that draw on an Axes

def draw_waits(ax, waits):
    ax.hist(waits, bins=20)
    ax.set_xlabel("waiting time (minutes)")
    return ax

fig, (left, right) = plt.subplots(1, 2, sharex=True, sharey=True)
draw_waits(left, january)
draw_waits(right, july)

fig.savefig("waits.png")
plt.close(fig)
  • sharex and sharey give the panels the same range, which makes them comparable by eye.
  • In a program there is no screen: save the figure, then close it. Nothing calls show().

Concept 6

The chart follows the question

QuestionKindChartMethodSummary number
how are the values spread out?distributionhistogram, box plotax.hist, ax.boxplotmedian, quartiles
which group has more?comparisonbarsax.bar, ax.barhone number per group
do two things go together?relationshipscatter plotax.scattercorrelation
how did it change over time?trendlineax.plotchange from start to end

Most bad charts are a good answer to a question nobody asked.

Concept 7

Honest pictures

A figure without axis labels and units is not yet a result.

  • Bars start at zero. Cut the axis at 5,100 and a 7 % difference looks like a factor of four.
  • A line may start anywhere: it shows change by its slope. State the size of the change in words.
  • Skewed data needs a logarithmic axis, with bins from np.geomspace, and a label that says so.
  • Labels name the quantity and the unit: "area of the infestation (acres)", not "area".
  • A title says what to see: "Weekends sell a third more", not "Cups by weekday".

Worked example — notebook 2

1.3 million consumer complaints

Mean 243, median 6

Complaints per company, 5,275 companies. The typical company received six complaints in seven years.

Ten companies

received half of all complaints.

Equal bins: one bar

The histogram shows nothing until the axis is logarithmic. Then the shape appears.

778 "outliers"

hold 96 % of the complaints. They are not errors. They are the subject.

Worked example — notebook 2

Four traps, none of which raises an error

1. The axis that hides the data

Equal-width bins on heavily skewed counts put nearly everything in the first bar.

2. The categories changed

"Credit reporting" was renamed partway through. Its complaints are split across two bars, and mortgages look like the top product.

3. The incomplete last period

The trend line collapses in the final month. The file ends on the tenth.

4. Deleting what you have not understood

7,052 complaints were forwarded "one day early". Not 7,052 typing mistakes: one cause, such as two systems in different time zones. Decide, and write the count next to the result.

Also in the data: a spike that follows a data breach at a credit bureau, an outlier that is the most informative point on the chart; and a correlation near zero with a clear pattern all the same, since the companies that answer late are small ones.

To take away

Key points

  • Mean and median answer different questions. Compute both; if they differ, say why.
  • Know which variance you have: count − 1 in pandas, count in NumPy.
  • An outlier is flagged, looked at, and then decided on. Never deleted on sight.
  • The same summary numbers can come from very different data. Draw it.
  • Name the kind of question, then choose the chart.
  • Bars from zero; logarithmic axes announced; labels with units; a title that says what to see.

Now: hands-on

Over to the notebooks

Folder 09-Visualization-Descriptive-Statistics — work them in this order:

1Numbers and Pictures

Concepts

Centre, spread, outliers, your first figure, and the coffee cart's summer in four charts. Four exercises.

2Consumer Complaints

Worked example

1.3 million records, seven steps, four traps. Run it on ARC.

3Reference

Look things up

Statistics and plotting calls to keep open while you work.

As you work, ask of every figure: would a reader get the right numbers from it?
Homework: Homework 8: Same Numbers, Different Pictures

◀ Slides