Skip to contents

Start with an ordinary ggplot

Use the same data, layers and scales you already use in ggplot2. A theme sets the size and weight of titles, the grid, spacing and legend. A colour scale maps data to colours. Here the factor’s levels give each cylinder count a stable colour.

library(ggplot2)
library(ggforma)
cars <- transform(mtcars, cylinders = factor(cyl))
p.cars <- ggplot(cars, aes(wt, mpg, colour = cylinders)) +
  geom_point(size = 2.5) +
  scale_colour_forma(limits = levels(cars$cylinders)) +
  labs(title = "Fuel economy by engine size", x = "Weight (1,000 lb)",
       y = "Miles per US gallon", colour = "Cylinders") +
  theme_forma(preset = "report", grid = "y")
p.cars

Choose panel = "framed" for bordered facets. Try preset = "journal" at the intended column width or preset = "presentation" at the intended slide size. For a dark background use matching mode = "dark" in both the theme and the scale. For print, medium = "greyscale" supplies a separate scale. Use symbols, direct labels or line types as a second cue when groups must be identifiable in grayscale.

Make a ring and a Mosaic

A chart has two kinds of labels. The model needs stable category IDs. Readers need names and number formats in their language. Compute from the IDs, then apply display labels. Two equal translations can still refer to separate categories.

trips <- data.frame(site = factor(c("N", "S")), visits = c(60, 40))
dict <- data.frame(variable = "site", id = c("N", "S"),
                   lang = "en", label = c("North", "South"))
ggpie(trips, "site", "visits", hole = 0.4, lang = "en", dictionary = dict) +
  labs(title = "Visits by site")

For several categorical dimensions, calculate proportional rectangles. With no gaps, a rectangle’s area equals its observed share. The figure below shows two-way independence. The signs and intensities of its Pearson residuals describe where observed counts differ from that model.

eye <- marginSums(HairEyeColor, c("Hair", "Eye"))
ggmosaic(eye, shade = "bands", hierarchy = TRUE) +
  labs(title = "Hair colour and eye colour")

mosaic_layout(eye)$cells retains the statistics for all cells, including cells too small to label. Declare structural exclusions separately if they are part of the sampling design. For survey weights use descriptive mode.

For a three-way table, name the dimension that defines the strata. This model makes admission and gender independent within each department. A residual threshold describes departure from the fitted counts. Formal inference requires a sampling model and an appropriate test.

model <- mosaic_layout(UCBAdmissions, model = "conditional", given = "Dept",
                       residual = "standardized")
model$diagnostics[c("method", "rank", "df_residual", "deviance")]
$method
[1] "product of within-stratum margins"

$rank
[1] 18

$df_residual
[1] 6

$deviance
[1] 21.73551

Change the display language

Keep a copy of the original plot. A local dictionary supplies the new display text. Number, percentage and date conventions can each use a separate locale. The following check compares the computed counts, angles and colours of the two editions.

p <- ggpie(trips, "site", "visits", .legend = TRUE)
cn <- forma_dictionary(c(N = "北区", S = "南区"), "zh-CN", "site")
edition <- p + locale_forma("zh-CN", dictionary = cn, number_locale = "de-DE")
fields <- c("slice", "count", "total", "prop", "start", "end", "fill")
stopifnot(identical(layer_data(p)[fields], layer_data(edition)[fields]))
extract_plot_text(edition, "categories")[c("id", "text")]
  id text
1  S 南区
2  N 北区
forma_translate("observed", "ja", diagnostics = TRUE)
        id context lang matched_lang  label  origin
1 observed    stat   ja           ja 観測値 builtin
                             source review_status status
1 ggforma AI-assisted seed glossary   provisional  exact

Use forma_dictionary() to inspect glossary sources and review status before publication. Save local entries with write.csv() and validate them again with forma_dictionary() after reading them. Mark code, formulas and rich markup as protected when calling forma_translate() on character input. A plot uses the dictionary available in memory each time it draws.

