A Data Science Vocabulary for Task Abstraction
DS 2023 | Communicating with Data
Overview¶
This notebook attempts to develop a vocabulary of primitive action terms specifically designed for data science.
To motivate this, consider that throughout this course, we have seen that every visualization is produced by two kinds of work:
First, you shape and summarize the source data until it has the form the chart needs.
Second, you map the data onto on the visual elements of a canvas — marks, scales, facets, labels, etc. — according to a visual metaphor to represent aspects of the data.
These two kinds of work have their own vocabularies:
The data mutation words describe what you do to a table.
The visual composition words describe what you do to a figure.
These two vocabularies help you plan your code before you write it.
They map onto the specific action level of the Visualization Task Hierarchy.
Each verb can be used to compose
action + targetstatements.
The Visualization Task Hierarchy¶
Let’s review the place of these vocabularies in the task abstraction process.
Here is a summary of the process, applied to design:
1 Start at the Task level.
State the central analytical question the dashboard is meant to answer.
This scopes everything below it.
This question should be answerable within the scope of your data.
2 Decompose into Sub-tasks.
Break the central question into the 3–5 specific questions a user must answer to reach the goal.
Each sub-task is a logical unit of the dashboard (a panel, a view, a filter section).
3 Operationalize each sub-task.
Rephrase it as a Verb + Object using controlled vocabularies for data and visualization.
4 Map operations to specific actions.
Decide what interactive moves (query, filter, zoom, plot) the user needs to perform that operation.
These become your widget choices: sliders, dropdowns, linked charts.
5 Ask: what trails does this dashboard support?
A trail is a sequence of actions leading to a discovery.
If you can’t trace a plausible path from the Task question to an insight using your dashboard’s controls, something is missing.
Analytic Task Taxonomy¶
Here is a a vocabulary of ten low-level (primitive) analysis tasks that largely capture people’s activities while employing information visualization tools for understanding data.
From Amar, Eagan & Stasko (2005) “Low-Level Components of Analytic Activity in Information Visualization,” IEEE InfoVis 2005.
| # | Task | Description | Pro Forma Abstract | Examples |
|---|---|---|---|---|
| 1 | Retrieve Value | Given a set of specific observations, find the values of variables for those observations. | What are the values of variables {X, Y, Z, ...} for observations {A, B, C, ...}? | What is the mileage per gallon of the Audi TT? How long is the movie Gone with the Wind? |
| 2 | Filter | Given some concrete conditions on variable values, find observations satisfying those conditions. | Which observations satisfy conditions {A, B, C, ...}? | What Kellogg’s cereals have high fiber? What comedies have won awards? Which funds underperformed the SP-500? |
| 3 | Compute Derived Value | Given a set of observations, compute an aggregate numeric representation of those observations. | What is the value of aggregation function F over a given set S of observations? | What is the average calorie content of Post cereals? What is the gross income of all stores combined? How many manufacturers of cars are there? |
| 4 | Find Extremum | Find observations possessing an extreme value of a variable over its range within the data set. | What are the top/bottom N observations with respect to variable A? | What is the car with the highest MPG? What director/film has won the most awards? What Robin Williams film has the most recent release date? |
| 5 | Sort | Given a set of observations, rank them according to some ordinal metric. | What is the sorted order of a set S of observations according to their value of variable A? | Order the cars by weight. Rank the cereals by calories. |
| 6 | Determine Range | Given a set of observations and a variable of interest, find the span of values within the set. | What is the range of values of variable A in a set S of observations? | What is the range of film lengths? What is the range of car horsepowers? What actresses are in the data set? |
| 7 | Characterize Distribution | Given a set of observations and a quantitative variable of interest, characterize the distribution of that variable’s values over the set. | What is the distribution of values of variable A in a set S of observations? | What is the distribution of carbohydrates in cereals? What is the age distribution of shoppers? |
| 8 | Find Anomalies | Identify any anomalies within a given set of observations with respect to a given relationship or expectation, e.g. statistical outliers. | Which observations in a set S have unexpected/exceptional values? | Are there exceptions to the relationship between horsepower and acceleration? Are there any outliers in protein? |
| 9 | Cluster | Given a set of observations, find clusters of similar variable values. | Which observations in a set S are similar in value for variables {X, Y, Z, ...}? | Are there groups of cereals with similar fat/calories/sugar? Is there a cluster of typical film lengths? |
| 10 | Correlate | Given a set of observations and two variables, determine useful relationships between the values of those variables. | What is the correlation between variables X and Y over a given set S of observations? | Is there a correlation between carbohydrates and fat? Is there a correlation between country of origin and MPG? Do different genders have a preferred payment method? Is there a trend of increasing film length over the years? |
Our own vocabulary¶
We will create our own vocabulary by abstracting form the tools we have used in this course.
The two verb domains
| Domain | Question it answers | Typical tool |
|---|---|---|
| Data Mutation | What does the table need to look like? | pandas |
| Visual Composition | What does the figure need to show? | Seaborn / Matplotlib |
A useful rule of thumb:
If you are touching a DataFrame, you are in the data mutation domain.
If you are touching an
Axesor calling a Seaborn function, you are in the visual composition domain.
Many visualization bugs come from mixing the two — trying to fix a chart problem with a data fix, or the reverse. Naming the domain first points you at the right tool.
Data Mutation Verbs¶
These verbs operate on a DataFrame. They produce another DataFrame (or a scalar summary). They do not care about colors, axes, or marks.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as snsThe examples in this section use the penguins dataset from Seaborn.
It records body measurements for 344 penguins across three species
(Adelie, Chinstrap, Gentoo) on three Antarctic islands.
Columns include species, island, bill_length_mm, bill_depth_mm,
flipper_length_mm, body_mass_g, and sex.
penguins = sns.load_dataset('penguins')
penguins.head()Declare¶
Establish an attribute and its measurement scale.
Every column has a dtype that encodes its scale of measurement:
float64 for quantitative, category for nominal or ordinal, datetime64 for temporal.
Pandas infers dtypes on load, but sometimes you need to declare them explicitly.
The astype() method is the most direct way to do this.
# Declare 'species' as a categorical (nominal) variable
penguins_typed = penguins.copy()
penguins_typed['species'] = penguins_typed['species'].astype('category')
print(penguins_typed['species'].dtype)category
Mutate¶
Compute a new column from existing ones.
Use df.assign() to add derived columns without modifying the original DataFrame.
The new column is a function of existing columns.
# Derive bill_ratio: the ratio of bill length to bill depth
penguins = penguins.assign(bill_ratio=penguins['bill_length_mm'] / penguins['bill_depth_mm'])
penguins[['species', 'bill_length_mm', 'bill_depth_mm', 'bill_ratio']].head()Filter¶
Restrict rows to those satisfying a predicate.
Boolean indexing selects rows where the condition is True.
The result is a smaller DataFrame with the same columns.
# Keep only Gentoo penguins
gentoo = penguins[penguins['species'] == 'Gentoo']
print(f'{len(gentoo)} rows after filtering to Gentoo')
gentoo.head()124 rows after filtering to Gentoo
Sort¶
Reorder rows by one or more attribute values.
Use sort_values().
Pass ascending=False to sort from largest to smallest.
# Sort penguins by body_mass_g, heaviest first
penguins_sorted = penguins.sort_values('body_mass_g', ascending=False)
penguins_sorted[['species', 'island', 'body_mass_g']].head()Select¶
Select a subset of columns.
Projection reduces the table to only the attributes you need.
Pass a list of column names to df[[...]].
# Project down to three columns
penguins[['species', 'flipper_length_mm', 'body_mass_g']].head()Aggregate¶
Collapse rows into summary statistics.
groupby().agg() groups rows by one or more columns and applies an aggregation
function — mean, median, count, sum, or a custom function — to each group.
# Mean body mass and flipper length by species
penguins.groupby('species')[['body_mass_g', 'flipper_length_mm']].agg('mean').round(1)Pivot¶
Change the layout of the table.
pivot_table() rotates one column’s values into new column headers.
This produces “wide” data, where each category gets its own column.
Wide data is convenient for certain chart types and for side-by-side comparisons.
# Pivot: rows = island, columns = species, values = mean body_mass_g
penguins.pivot_table(
index='island',
columns='species',
values='body_mass_g',
aggfunc='mean'
).round(0)Combine¶
Combine two datasets on a shared key.
pd.merge(), pd.join(), and pd.concat(axis=1) combine DataFrames by matching rows on one or more key columns.
# Build a small lookup table mapping species to a common name
species_info = pd.DataFrame({
'species': ['Adelie', 'Chinstrap', 'Gentoo'],
'common_name': ['Adelie penguin', 'Chinstrap penguin', 'Gentoo penguin'],
'clade': ['Pygoscelis', 'Pygoscelis', 'Pygoscelis']
})
# Merge the lookup into the penguins DataFrame
penguins_merged = pd.merge(penguins, species_info, on='species')
penguins_merged[['species', 'common_name', 'body_mass_g']].head()Visual Composition Verbs¶
These verbs operate on a figure or axes object. They assume the data is already in the correct shape. They do not touch the DataFrame.
Map¶
Map a data attribute to a visual channel.
A visual channel is any perceptual dimension that can carry information:
position (, ), color, size, shape, opacity.
In Seaborn, bindings are declared as keyword arguments: x=, y=, hue=, size=, style=.
The cell below binds bill_length_mm to the -axis, body_mass_g to the -axis,
and species to color (hue).
fig, ax = plt.subplots(figsize=(7, 5))
sns.scatterplot(
data=penguins.dropna(),
x='bill_length_mm',
y='body_mass_g',
hue='species',
ax=ax
)
ax.set_title('Bind: bill_length_mm → x, body_mass_g → y, species → color')
sns.despine()
plt.show()
Scale¶
Define the transformation between the data domain and the visual range.
By default, Matplotlib uses a linear scale. A log scale compresses large ranges; a categorical scale spaces discrete values evenly. Color scales (palettes) map a data range onto a sequence of hues or shades.
fig, axes = plt.subplots(1, 2, figsize=(10, 3))
# Linear scale (default)
tips = sns.load_dataset('tips')
axes[0].hist(tips['total_bill'], bins=20, color='steelblue', edgecolor='white')
axes[0].set_title('Linear scale (default)')
axes[0].set_xlabel('total_bill')
# Log scale on x-axis
axes[1].hist(tips['total_bill'], bins=20, color='steelblue', edgecolor='white')
axes[1].set_xscale('log')
axes[1].set_title('Log scale on x-axis')
axes[1].set_xlabel('total_bill (log)')
sns.despine()
plt.tight_layout()
plt.show()
Draw¶
Instantiate a geometric mark.
A mark is the basic visual unit: a point, a bar, a line, an area.
Choosing a mark is choosing how each row of data appears on the canvas.
Seaborn’s named plot functions (scatterplot, barplot, lineplot) each render a different mark type.
fig, axes = plt.subplots(1, 3, figsize=(12, 3))
penguins_clean = penguins.dropna()
species_mass = penguins_clean.groupby('species')['body_mass_g'].mean().reset_index()
# Point mark
sns.scatterplot(data=penguins_clean, x='bill_length_mm', y='body_mass_g',
hue='species', ax=axes[0], legend=False)
axes[0].set_title('Point mark')
# Bar mark
sns.barplot(data=species_mass, x='species', y='body_mass_g',
hue='species', ax=axes[1], legend=False)
axes[1].set_title('Bar mark')
# Line mark
healthexp = sns.load_dataset('healthexp')
for country in ['USA', 'Germany', 'France']:
subset = healthexp[healthexp['Country'] == country]
axes[2].plot(subset['Year'], subset['Life_Expectancy'], label=country)
axes[2].set_title('Line mark')
axes[2].legend(fontsize=8)
sns.despine()
plt.tight_layout()
plt.show()
Transform (Statistical)¶
Compute a visualization-specific summary on the fly.
Some chart functions bin continuous values, smooth a curve, or compute a confidence interval as part of the rendering step — not as a separate data step. This is a statistical transform built into the visual layer.
sns.histplot()bins raw values into counts.sns.regplot()fits and draws a regression line with a confidence band.
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
# Statistical transform: binning (histplot)
sns.histplot(data=penguins_clean, x='flipper_length_mm', hue='species',
bins=20, ax=axes[0])
axes[0].set_title('Transform: bin into counts')
# Statistical transform: regression + CI (regplot)
sns.regplot(data=penguins_clean, x='bill_length_mm', y='body_mass_g',
scatter_kws={'alpha': 0.3}, ax=axes[1])
axes[1].set_title('Transform: regression + confidence band')
sns.despine()
plt.tight_layout()
plt.show()
Subplot¶
Split the canvas into sub-plots by a categorical attribute.
Faceting creates one panel per category value.
It lets you compare the same chart across groups without overlapping marks.
In Seaborn, the col= or row= arguments to sns.relplot() and sns.displot() handle faceting.
g = sns.displot(
data=penguins_clean,
x='flipper_length_mm',
col='species',
bins=15,
height=3,
aspect=0.9
)
g.set_titles(col_template='{col_name}')
g.set_xlabels('Flipper length (mm)')
plt.show()
Layer¶
Superimpose multiple geometric marks on the same axes.
Layering adds information density without adding panels.
In Matplotlib, you layer by making multiple plot calls on the same ax object.
fig, ax = plt.subplots(figsize=(7, 4))
# Layer 1: scatter points
sns.scatterplot(data=penguins_clean, x='bill_length_mm', y='body_mass_g',
hue='species', alpha=0.5, ax=ax)
# Layer 2: regression line for all species combined
sns.regplot(data=penguins_clean, x='bill_length_mm', y='body_mass_g',
scatter=False, color='black', line_kws={'linewidth': 1.5}, ax=ax)
ax.set_title('Layer: scatter + regression line')
sns.despine()
plt.show()
Annotate¶
Add non-data marks: titles, labels, reference lines, text.
Annotation does not encode new data — it explains or contextualizes what is already shown.
Use ax.set_title(), ax.set_xlabel(), ax.axhline(), ax.axvline(), and ax.text().
fig, ax = plt.subplots(figsize=(7, 5))
sns.scatterplot(data=penguins_clean, x='flipper_length_mm', y='body_mass_g',
hue='species', alpha=0.6, ax=ax)
# Annotate: reference line at the overall median body mass
median_mass = penguins_clean['body_mass_g'].median()
ax.axhline(median_mass, color='black', linewidth=1, linestyle='--')
ax.text(170, median_mass + 60, f'Median: {median_mass:.0f} g', fontsize=9)
ax.set_title('Flipper length vs. body mass')
ax.set_xlabel('Flipper length (mm)')
ax.set_ylabel('Body mass (g)')
sns.despine()
plt.show()
Worked Example: Verb Chain from Question to Plot¶
Let’s walk through a complete verb chain — from a plain analytical question to a finished visualization — naming each verb as we apply it.
The Question¶
Do heavier penguins have proportionally longer bills, and does this differ by species?
The Verb Chain¶
Data mutation steps:
Filter — drop rows with missing values so every downstream step has clean input.
Mutate — compute
bill_ratio(bill length ÷ bill depth) as the “proportionality” measure.Aggregate — compute the mean
bill_ratioand meanbody_mass_gper species, to add a per-species summary layer.
Visual composition steps:
Map — map
body_mass_g→ ,bill_ratio→ ,species→ color.Draw — draw a scatter mark for the individual penguins.
Layer — superimpose per-species mean points as larger markers.
Annotate — add a title and axis labels.
Let’s execute each step.
# Step 1 — Filter: drop rows with any missing value
df = sns.load_dataset('penguins').dropna()
print(f'{len(df)} rows after filtering')
# Step 2 — Mutate: compute bill_ratio
df = df.assign(bill_ratio=df['bill_length_mm'] / df['bill_depth_mm'])
# Step 3 — Aggregate: per-species means
species_means = (
df.groupby('species')[['body_mass_g', 'bill_ratio']]
.mean()
.reset_index()
)
species_means333 rows after filtering
fig, ax = plt.subplots(figsize=(8, 5))
# Step 4 + 5 — Bind + Render: scatter of individual penguins
sns.scatterplot(
data=df,
x='body_mass_g',
y='bill_ratio',
hue='species',
alpha=0.45,
s=40,
ax=ax
)
# Step 6 — Layer: per-species mean points
sns.scatterplot(
data=species_means,
x='body_mass_g',
y='bill_ratio',
hue='species',
s=200,
marker='D',
edgecolor='black',
linewidth=1,
legend=False,
ax=ax
)
# Step 7 — Annotate
ax.set_title('Bill ratio vs. body mass by species (diamonds = species means)')
ax.set_xlabel('Body mass (g)')
ax.set_ylabel('Bill ratio (length / depth)')
sns.despine()
plt.show()
Summary¶
Visualization action verbs and their pandas / Seaborn counterparts
| Domain | Verb | What it does | Pandas / Seaborn |
|---|---|---|---|
| Data Mutation | Declare | Set a column’s dtype and measurement scale | astype() |
| Data Mutation | Mutate | Compute a new column from existing ones | assign() |
| Data Mutation | Filter | Keep rows that satisfy a predicate | df[condition], .query() |
| Data Mutation | Sort | Reorder rows by attribute value | sort_values() |
| Data Mutation | Select | Select a subset of columns | df[['a', 'b']] |
| Data Mutation | Aggregate | Collapse rows into summaries | groupby().agg() |
| Data Mutation | Pivot | Change the table layout | pivot_table(), melt() |
| Data Mutation | Combine | Merge datasets on a shared key | pd.merge() |
| Visual Composition | Map | Assign a data attribute to a visual channel | x=, y=, hue=, size= |
| Visual Composition | Scale | Set the data-to-visual-range transformation | set_xscale(), color palettes |
| Visual Composition | Draw | Instantiate a geometric mark | sns.scatterplot(), barplot(), lineplot() |
| Visual Composition | Transform (Statistical) | Compute summaries inside the visual layer | sns.histplot(), sns.regplot() |
| Visual Composition | Facet | Split into sub-plots by category | col=, row=, FacetGrid |
| Visual Composition | Layer | Superimpose marks on the same axes | Multiple calls on the same ax |
| Visual Composition | Annotate | Add titles, labels, reference marks | set_title(), axhline(), text() |