---
webr:
packages: [dplyr, ggplot2, svglite]
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 >}}
# Themes, fonts, sizes and saving {#sec-theme-export}
```{webr}
#| include: false
source("R/setup.R")
peng <- penguins |> filter(!is.na(sex)) |>
mutate(Species = factor(species, c("Adelie", "Chinstrap", "Gentoo"), c("Adelie", "Chinstrap", "Gentoo")))
base_plot <- ggplot(peng, aes(flipper_length_mm, body_mass_g, colour = Species)) +
geom_point(size = 1.5, alpha = 0.8) +
scale_colour_manual(values = c("#E69F00", "#56B4E9", "#009E73")) +
labs(x = "Flipper length (mm)", y = "Body mass (g)", colour = "Species")
```
```{pyodide}
#| include: false
exec(open("py/setup.py").read())
peng = penguins.dropna(subset=["sex"]).copy()
peng["Species"] = pd.Categorical(peng["species"].map({"Adelie": "Adelie", "Chinstrap": "Chinstrap", "Gentoo": "Gentoo"}),
categories=["Adelie", "Chinstrap", "Gentoo"])
pal = ["#E69F00", "#56B4E9", "#009E73"]
```
This chapter covers tidying up the appearance unrelated to the data (background, lines, text) and saving at the size required by a journal's guidelines.
## Choosing a theme and changing its elements
::: {.panel-tabset group="lang"}
## R (ggplot2)
```{webr}
base_plot + theme_grey(base_size = 12) + labs(title = "theme_grey (ggplot2's default)")
base_plot + theme_classic(base_size = 12) + labs(title = "theme_classic (no panel border or grid lines)")
```
In ggplot2, you choose the overall theme with `theme_xxx()` and change individual **elements** with `theme()`.
| Element | Function to change it | Example |
|---|---|---|
| Text | `element_text()` | `axis.title = element_text(size = 11, face = "bold")` |
| Lines | `element_line()` | `panel.grid.major = element_line(colour = "grey90")` |
| Rectangles | `element_rect()` | `panel.background = element_rect(fill = "white")` |
| Remove | `element_blank()` | `panel.grid.minor = element_blank()` |
```{webr}
theme_paper <- function(base_size = 10) {
theme_classic(base_size = base_size) +
theme(axis.text = element_text(colour = "black"),
axis.ticks = element_line(colour = "black"),
legend.position = "inside", legend.position.inside = c(0.02, 0.98), # legend at the top left inside the panel
legend.justification = c(0, 1),
legend.background = element_rect(fill = NA),
plot.title = element_text(face = "bold", size = base_size + 1))
}
base_plot + theme_paper(12) + labs(title = "My own theme")
```
## Python (seaborn / matplotlib)
```{pyodide}
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
for ax, style in zip(axes, ["whitegrid", "ticks"]):
sns.set_style(style, {"font.family": "Noto Sans JP"})
sns.scatterplot(data=peng, x="flipper_length_mm", y="body_mass_g", hue="Species", palette=pal, s=20, ax=ax)
ax.set(xlabel="Flipper length (mm)", ylabel="Body mass (g)", title=f'sns.set_style("{style}")')
sns.despine(ax=axes[1]) # remove the top and right spines
plt.tight_layout()
plt.show()
sns.set_theme(style="whitegrid", font="Noto Sans JP", rc={"axes.unicode_minus": False}) # restore
```
In matplotlib, you change the overall look with **`plt.rcParams`** (a dictionary of defaults) and individual parts with `ax.` functions. seaborn's `set_theme()` / `set_style()` are functions that change rcParams in bulk.
```{pyodide}
paper_rc = {
"font.size": 10, "axes.labelsize": 10, "axes.titlesize": 11, "axes.titleweight": "bold",
"xtick.labelsize": 9, "ytick.labelsize": 9, "legend.fontsize": 9,
"axes.spines.top": False, "axes.spines.right": False, # remove the top and right spines
"axes.grid": False, "xtick.direction": "out", "ytick.direction": "out",
"axes.edgecolor": "black", "xtick.color": "black", "ytick.color": "black",
}
with plt.rc_context(paper_rc): # change settings only inside this block
sns.set_style("ticks", {"font.family": "Noto Sans JP"})
fig, ax = plt.subplots(figsize=(6, 4))
sns.scatterplot(data=peng, x="flipper_length_mm", y="body_mass_g", hue="Species", palette=pal, s=20, ax=ax)
ax.legend(loc="upper left", frameon=False, title="Species")
ax.set(xlabel="Flipper length (mm)", ylabel="Body mass (g)", title="My own theme")
plt.show()
sns.set_theme(style="whitegrid", font="Noto Sans JP", rc={"axes.unicode_minus": False})
```
:::
## Displaying Japanese text on your own PC
::: {.panel-tabset group="lang"}
## R (ggplot2)
Japanese text in ggplot2 depends on the **graphics device** and the **font name**.
```r
# macOS
theme_set(theme_minimal(base_family = "Hiragino Sans"))
# Windows
theme_set(theme_minimal(base_family = "Yu Gothic"))
# Independent of the environment: ragg (RStudio's default device) or showtext
library(ragg)
ggsave("fig.png", p, device = ragg::agg_png, width = 85, height = 65, units = "mm", dpi = 300)
```
When saving as PDF, use `cairo_pdf`, which can embed Japanese (with the default `pdf()`, Japanese text may not be displayed).
```r
ggsave("fig.pdf", p, device = cairo_pdf, width = 85, height = 65, units = "mm")
```
## Python (seaborn / matplotlib)
In matplotlib, you **register a font file and specify it by name**. This is the same method as this hands-on's `py/setup.py`.
```python
from matplotlib import font_manager
font_manager.fontManager.addfont("NotoSansJP-Regular.ttf") # font file
plt.rcParams["font.family"] = "Noto Sans JP"
plt.rcParams["axes.unicode_minus"] = False # prevent the minus sign from rendering as a missing glyph
```
To use fonts installed in the OS, set `font.family` to `"Hiragino Sans"` (macOS), `"Yu Gothic"` (Windows), `"Noto Sans CJK JP"` (Linux), etc.
When characters turn into □ ("tofu"), check whether a `Glyph ... missing from font` warning was shown.
To embed Japanese in a PDF so that the text can be edited in Illustrator and the like, set it to **embed as TrueType**.
```python
plt.rcParams["pdf.fonttype"] = 42 # with the default 3, text is embedded as shapes and is hard to edit
plt.rcParams["ps.fonttype"] = 42
```
:::
## Making figures at the size required by journal guidelines
Journal figure widths are roughly **85–90 mm for a single column and 170–180 mm for two columns**. Text is typically required to be about **6–9 pt** when printed.
What matters is to **make the figure at its actual size from the start**. If you make it large and shrink it, text and lines become too small to read.
::: {.panel-tabset group="lang"}
## R (ggplot2)
```{webr}
#| fig-width: 3.35
#| fig-height: 2.6
# single-column width (85 mm = 3.35 inches), 8 pt text
base_plot + theme_paper(base_size = 8) + guides(colour = guide_legend(override.aes = list(size = 1.5)))
```
The 8 in `theme_paper(base_size = 8)` is in **points (pt)**. If you fix the actual size of the figure when saving, the text will be 8 pt when printed.
```r
ggsave("fig1.pdf", width = 85, height = 65, units = "mm", device = cairo_pdf) # vector
ggsave("fig1.tiff", width = 85, height = 65, units = "mm", dpi = 600, compression = "lzw") # raster
```
## Python (seaborn / matplotlib)
```{pyodide}
mm = 1 / 25.4 # 1 mm in inches
with plt.rc_context({**paper_rc, "font.size": 8, "axes.labelsize": 8, "axes.titlesize": 8,
"xtick.labelsize": 7, "ytick.labelsize": 7, "legend.fontsize": 7}):
sns.set_style("ticks", {"font.family": "Noto Sans JP"})
fig, ax = plt.subplots(figsize=(85 * mm, 65 * mm), dpi=150)
sns.scatterplot(data=peng, x="flipper_length_mm", y="body_mass_g", hue="Species", palette=pal, s=8, linewidth=0, ax=ax)
ax.legend(loc="upper left", frameon=False, title=None, handletextpad=0.1)
ax.set(xlabel="Flipper length (mm)", ylabel="Body mass (g)")
fig.tight_layout()
plt.show()
sns.set_theme(style="whitegrid", font="Noto Sans JP", rc={"axes.unicode_minus": False})
```
```python
fig.savefig("fig1.pdf", bbox_inches="tight") # vector
fig.savefig("fig1.tiff", dpi=600, pil_kwargs={"compression": "tiff_lzw"}) # raster
```
`bbox_inches="tight"` trims the margins, but note that **the figure becomes smaller than the specified size**. To keep the size exactly, adjust the margins with `fig.tight_layout()` or `layout="constrained"` and then save without specifying `bbox_inches`.
:::
## File formats
| Format | Type | When to use |
|---|---|---|
| **PDF / SVG / EPS** | Vector (no degradation when enlarged) | Figures for papers (lines, text, points). Can be edited later in Illustrator, etc. |
| **PNG** | Raster (lossless compression) | Slides and the web. Specify the resolution (dpi) |
| **TIFF** | Raster | Sometimes required by journals (300–600 dpi; e.g. 300 for photos, 600–1200 for line art) |
| JPEG | Raster (lossy compression) | Don't use for figures (lines and text get blurry edges) |
::: {.callout-tip}
## Figures with tens of thousands of points
Saving a scatter plot with tens of thousands of points as PDF makes the file heavy and slow to display. With `ggrastr` in ggplot2, or `ax.scatter(..., rasterized=True)` in matplotlib, you can **rasterize only the points while keeping text and axes as vectors**.
:::
## About saving inside the browser
R and Python on this page run inside the browser, so files saved with `ggsave()` or `savefig()` are created in **a virtual folder inside the browser** and are not saved to your PC.
You can still check the size of the saved files.
::: {.panel-tabset group="lang"}
## R (ggplot2)
```{webr}
ggsave("fig1.svg", base_plot + theme_paper(8), width = 85, height = 65, units = "mm")
ggsave("fig1.png", base_plot + theme_paper(8), width = 85, height = 65, units = "mm", dpi = 300)
file.size(c("fig1.svg", "fig1.png"))
```
## Python (seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots(figsize=(85 * mm, 65 * mm))
sns.scatterplot(data=peng, x="flipper_length_mm", y="body_mass_g", hue="Species", palette=pal, s=8, ax=ax)
fig.savefig("fig1.svg"); fig.savefig("fig1.png", dpi=300)
plt.close(fig)
import os
print({f: os.path.getsize(f) for f in ["fig1.svg", "fig1.png"]})
```
:::
::: {.callout-important}
## Chapter summary
- In ggplot2, change the whole with `theme_xxx()` and elements with `theme()` and `element_xxx()`. Make your own theme a function
- In matplotlib, change things with `rcParams` (temporarily with `rc_context`) and `ax.`. seaborn's `set_theme()` changes rcParams in bulk
- For Japanese text: in R, the font name and graphics device (ragg, cairo_pdf); in matplotlib, registering the font and `pdf.fonttype = 42`
- **Make figures at their actual size (mm) and text size (pt) from the start**. Vector (PDF/SVG) for papers; specify dpi for raster
:::