Plain text, structured inline markup and plotmath expressions serve different purposes. Use markup_grob() with a glyph-capable device for multi-script labels. Inspect the actual fonts chosen for your data using font_check(). A print or screen export still needs review at the final dimensions.

forma_format(c(0.25, 0.875), "percent", lang = "ar", digits = 1)
[1] "٢٥٫٠٪" "٨٧٫٥٪"
head(font_check("Library", family = "sans")[c("glyph", "fallback", "missing")])
  glyph fallback missing
1    47    FALSE   FALSE
2    76    FALSE   FALSE
3    69    FALSE   FALSE
4    85    FALSE   FALSE
5    68    FALSE   FALSE
6    85    FALSE   FALSE

Put a formula in a title

Use format = "mixed" to place R plotmath between dollar signs. The default Markdown grammar displays ordinary dollar signs. The same engine draws mixed annotations in data coordinates.

p.label <- p.cars +
  labs(title = "**Fuel economy** and the sample mean $bar(x)$") +
  theme(plot.title = element_markup(format = "mixed")) +
  annotate_markup(4.5, 30, "**Mean** $bar(x)$", format = "mixed")
p.label

Check the font and graphics device

font_check() returns a row for each shaped glyph. Look at its file and face index to see what the local system selected. A zero glyph or the missing flag calls for a different installed family. Test the actual text. A generic family can resolve differently on a colleague’s machine. For regional Chinese and Japanese forms, choose a locally available face designed for the intended region.

coverage <- font_check("ABC 2026", family = "sans")
head(coverage[c("path", "index", "fallback", "missing")])
                           path index fallback missing
1 C:\\WINDOWS\\Fonts\\arial.ttf     0    FALSE   FALSE
2 C:\\WINDOWS\\Fonts\\arial.ttf     0    FALSE   FALSE
3 C:\\WINDOWS\\Fonts\\arial.ttf     0    FALSE   FALSE
4 C:\\WINDOWS\\Fonts\\arial.ttf     0    FALSE   FALSE
5 C:\\WINDOWS\\Fonts\\arial.ttf     0    FALSE   FALSE
6 C:\\WINDOWS\\Fonts\\arial.ttf     0    FALSE   FALSE
   device number active positioned_glyphs
1 agg_png      2   TRUE              TRUE
                                                                                   advice
1 The device reports positioned glyph support. Use font_check() to inspect font coverage.

In Windows RStudio, draw an ordinary plot to open the Plots device and call forma_device_info(). If positioned glyphs are unavailable, select Tools → Global Options → General → Graphics → Backend → AGG, then open a new graphics device and redraw. Choose a local file device below if you want to keep the current IDE preferences.

Export at a known size

This example writes three files into an R temporary directory. Choose a directory you want to retain for publication. PNG resolution is in pixels per inch. SVG and PDF use physical dimensions.

out <- tempdir()
ggsave(file.path(out, "fuel-economy.png"), p.label, device = ragg::agg_png,
       width = 6, height = 4, units = "in", dpi = 180, bg = "white")
ggsave(file.path(out, "fuel-economy.svg"), p.label, device = grDevices::svg,
       width = 6, height = 4, units = "in", bg = "white")
ggsave(file.path(out, "fuel-economy.pdf"), p.label, device = grDevices::cairo_pdf,
       width = 6, height = 4, units = "in", bg = "white")
stopifnot(all(file.size(file.path(out, paste0("fuel-economy.", c("png", "svg", "pdf")))) > 0))

Check the exported figure at final size. Cairo SVG can store letters as paths. Text search and copy depend on how the file represents each run. Large plotmath operators can differ between PNG and PDF. Base pdf() advertises glyph support but showed incorrect ink in the Windows multilingual test.

The ordinary plot, high-level Pie and Mosaic, local dictionaries and the documented mixed-text grammar are supported development interfaces. Complex scripts and device combinations have fixture-specific evidence. Interactive conversion has a smaller text and layout contract. Aligned equation systems and vertical paragraphs remain future work.