---
webr:
packages: [dplyr, tidyr, ggplot2, patchwork, scales]
resources: [R/setup.R, py/setup.py, data/penguins.csv, data/nhanes_adults.csv, fonts/NotoSansJP-Regular.ttf, fonts/NotoSansJP-Bold.ttf]
cell-options:
autorun: true
pyodide:
packages: [pandas, matplotlib, seaborn]
cell-options:
autorun: true
---
{{< include ./_extensions/r-wasm/live/_knitr.qmd >}}
# Categories: order, names, facets {#sec-categories}
```{webr}
#| include: false
source("R/setup.R")
```
```{pyodide}
#| include: false
exec(open("py/setup.py").read())
```
When you split colours or figures by category (species, island, sex), what you care about is **the order** and **the displayed names**.
## Giving categories display names and an order
R's **factor** and pandas' **categorical type** (Categorical) are both types that hold "the possible values and their order".
**If you decide them once on the data side**, the legend, axes and facets all get the same order and names.
::: {.panel-tabset group="lang"}
## R (ggplot2)
```{webr}
peng <- penguins |>
filter(!is.na(sex)) |>
mutate(Species = factor(species, levels = c("Adelie", "Chinstrap", "Gentoo"),
labels = c("Adelie", "Chinstrap", "Gentoo")),
Sex = factor(sex, levels = c("female", "male"), labels = c("Female", "Male")))
levels(peng$Species)
table(peng$Species, peng$Sex)
```
## Python (seaborn / matplotlib)
```{pyodide}
sp_en = {"Adelie": "Adelie", "Chinstrap": "Chinstrap", "Gentoo": "Gentoo"}
peng = penguins.dropna(subset=["sex"]).copy()
peng["Species"] = pd.Categorical(peng["species"].map(sp_en), categories=["Adelie", "Chinstrap", "Gentoo"])
peng["Sex"] = pd.Categorical(peng["sex"].map({"female": "Female", "male": "Male"}), categories=["Female", "Male"])
print(peng["Species"].cat.categories.tolist())
print(pd.crosstab(peng["Species"], peng["Sex"]))
```
:::
::: {.callout-note}
## Missing sex
The 11 penguins of unknown sex are excluded. You could also keep them by creating an "Unknown" level. Write what was excluded in the figure's caption.
:::
## Bar charts: counting vs plotting values as they are
ggplot2 distinguishes `geom_bar()`, which **counts the data to make bars**, from `geom_col()`, which **uses the values as they are for the bar heights**.
::: {.panel-tabset group="lang"}
## R (ggplot2)
```{webr}
# geom_bar(): counts rows (statistical transformation stat = "count")
ggplot(peng, aes(Species, fill = Sex)) +
geom_bar(position = "dodge") +
labs(x = NULL, y = "Count")
```
```{webr}
# Position adjustments: stacked (stack) and proportions (fill)
library(patchwork)
p1 <- ggplot(peng, aes(island, fill = Species)) + geom_bar(position = "stack") + labs(x = "Island", y = "Count", title = "stack")
p2 <- ggplot(peng, aes(island, fill = Species)) + geom_bar(position = "fill") +
scale_y_continuous(labels = scales::percent) + labs(x = "Island", y = "Proportion", title = "fill")
p1 + p2 + plot_layout(guides = "collect")
```
## Python (seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots()
sns.countplot(data=peng, x="Species", hue="Sex", ax=ax)
ax.set(xlabel="", ylabel="Count")
plt.show()
```
```{pyodide}
# For stacked bars and proportions, the easy way is to aggregate first and draw with pandas' plot
tab = pd.crosstab(peng["island"], peng["Species"])
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
tab.plot(kind="bar", stacked=True, ax=axes[0], rot=0, title="Stacked")
tab.div(tab.sum(axis=1), axis=0).plot(kind="bar", stacked=True, ax=axes[1], rot=0, legend=False, title="Proportion")
axes[0].set(xlabel="Island", ylabel="Count"); axes[1].set(xlabel="Island", ylabel="Proportion")
axes[1].yaxis.set_major_formatter(matplotlib.ticker.PercentFormatter(1.0))
plt.tight_layout()
plt.show()
```
:::
You can see that Biscoe Island has Gentoo and Adelie, Dream Island has Chinstrap and Adelie, and Torgersen Island has only Adelie. This **imbalance between islands and species** leads into Simpson's paradox in Chapter 6.
## Ordering by value
When categories have no natural order, ordering them **by the size of a value** makes them easier to read. We order the NHANES race/ethnicity categories by median BMI.
::: {.panel-tabset group="lang"}
## R (ggplot2)
```{webr}
nh <- nhanes |> filter(!is.na(BMI))
ggplot(nh, aes(x = reorder(Race1, BMI, FUN = median), y = BMI)) + # order by median
geom_boxplot(outlier.size = 0.5) +
coord_flip() +
labs(x = NULL, y = "BMI")
```
## Python (seaborn / matplotlib)
```{pyodide}
nh = nhanes.dropna(subset=["BMI"])
order = nh.groupby("Race1")["BMI"].median().sort_values().index.tolist()
fig, ax = plt.subplots()
sns.boxplot(data=nh, y="Race1", x="BMI", order=order[::-1], fliersize=1, ax=ax) # largest at the top
ax.set(ylabel="", xlabel="BMI")
plt.show()
```
:::
## Facets: arranging small plots
Arranging plots of the same form side by side, one per category, is called **faceting** (small multiples). It can be easier to compare than distinguishing by colour.
::: {.panel-tabset group="lang"}
## R (ggplot2)
```{webr}
# facet_wrap: arrange by one variable (wrapping)
ggplot(peng, aes(flipper_length_mm, body_mass_g, colour = Sex)) +
geom_point(alpha = 0.7) +
facet_wrap(~ Species) +
labs(x = "Flipper length (mm)", y = "Body mass (g)")
```
```{webr}
# facet_grid: two variables for rows and columns
ggplot(peng, aes(body_mass_g)) +
geom_histogram(binwidth = 200, fill = "grey60", colour = "white") +
facet_grid(Sex ~ Species) +
labs(x = "Body mass (g)", y = "Count")
```
## Python (seaborn / matplotlib)
```{pyodide}
g = sns.relplot(data=peng, x="flipper_length_mm", y="body_mass_g", hue="Sex",
col="Species", height=3.3, aspect=0.95, alpha=0.7)
g.set_axis_labels("Flipper length (mm)", "Body mass (g)")
g.set_titles(col_template="{col_name}") # panel titles (default is "Species = Adelie")
plt.show()
```
```{pyodide}
g = sns.displot(data=peng, x="body_mass_g", row="Sex", col="Species", binwidth=200,
height=2.4, aspect=1.3, color="grey")
g.set_axis_labels("Body mass (g)", "Count")
g.set_titles(row_template="{row_name}", col_template="{col_name}")
plt.show()
```
:::
### Aligned axes or per-panel axes
By default, facets **use the same axis ranges for all panels**, so that values can be compared across panels.
When you want different ranges per panel (when the magnitudes differ a lot), use `scales = "free_y"` in ggplot2 and `facet_kws={"sharey": False}` in seaborn.
::: {.panel-tabset group="lang"}
## R (ggplot2)
```{webr}
nh_long <- nhanes |>
select(Gender, BMI, BPSysAve, TotChol) |>
tidyr::pivot_longer(-Gender, names_to = "Variable", values_to = "Value")
ggplot(nh_long, aes(Value, fill = Gender)) +
geom_density(alpha = 0.4, na.rm = TRUE) +
facet_wrap(~ Variable, scales = "free") + # units differ by variable, so free the axes
labs(x = NULL, y = "Density", fill = "Sex")
```
## Python (seaborn / matplotlib)
```{pyodide}
nh_long = nhanes.melt(id_vars="Gender", value_vars=["BMI", "BPSysAve", "TotChol"], var_name="Variable", value_name="Value")
g = sns.displot(data=nh_long, x="Value", hue="Gender", col="Variable", kind="kde", fill=True,
common_norm=False, height=3, aspect=1.1, facet_kws={"sharex": False, "sharey": False})
g.set_titles(col_template="{col_name}")
plt.show()
```
:::
::: {.callout-warning}
## With free axes, you can't compare across panels
If axis ranges differ between panels, comparing visual heights and positions is meaningless. For facets comparing quantities in the same unit, keep the axes aligned.
:::
::: {.callout-important}
## Chapter summary
- Decide category **names and order once, on the data side** (R's factor, pandas' Categorical)
- `geom_bar()` counts, `geom_col()` uses values as they are. Stacking and proportions via `position =`
- Order categories without a natural order **by the size of a value**
- Facets: `facet_wrap` / `facet_grid`; in seaborn, `col=` and `row=` of figure-level functions. Be aware of **whether to align the axes**
:::