| Title: | Backend-Agnostic Figure Builder for 'highcharter' and 'ggplot2' |
|---|---|
| Description: | Provides a backend-agnostic 'API' for creating data visualizations using 'highcharter' (interactive) or 'ggplot2' (static). Figures are defined once via a specification object and can be rendered to either backend without modifying the calling code. Supports both declarative and layered workflows, flexible theming and colour palettes, optional 'JavaScript' enhancements, and tools for exporting figures and interactive exploration via a 'shiny' app. |
| Authors: | Yusman Kamaleri [aut, cre] (ORCID: <https://orcid.org/0000-0001-5014-3665>) |
| Maintainer: | Yusman Kamaleri <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.5.0 |
| Built: | 2026-05-29 23:14:40 UTC |
| Source: | https://github.com/folkehelsestats/highdir |
Implements the + operator for hd() objects, mirroring how ggplot2
builds plots incrementally. Recognised right-hand sides:
## S3 method for class 'hd' e1 + e2## S3 method for class 'hd' e1 + e2
e1 |
An |
e2 |
An |
hd_geom objectSets the geometry (from any hd_geom_*() call).
Adding a second geom replaces the first where highdir renders one geometry
per figure.
hd_opts objectSets presentation options. Adding a second
hd_opts replaces the first.
Unknown right-hand sides produce an informative error rather than silently being ignored.
The updated hd object (invisibly, so the chain prints once).
df <- data.frame(age = c("18-24", "25-34"), pct = c(42, 55)) # Chain layers p <- hd(df, x = "age", y = "pct") + hd_geom_column() + hd_opts(title = "Demo") # Reuse a partial object with different opts base <- hd(df, x = "age", y = "pct") + hd_geom_column() base + hd_opts(title = "English title") base + hd_opts(title = "Norsk tittel")df <- data.frame(age = c("18-24", "25-34"), pct = c(42, 55)) # Chain layers p <- hd(df, x = "age", y = "pct") + hd_geom_column() + hd_opts(title = "Demo") # Reuse a partial object with different opts base <- hd(df, x = "age", y = "pct") + hd_geom_column() base + hd_opts(title = "English title") base + hd_opts(title = "Norsk tittel")
Annual estimates of alcohol consumption, including adjusted mean values,
standard errors, and 95% confidence intervals. Includes an alternative
unit (adj_enhet) with corresponding uncertainty estimates.
A data frame with 14 rows and 9 variables:
Helsedirektoratet. Tall om alkohol. https://www.helsedirektoratet.no/rapporter/tall-om-alkohol
Annual estimates of alcohol consumption stratified by kjønn
(gender), including adjusted means, standard errors, and 95\
intervals. Also includes an alternative unit (adj_enhet) with uncertainty.
A data frame with 28 rows and 10 variables:
Helsedirektoratet. Tall om alkohol. https://www.helsedirektoratet.no/rapporter/tall-om-alkohol
Prints the required and optional ... arguments accepted by a geometry
when used with hd_make(). This is the primary discoverability tool
for geometry-specific arguments that do not appear in hd_make()'s
signature.
geom_args(type = NULL)geom_args(type = NULL)
type |
Character. Geometry name, e.g. |
A data frame of argument metadata, invisibly. The primary purpose is the side-effect of printing.
hd_make() uses ... for all geometry-specific arguments so its own
signature stays clean regardless of how many geometries are registered.
The trade-off is that users cannot see available args from hd_make()
alone. geom_args() solves that: it reads the required_args and
optional_args fields registered for each geometry and presents them
in a readable table.
geom_args("line") geom_args("ranked_bar") geom_args("arearange") geom_args() # all registered geometriesgeom_args("line") geom_args("ranked_bar") geom_args("arearange") geom_args() # all registered geometries
Retrieve a Named Palette
get_palette(name)get_palette(name)
name |
Character. Palette name (see |
Character vector of colours, or NULL if not found.
get_palette("hdir")get_palette("hdir")
Constructs a ggplot2 theme by resolving a base theme, then merging colour
and font overrides – exactly mirroring what hd_theme() does for the
highcharter backend.
gg_theme(theme = NULL, colors = NULL, font = NULL)gg_theme(theme = NULL, colors = NULL, font = NULL)
theme |
Character name string, ggplot2 theme object, or |
colors |
Character vector, palette name string, or |
font |
Character or |
Priority for each argument:
theme: explicit argument > getOption("highdir.gg_theme") > "classic"
colors: explicit argument > getOption("highdir.colors") > NULL
font: explicit argument > getOption("highdir.font") > NULL
Called automatically inside ggplot_engine(); also useful for applying the
package theme to a ggplot built outside highdir.
Built-in name strings and their ggplot2 equivalents:
| Name | ggplot2 function |
"classic" (default) |
theme_classic() |
"minimal" |
theme_minimal() |
"bw" |
theme_bw() |
"light" |
theme_light() |
"dark" |
theme_dark() |
"void" |
theme_void() |
"grey" / "gray" |
theme_grey()
|
An object of class "hd_gg_theme" - a list with two fields:
$theme (a ggplot2 theme object with font baked in) and $colors
(a resolved character vector or NULL). ggplot_engine() unpacks
both. The object can also be added directly to a ggplot with +
via the +.gg method (only the theme is applied; colors are handled
separately by apply_gg_colors()).
gg_theme() # session defaults gg_theme("bw") # theme_bw(), session colors/font gg_theme("classic", colors = c("#025169", "#7C145C")) gg_theme("minimal", font = "Source Sans Pro") gg_theme(ggplot2::theme_bw(base_size = 14), font = "mono")gg_theme() # session defaults gg_theme("bw") # theme_bw(), session colors/font gg_theme("classic", colors = c("#025169", "#7C145C")) gg_theme("minimal", font = "Source Sans Pro") gg_theme(ggplot2::theme_bw(base_size = 14), font = "mono")
Creates an hd object that accumulates geometry and presentation layers
via +, then renders when printed. This mirrors the way ggplot2 builds
plots: data mapping is declared first; visual decisions are added
incrementally; nothing is rendered until the object hits the console (or an
explicit print() / knit call).
hd( data, x = NULL, y = NULL, group = NULL, n = NULL, colour = NULL, backend = getOption("highdir.backend", "highcharter") )hd( data, x = NULL, y = NULL, group = NULL, n = NULL, colour = NULL, backend = getOption("highdir.backend", "highcharter") )
data |
A |
x |
Character. Column name for the x-axis variable.
Ignored when |
y |
Character. Column name for the y-axis variable.
Ignored when |
group |
Character or |
n |
Character or |
colour |
Character or |
backend |
Character. Rendering engine - |
hd() accepts either raw data columns or an existing hd_spec() object.
Passing an hd_spec is the recommended bridge for code that already
constructs specs separately (e.g. in Shiny or a reporting pipeline).
An S3 object of class "hd" with slots:
$specAn hd_spec() object.
$geomNULL until a + hd_geom_*() layer is added.
$optsAn hd_opts() object (defaults until overridden).
$backendCharacter. The resolved engine name.
hd_geom_column(), hd_geom_line(), hd_geom_arearange(),
hd_opts(), hd_make()
df <- data.frame( age = rep(c("18-24", "25-34", "35-44", "45-54"), each = 2), sex = rep(c("Male", "Female"), 4), pct = c(42, 38, 55, 61, 48, 52, 60, 57), n = c(120, 115, 200, 210, 180, 175, 160, 155) ) # Composable style hd(df, x = "age", y = "pct", group = "sex") + hd_geom_column() + hd_opts(title = "Health survey", ylim = c(0, 80)) # Pass an existing hd_spec spec <- hd_spec(df, x = "age", y = "pct", group = "sex", n = "n") hd(spec) + hd_geom_line(smooth = TRUE) + hd_opts(title = "Trend") # Switch backend per figure hd(df, x = "age", y = "pct", backend = "ggplot2") + hd_geom_column() + hd_opts(title = "Static version")df <- data.frame( age = rep(c("18-24", "25-34", "35-44", "45-54"), each = 2), sex = rep(c("Male", "Female"), 4), pct = c(42, 38, 55, 61, 48, 52, 60, 57), n = c(120, 115, 200, 210, 180, 175, 160, 155) ) # Composable style hd(df, x = "age", y = "pct", group = "sex") + hd_geom_column() + hd_opts(title = "Health survey", ylim = c(0, 80)) # Pass an existing hd_spec spec <- hd_spec(df, x = "age", y = "pct", group = "sex", n = "n") hd(spec) + hd_geom_line(smooth = TRUE) + hd_opts(title = "Trend") # Switch backend per figure hd(df, x = "age", y = "pct", backend = "ggplot2") + hd_geom_column() + hd_opts(title = "Static version")
Appends custom JavaScript to a highchart object via
chart.events.<where>. Use this for hand-written callbacks and plugins.
For Highcharts built-in modules (accessibility, exporting, etc.) use
highcharter::hc_add_dependency() instead.
hd_add_js( hc, code = NULL, file = NULL, plugin = NULL, where = c("load", "render") )hd_add_js( hc, code = NULL, file = NULL, plugin = NULL, where = c("load", "render") )
hc |
A |
code |
Character or |
file |
Character or |
plugin |
Character or |
where |
|
Exactly one of code, file, or plugin must be supplied.
The highchart object with JS injected.
if (interactive()) { spec <- hd_spec(mtcars, "wt", "mpg") fig <- hd_make(spec, "scatter") fig <- hd_add_js(fig, code = "console.log('chart loaded');") }if (interactive()) { spec <- hd_spec(mtcars, "wt", "mpg") fig <- hd_make(spec, "scatter") fig <- hd_add_js(fig, code = "console.log('chart loaded');") }
Opens an interactive browser-based application for building figures with
highcharter or ggplot2 without writing R code.
hd_app(return.app = FALSE)hd_app(return.app = FALSE)
return.app |
Logical. When deploying to server like Shiny.io to return the app object instead of launching it. |
The UI (inst/app/ui.R), server (inst/app/server.R) and shared setup
(inst/app/global.R) live in inst/app/ so the folder can be deployed
independently to Shiny Server or shinyapps.io.
Launches a Shiny app; does not return a value.
Upload datasets in any format supported by rio (CSV, XLSX, SPSS, Stata, RDS, …).
Choose geometry (column,
line, scatter, arearange, pie), backend, axis variables, and group
column.
Set title, subtitle, caption, colour palette, and HC theme.
Toggle JS hover band per figure.
Render on demand with the Draw button.
Download as HTML / JSON / PNG (highcharter) or PNG / SVG (ggplot2).
Copy the equivalent hd_make() call from the R
code tab.
hd_make(), hd_spec(), hd_opts(), hd_save()
Geometry layer for ribbon / confidence-interval charts. Unlike the other
hd_geom_*() functions, ymin and ymax are required named arguments
(they map to column names in spec$data) rather than optional ... extras.
This makes the contract explicit at the call site instead of burying
required information inside ....
hd_geom_arearange(ymin = NULL, ymax = NULL, ...)hd_geom_arearange(ymin = NULL, ymax = NULL, ...)
ymin |
Character. Column name for the lower bound of the range. |
ymax |
Character. Column name for the upper bound of the range. |
... |
Additional optional arguments forwarded to the geom function
(e.g. |
An S3 object of class "hd_geom" for use with +.hd.
# Single series spec_ar1 <- hd_spec(alco1, x = "year", y = "adj_enhet") opts_ar <- hd_opts( title = "Alcohol consumption with 95% CI", subtitle = "Source: Norwegian Directorate of Health", ylim = c(0, 30), ylab = "Number of units alcohol" ) hd_make(spec_ar1, "arearange", opts_ar, ymin = "lower_enhet", ymax = "upper_enhet") # Static ggplot2 version hd_make(spec_ar1, "arearange", opts_ar, ymin = "lower_enhet", ymax = "upper_enhet", backend = "ggplot2") #' # Multi-series with group column # Grouped by kjonn spec_ar2 <- hd_spec(alco2, x = "year", y = "adj_enhet", group = "kjonn") hd_make(spec_ar2, "arearange", opts_ar, ymin = "lower_enhet", ymax = "upper_enhet")# Single series spec_ar1 <- hd_spec(alco1, x = "year", y = "adj_enhet") opts_ar <- hd_opts( title = "Alcohol consumption with 95% CI", subtitle = "Source: Norwegian Directorate of Health", ylim = c(0, 30), ylab = "Number of units alcohol" ) hd_make(spec_ar1, "arearange", opts_ar, ymin = "lower_enhet", ymax = "upper_enhet") # Static ggplot2 version hd_make(spec_ar1, "arearange", opts_ar, ymin = "lower_enhet", ymax = "upper_enhet", backend = "ggplot2") #' # Multi-series with group column # Grouped by kjonn spec_ar2 <- hd_spec(alco2, x = "year", y = "adj_enhet", group = "kjonn") hd_make(spec_ar2, "arearange", opts_ar, ymin = "lower_enhet", ymax = "upper_enhet")
hd_geom_column() creates a column geometry layer that is added to an hd()
object via +. The layer records the geometry type and any geometry-specific
arguments; rendering only happens when the hd object is printed.
hd_geom_column(...)hd_geom_column(...)
... |
Geometry-specific arguments forwarded to |
An S3 object of class "hd_geom" for use with +.hd.
survey <- data.frame( age_group = rep(c("18-24", "25-34", "35-44", "45-54", "55-64"), each = 2), kjonn = rep(c("Male", "Female"), times = 5), pct = c(42, 38, 55, 61, 48, 52, 60, 57, 65, 70), n = c(120, 115, 200, 210, 180, 175, 160, 155, 140, 145) ) spec_col <- hd_spec(survey, x = "age_group", y = "pct", group = "kjonn", n = "n") opts_col <- hd_opts( title = "Alcohol use by age group and kjonn", subtitle = "Source: Norwegian Directorate of Health", ylim = c(0, 100), yint = 20, ylab = "Percentage (%)" ) # Interactive (default) hd_make(spec_col, "column", opts_col) # Static ggplot2 hd_make(spec_col, "column", opts_col, backend = "ggplot2") # Composable style p <- hd(survey, x = "age_group", y = "pct", group = "kjonn") p2 <- p + hd_geom_column() # More options p2 + hd_opts(title = "Health survey", ylim = c(0, 100)) # Pass an existing hd_spec spec <- hd_spec(survey, x = "age_group", y = "pct", group = "kjonn", n = "n") hd(spec, backend = "ggplot2") + hd_geom_column() + hd_opts(title = "Health survey", ylim = c(0, 80))survey <- data.frame( age_group = rep(c("18-24", "25-34", "35-44", "45-54", "55-64"), each = 2), kjonn = rep(c("Male", "Female"), times = 5), pct = c(42, 38, 55, 61, 48, 52, 60, 57, 65, 70), n = c(120, 115, 200, 210, 180, 175, 160, 155, 140, 145) ) spec_col <- hd_spec(survey, x = "age_group", y = "pct", group = "kjonn", n = "n") opts_col <- hd_opts( title = "Alcohol use by age group and kjonn", subtitle = "Source: Norwegian Directorate of Health", ylim = c(0, 100), yint = 20, ylab = "Percentage (%)" ) # Interactive (default) hd_make(spec_col, "column", opts_col) # Static ggplot2 hd_make(spec_col, "column", opts_col, backend = "ggplot2") # Composable style p <- hd(survey, x = "age_group", y = "pct", group = "kjonn") p2 <- p + hd_geom_column() # More options p2 + hd_opts(title = "Health survey", ylim = c(0, 100)) # Pass an existing hd_spec spec <- hd_spec(survey, x = "age_group", y = "pct", group = "kjonn", n = "n") hd(spec, backend = "ggplot2") + hd_geom_column() + hd_opts(title = "Health survey", ylim = c(0, 80))
hd_geom_line() creates a line geometry layer that is added to an hd()
object via +. The layer records the geometry type and any geometry-specific arguments;
rendering only happens when the hd object is printed.
hd_geom_line(smooth = TRUE, dot_size = 4, line_symbols = NULL, ...)hd_geom_line(smooth = TRUE, dot_size = 4, line_symbols = NULL, ...)
smooth |
Logical. TRUE = spline curves, FALSE = straight segments. Both backends. |
dot_size |
Numeric. Marker radius in pixels. Both backends. |
line_symbols |
Character vector. Highcharter only. Per-group marker shapes: "circle", "square", "diamond", "triangle", "triangle-down". |
... |
Geometry-specific arguments forwarded to |
An S3 object of class "hd_geom" for use with +.hd.
# Single series - no group column spec_line1 <- hd_spec(alco1, x = "year", y = "adj_mean" ) opts_line <- hd_opts( title = "Alcohol consumption over time", subtitle = "Source: Norwegian Directorate of Health", ylim = c(0, 50), ylab = "Litres per capita" ) # Straight segments hd_make(spec_line1, "line", opts_line, smooth = FALSE) # Composite example with multiple geoms and custom line symbols hd(alco2, x = "year", y = "adj_mean", group = "kjonn", backend = "ggplot2") + hd_geom_line(smooth = TRUE, dot_size = 3) + hd_opts(title = "Alcohol consumption over time by kjonn", subtitle = "Source: Norwegian Directorate of Health")# Single series - no group column spec_line1 <- hd_spec(alco1, x = "year", y = "adj_mean" ) opts_line <- hd_opts( title = "Alcohol consumption over time", subtitle = "Source: Norwegian Directorate of Health", ylim = c(0, 50), ylab = "Litres per capita" ) # Straight segments hd_make(spec_line1, "line", opts_line, smooth = FALSE) # Composite example with multiple geoms and custom line symbols hd(alco2, x = "year", y = "adj_mean", group = "kjonn", backend = "ggplot2") + hd_geom_line(smooth = TRUE, dot_size = 3) + hd_opts(title = "Alcohol consumption over time by kjonn", subtitle = "Source: Norwegian Directorate of Health")
hd_geom_pie() creates a pie geometry layer that is added to an hd()
object via +. The layer records the geometry type and any geometry-specific
arguments; rendering only happens when the hd object is printed.
hd_geom_pie(inner_size = "0%", ...)hd_geom_pie(inner_size = "0%", ...)
inner_size |
A string specifying the inner radius of the pie as a percentage of the total radius. For example, "50%" creates a donut chart with a hole in the middle. The default "0%" creates a standard pie chart. This argument is only applicable to the Highcharts backend; it is ignored by ggplot2 since it does not support donut charts. |
... |
Geometry-specific arguments forwarded to |
An S3 object of class "hd_geom" for use with +.hd.
# Category share dataset (pie) drinking_freq <- data.frame( category = c("Never", "Rarely", "Monthly", "Weekly", "Daily"), pct = c(18, 25, 30, 20, 7) ) spec_pie <- hd_spec(drinking_freq, x = "category", y = "pct" ) opts_pie <- hd_opts( title = "Drinking frequency", subtitle = "Source: Norwegian Directorate of Health", ylab = "Share (%)" ) # Donut interactive hd_make(spec_pie, "pie", opts_pie, inner_size = "50%") # Composable API style (ggplot2 ignores inner_size) hd(drinking_freq, x = "category", y = "pct", backend = "ggplot2") + hd_geom_pie() + hd_opts( title = "Drinking frequency", subtitle = "Source: Norwegian Directorate of Health" )# Category share dataset (pie) drinking_freq <- data.frame( category = c("Never", "Rarely", "Monthly", "Weekly", "Daily"), pct = c(18, 25, 30, 20, 7) ) spec_pie <- hd_spec(drinking_freq, x = "category", y = "pct" ) opts_pie <- hd_opts( title = "Drinking frequency", subtitle = "Source: Norwegian Directorate of Health", ylab = "Share (%)" ) # Donut interactive hd_make(spec_pie, "pie", opts_pie, inner_size = "50%") # Composable API style (ggplot2 ignores inner_size) hd(drinking_freq, x = "category", y = "pct", backend = "ggplot2") + hd_geom_pie() + hd_opts( title = "Drinking frequency", subtitle = "Source: Norwegian Directorate of Health" )
Draws a ranked bar chart with smart label placement and optional comparison highlighting. Bars are sorted by value, and labels are placed inside or outside the bar depending on available space. A single category can be highlighted with a contrasting fill colour, and an optional horizontal line can be added to indicate a target or benchmark value.
hd_geom_ranked_bar( ascending = TRUE, vs = NULL, aim = NULL, char_scale = 0.045, min_frac = 0.08, ... )hd_geom_ranked_bar( ascending = TRUE, vs = NULL, aim = NULL, char_scale = 0.045, min_frac = 0.08, ... )
ascending |
Logical. If |
vs |
Character string (partial match) identifying one category to highlight with a contrasting fill colour. If omitted all bars use the same colour. |
aim |
Numeric. Optional horizontal line indicating a target or benchmark
value. If |
char_scale |
Numeric scaling factor that converts label character-count
into axis-range units. Controls how generously space is estimated for each
character. Defaults to |
min_frac |
Numeric. Minimum fraction of the axis range that a bar must
span before its label is considered to fit inside. Acts as a safety floor
for very short labels. Defaults to |
... |
Geometry-specific arguments forwarded to |
An S3 object of class "hd_geom" for use with +.hd.
hd_geom_column(), hd_geom_line(), hd_geom_arearange(),
hd_opts(), hd_make()
# Regional health indicator dataset regions <- data.frame( region = c("Oslo", "Viken", "Vestland", "Rogaland", "Trondelag", "Innlandet", "Agder", "Nordland", "Troms og Finnmark"), rate = c(68.4, 71.2, 87.8, 10.5, 61.3, 6.1, 54.2, 49.8, 42.1), n = c(402, 448, 681, 318, 297, 251, 198, 177, 148) ) # Declarative API ---- spec_rb <- hd_spec(regions, x = "region", y = "rate", n = "n") opts_rb <- hd_opts( title = "Health indicator by region", subtitle = "Source: Norwegian Directorate of Health", ylab = "Rate per 100 000", flip = TRUE ) hd_make(spec_rb, "ranked_bar", opts_rb, vs = "Oslo", aim = 63) # Layered API ---- hd(regions, x = "region", y = "rate", n = "n", backend = "ggplot2") + hd_geom_ranked_bar( ascending = TRUE, vs = "Oslo", aim = 63, char_scale = 0.045, min_frac = 0.08) + hd_opts( title = "Health indicator by region", subtitle = "Source: Norwegian Directorate of Health", ylab = "Rate per 100 000", flip = TRUE )# Regional health indicator dataset regions <- data.frame( region = c("Oslo", "Viken", "Vestland", "Rogaland", "Trondelag", "Innlandet", "Agder", "Nordland", "Troms og Finnmark"), rate = c(68.4, 71.2, 87.8, 10.5, 61.3, 6.1, 54.2, 49.8, 42.1), n = c(402, 448, 681, 318, 297, 251, 198, 177, 148) ) # Declarative API ---- spec_rb <- hd_spec(regions, x = "region", y = "rate", n = "n") opts_rb <- hd_opts( title = "Health indicator by region", subtitle = "Source: Norwegian Directorate of Health", ylab = "Rate per 100 000", flip = TRUE ) hd_make(spec_rb, "ranked_bar", opts_rb, vs = "Oslo", aim = 63) # Layered API ---- hd(regions, x = "region", y = "rate", n = "n", backend = "ggplot2") + hd_geom_ranked_bar( ascending = TRUE, vs = "Oslo", aim = 63, char_scale = 0.045, min_frac = 0.08) + hd_opts( title = "Health indicator by region", subtitle = "Source: Norwegian Directorate of Health", ylab = "Rate per 100 000", flip = TRUE )
hd_geom_scatter() creates a scatter geometry layer that is added to an
hd() object via +. Use geom_args() to discover available arguments per
geometry, e.g. geom_args("scatter") lists dot_size.
hd_geom_scatter(dot_size = 4, ...)hd_geom_scatter(dot_size = 4, ...)
dot_size |
Numeric. Size of the points in the scatter plot. Default is 4. |
... |
Geometry-specific arguments forwarded to |
An S3 object of class "hd_geom" for use with +.hd.
# Basic scatter plot - layered API hd(mtcars, x = "wt", y = "mpg", backend = "ggplot2") + hd_geom_scatter() + hd_opts(title = "Scatter Plot of mtcars") # Basic scatter plot - declarative API car <- hd_spec(mtcars, x = "wt", y = "mpg") opt <- hd_opts(title = "Scatter Plot of mtcars") hd_make(car, type = "scatter")# Basic scatter plot - layered API hd(mtcars, x = "wt", y = "mpg", backend = "ggplot2") + hd_geom_scatter() + hd_opts(title = "Scatter Plot of mtcars") # Basic scatter plot - declarative API car <- hd_spec(mtcars, x = "wt", y = "mpg") opt <- hd_opts(title = "Scatter Plot of mtcars") hd_make(car, type = "scatter")
Create a stacked column geometry layer for hd objects. Each stack is a facet
(sub-panel) containing one or more series. The stack argument specifies
the column in the data that defines the stacks. The group aesthetic in
hd_spec() defines the series within each stack. The stacking
argument controls how the stacks are rendered: "normal" (default) stacks values
on top of each other, while "percent" stacks values as percentages of the total
stack height.
hd_geom_stacked_column(stack, stacking = c("normal", "percent"), ...)hd_geom_stacked_column(stack, stacking = c("normal", "percent"), ...)
stack |
Character. Column name for the stack variable. Each unique value in this column creates a separate stack (facet) containing all series with that stack value. Required. |
stacking |
Character. Stacking mode for the column geometry. One of
|
... |
Additional optional arguments forwarded to the geom function
(e.g. |
An S3 object of class "hd_geom" for use with +.hd.
# Example data: medal counts for four countries across three medal types olympics <- data.frame( Country = rep(c("Norway", "Germany", "United States", "Canada"), each = 3), Continent = rep(c("Europe", "Europe", "North America", "North America"), each = 3), Medal = rep(c("Gold", "Silver", "Bronze"), times = 4), Count = c(148, 133, 124, 102, 98, 65, 113, 122, 95, 77, 72, 80) ) # Define Specification and Options spec_st <- hd_spec(olympics, x = "Medal", y = "Count", group = "Country" ) opts_st <- hd_opts( title = "Olympic Games all-time medal table, grouped by continent", subtitle = "Source: Olympics", ylab = "Count medals" ) # Interactive - stacks are separated by continent hd_make(spec_st, "stacked_column", opts_st, stack = "Continent") # Static ggplot2 - stacks are separated by continent hd(spec_st, backend = "ggplot2") + hd_geom_stacked_column(stack = "Continent") + hd_opts(title = "Olympic Games all-time medal table, grouped by continent", ylab = "Count medals")# Example data: medal counts for four countries across three medal types olympics <- data.frame( Country = rep(c("Norway", "Germany", "United States", "Canada"), each = 3), Continent = rep(c("Europe", "Europe", "North America", "North America"), each = 3), Medal = rep(c("Gold", "Silver", "Bronze"), times = 4), Count = c(148, 133, 124, 102, 98, 65, 113, 122, 95, 77, 72, 80) ) # Define Specification and Options spec_st <- hd_spec(olympics, x = "Medal", y = "Count", group = "Country" ) opts_st <- hd_opts( title = "Olympic Games all-time medal table, grouped by continent", subtitle = "Source: Olympics", ylab = "Count medals" ) # Interactive - stacks are separated by continent hd_make(spec_st, "stacked_column", opts_st, stack = "Continent") # Static ggplot2 - stacks are separated by continent hd(spec_st, backend = "ggplot2") + hd_geom_stacked_column(stack = "Continent") + hd_opts(title = "Olympic Games all-time medal table, grouped by continent", ylab = "Count medals")
Renders a hd_spec and hd_opts pair using the selected backend and
geometry. This is the central function of the package - everything else
feeds into or flows out of hd_make().
hd_make( spec, type = "column", opts = NULL, backend = "highcharter", use_js = TRUE, module = FALSE, ... )hd_make( spec, type = "column", opts = NULL, backend = "highcharter", use_js = TRUE, module = FALSE, ... )
spec |
|
type |
Character. Geometry name - one of |
opts |
A hd_opts object or |
backend |
Character. Rendering engine - |
use_js |
Logical. When |
module |
Use available modules js from CDN https://api.highcharts.com/highcharts/ |
... |
Extra arguments forwarded to the geometry function.
Required arguments (e.g. |
A highchart widget (highcharter backend) or ggplot object
(ggplot2 backend), invisibly wrapped so knitr/Shiny render it
automatically.
spec <- hd_spec(df, x = "age", y = "pct", group = "sex", n = "n") opts <- hd_opts(title = "Health survey", ylim = c(0, 80)) hd_make(spec, "column", opts) # highcharter (default) hd_make(spec, "column", opts, backend = "ggplot2") # static ggplot2 hd_make(spec, "line", opts, smooth = TRUE) # smooth spline hd_make(spec, "pie", opts) # pie / donut
hd_spec(), hd_opts(), hd_save(), hd_set_theme(),
list_geoms(), list_backends(), hd_app()
df <- data.frame( age = rep(c("18-24", "25-34", "35-44", "45-54"), each = 2), sex = rep(c("Male", "Female"), 4), pct = c(42, 38, 55, 61, 48, 52, 60, 57), n = c(120, 115, 200, 210, 180, 175, 160, 155) ) spec <- hd_spec(df, x = "age", y = "pct", group = "sex", n = "n") opts <- hd_opts(title = "Health survey results", subtitle = "Source: FHI 2024", ylim = c(0, 80)) # -- Interactive charts (highcharter) -------------------------------------- hd_make(spec, "column", opts) hd_make(spec, "line", opts, smooth = TRUE) hd_make(spec, "line", opts, smooth = FALSE, dot_size = 6) hd_make(spec, "scatter") # Pie chart - group is ignored; x = label, y = value pie_df <- data.frame(category = c("A","B","C","D"), value = c(35, 25, 20, 20)) pie_spec <- hd_spec(pie_df, x = "category", y = "value") pie_opts <- hd_opts(title = "Share by category") hd_make(pie_spec, "pie", pie_opts) hd_make(pie_spec, "pie", pie_opts, inner_size = "50%") # donut # Arearange - requires ymin + ymax in ... df2 <- cbind(df, lo = df$pct - 5, hi = df$pct + 5) spec2 <- hd_spec(df2, "age", "pct", group = "sex") hd_make(spec2, "arearange", opts, ymin = "lo", ymax = "hi") # -- Disable JS hover band ------------------------------------------------- hd_make(spec, "column", opts, use_js = FALSE) # -- Static ggplot2 versions ----------------------------------------------- hd_make(spec, "column", opts, backend = "ggplot2") hd_make(spec, "line", opts, backend = "ggplot2") hd_make(spec, "scatter", opts, backend = "ggplot2") hd_make(pie_spec, "pie", pie_opts, backend = "ggplot2") # -- Reuse spec with different presentation -------------------------------- opts_no <- hd_opts(title = "Helseundersøkelse", subtitle = "Alle aldre") hd_make(spec, "column", opts_no) # -- Save outputs ---------------------------------------------------------- hd_save(hd_make(spec, "column", opts), "column.html") hd_save(hd_make(spec, "column", opts, backend="ggplot2"), "column.png")df <- data.frame( age = rep(c("18-24", "25-34", "35-44", "45-54"), each = 2), sex = rep(c("Male", "Female"), 4), pct = c(42, 38, 55, 61, 48, 52, 60, 57), n = c(120, 115, 200, 210, 180, 175, 160, 155) ) spec <- hd_spec(df, x = "age", y = "pct", group = "sex", n = "n") opts <- hd_opts(title = "Health survey results", subtitle = "Source: FHI 2024", ylim = c(0, 80)) # -- Interactive charts (highcharter) -------------------------------------- hd_make(spec, "column", opts) hd_make(spec, "line", opts, smooth = TRUE) hd_make(spec, "line", opts, smooth = FALSE, dot_size = 6) hd_make(spec, "scatter") # Pie chart - group is ignored; x = label, y = value pie_df <- data.frame(category = c("A","B","C","D"), value = c(35, 25, 20, 20)) pie_spec <- hd_spec(pie_df, x = "category", y = "value") pie_opts <- hd_opts(title = "Share by category") hd_make(pie_spec, "pie", pie_opts) hd_make(pie_spec, "pie", pie_opts, inner_size = "50%") # donut # Arearange - requires ymin + ymax in ... df2 <- cbind(df, lo = df$pct - 5, hi = df$pct + 5) spec2 <- hd_spec(df2, "age", "pct", group = "sex") hd_make(spec2, "arearange", opts, ymin = "lo", ymax = "hi") # -- Disable JS hover band ------------------------------------------------- hd_make(spec, "column", opts, use_js = FALSE) # -- Static ggplot2 versions ----------------------------------------------- hd_make(spec, "column", opts, backend = "ggplot2") hd_make(spec, "line", opts, backend = "ggplot2") hd_make(spec, "scatter", opts, backend = "ggplot2") hd_make(pie_spec, "pie", pie_opts, backend = "ggplot2") # -- Reuse spec with different presentation -------------------------------- opts_no <- hd_opts(title = "Helseundersøkelse", subtitle = "Alle aldre") hd_make(spec, "column", opts_no) # -- Save outputs ---------------------------------------------------------- hd_save(hd_make(spec, "column", opts), "column.html") hd_save(hd_make(spec, "column", opts, backend="ggplot2"), "column.png")
Defines the visual presentation of a figure independently from the data
mapping. Pass the result as the opts argument of hd_make(), or omit
it to accept all defaults.
hd_opts( title = NULL, subtitle = NULL, caption = NULL, description = NULL, xlab = " ", ylab = " ", ylim = NULL, yint = 10, ysuffix = NULL, xtick_labels = NULL, decimals = NULL, flip = FALSE, colors = NULL, hc_theme = NULL, gg_theme = NULL )hd_opts( title = NULL, subtitle = NULL, caption = NULL, description = NULL, xlab = " ", ylab = " ", ylim = NULL, yint = 10, ysuffix = NULL, xtick_labels = NULL, decimals = NULL, flip = FALSE, colors = NULL, hc_theme = NULL, gg_theme = NULL )
title |
Character or |
subtitle |
Character or |
caption |
Character or |
description |
Character or
Write a concise one- or two-sentence summary of what the figure shows,
including the key trend or comparison, so the information is equally
accessible to users who cannot see the chart. Example:
|
xlab |
Character or
|
ylab |
Character or |
ylim |
Numeric vector of length 2 or |
yint |
Positive numeric. Y-axis tick interval. Default |
ysuffix |
Character or |
xtick_labels |
Character or |
decimals |
Integer or |
flip |
Logical. Invert axes (horizontal bars / inverted chart).
Default |
colors |
Character vector, palette name string, or |
hc_theme |
Character or |
gg_theme |
Character name string, ggplot2 theme object, or |
Because opts are separate from hd_spec(), the same data mapping can
be rendered with multiple styles without repetition:
spec <- hd_spec(df, "age", "pct", group = "sex") opts_en <- hd_opts(title = "Health survey", subtitle = "All ages") opts_no <- hd_opts(title = "Helseundersøkelse", subtitle = "Alle aldre") hd_make(spec, "column", opts_en) hd_make(spec, "column", opts_no)
An S3 object of class "hd_opts".
hd_spec(), hd_make(), hd_set_theme()
opts <- hd_opts( title = "Health survey results", subtitle = "Source: FHI 2024", caption = "Tall om helse", description = paste( "Grouped bar chart showing alcohol use by age group and sex.", "Use is highest in the 45-54 age group at 65% for women." ), ylim = c(0, 100), yint = 20, colors = c("#025169", "#7C145C") ) optsopts <- hd_opts( title = "Health survey results", subtitle = "Source: FHI 2024", caption = "Tall om helse", description = paste( "Grouped bar chart showing alcohol use by age group and sex.", "Use is highest in the 45-54 age group at 65% for women." ), ylim = c(0, 100), yint = 20, colors = c("#025169", "#7C145C") ) opts
Exports a highchart or ggplot figure produced by hd_make() to a
file. The output format is inferred from the file extension unless type
is supplied explicitly.
hd_save( fig, file, type = "auto", width = 8, height = 5, dpi = 300, selfcontained = TRUE, ... )hd_save( fig, file, type = "auto", width = 8, height = 5, dpi = 300, selfcontained = TRUE, ... )
fig |
A |
file |
Character. Output path including extension. |
type |
|
width |
Numeric. Width in inches (ggplot2). Default: |
height |
Numeric. Height in inches (ggplot2). Default: |
dpi |
Numeric. Raster resolution for ggplot2. Default: |
selfcontained |
Logical. Embed all JS/CSS in the HTML file.
Default: |
... |
Passed to |
| Backend | Supported formats |
| highcharter | html, json |
| ggplot2 | png, svg, pdf, jpeg, jpg, |
tiff, bmp, eps
|
To export a highcharter figure as an image, either save as html and
screenshot in a browser, or re-render with backend = "ggplot2" in
hd_make() and save as png.
file, invisibly.
Configures the default theme, colour palette, font, and optional JavaScript
plugins for all figures produced with hd_make() in the current R session.
Call once at the top of a script or in .Rprofile.
hd_set_theme( hc_theme = NULL, gg_theme = NULL, colors = NULL, font = NULL, js_plugins = NULL )hd_set_theme( hc_theme = NULL, gg_theme = NULL, colors = NULL, font = NULL, js_plugins = NULL )
hc_theme |
Character or |
gg_theme |
Character, ggplot2 theme object, or |
colors |
Character vector, palette name, or |
font |
Character or |
js_plugins |
Character vector or |
Per-figure overrides are provided via hd_opts(), which always take
precedence over these session defaults.
The previous option values invisibly; pass to options() to
restore.
hd_opts() for per-figure overrides
hd_set_theme(hc_theme = "economist", gg_theme = "classic", colors = c("#025169", "#7C145C", "#C68803")) # Reset hd_set_theme(hc_theme = "default", gg_theme = "minimal", colors = NULL)hd_set_theme(hc_theme = "economist", gg_theme = "classic", colors = c("#025169", "#7C145C", "#C68803")) # Reset hd_set_theme(hc_theme = "default", gg_theme = "minimal", colors = NULL)
Defines the data mapping for a figure - which columns map to x, y,
group, and count - independently of any visual presentation choices.
Pass the result to hd_make() together with an optional hd_opts()
object.
hd_spec(data, x, y, group = NULL, n = NULL, colour = NULL)hd_spec(data, x, y, group = NULL, n = NULL, colour = NULL)
data |
A |
x |
Character. Column name for the x-axis variable. |
y |
Character. Column name for the y-axis variable (typically a percentage or count). |
group |
Character or |
n |
Character or |
colour |
Character or |
An S3 object of class "hd_spec".
df <- data.frame( age = rep(c("18-24", "25-34", "35-44", "45-54"), each = 2), sex = rep(c("Male", "Female"), 4), pct = c(42, 38, 55, 61, 48, 52, 60, 57), n = c(120, 115, 200, 210, 180, 175, 160, 155) ) spec <- hd_spec(df, x = "age", y = "pct", group = "sex", n = "n") specdf <- data.frame( age = rep(c("18-24", "25-34", "35-44", "45-54"), each = 2), sex = rep(c("Male", "Female"), 4), pct = c(42, 38, 55, 61, 48, 52, 60, 57), n = c(120, 115, 200, 210, 180, 175, 160, 155) ) spec <- hd_spec(df, x = "age", y = "pct", group = "sex", n = "n") spec
Constructs a highcharter theme by merging a named base theme with colour
and font overrides from the current hd_set_theme() session defaults and
any per-figure opts.
hd_theme(name = NULL, colors = NULL, ...)hd_theme(name = NULL, colors = NULL, ...)
name |
Character or |
colors |
Character vector or |
... |
Named arguments forwarded to |
Called automatically inside the highcharter engine; useful when you want to apply a theme to a highchart built outside highdir.
A highcharter theme object (hc_theme).
if(interactive()) { t <- hd_theme("darkunica") highcharter::highchart() |> highcharter::hc_add_theme(t) }if(interactive()) { t <- hd_theme("darkunica") highcharter::highchart() |> highcharter::hc_add_theme(t) }
List Registered Backends
list_backends()list_backends()
Character vector of registered backend names.
List Registered Geometries
list_geoms()list_geoms()
Character vector of registered geometry names.
List Registered Palettes
list_palettes()list_palettes()
Character vector of registered palette names.
list_palettes()list_palettes()
Printing an hd() object triggers rendering. The geometry type and any
geometry-specific parameters are extracted from the stored hd_geom layer;
presentation options from the hd_opts layer; the backend from the
$backend slot. All of these are forwarded to hd_make(), which performs
the actual rendering via the registered engine.
## S3 method for class 'hd' print(x, ...)## S3 method for class 'hd' print(x, ...)
x |
An |
... |
Ignored; present for S3 consistency. |
You rarely need to call print.hd() directly since R calls it automatically
when the object appears at the top level, in knitr/Quarto chunks, or in
Shiny renderHighchart() / renderPlot() blocks.
The rendered output (a highchart widget or a ggplot object),
invisibly.
Register a Rendering Backend and used when loding in zzz.R file
register_backend(name, engine)register_backend(name, engine)
name |
Character. Unique backend identifier (e.g. |
engine |
Function. |
name, invisibly.
Adds a geometry to the registry. The optional_args field is the key
mechanism for user discoverability: it is what geom_args() prints, what
the Shiny app reads to build dynamic UI, and what automated documentation
can harvest without parsing source code.
register_geom( name, ggplot_fun = NULL, highcharter_fun = NULL, required_args = list(), optional_args = list(), is_map_geom = FALSE )register_geom( name, ggplot_fun = NULL, highcharter_fun = NULL, required_args = list(), optional_args = list(), is_map_geom = FALSE )
name |
Character. Unique geometry identifier. |
ggplot_fun |
Function or |
highcharter_fun |
Function or |
required_args |
Named list of |
optional_args |
Named list of |
is_map_geom |
Logical. Bypasses |
Structure of optional_args:
A named list where each element is itself a list with two fields:
default - the value used when the arg is not supplied (may be NULL)
desc - a short human-readable description (shown by geom_args())
Example:
optional_args = list( smooth = list(default = TRUE, desc = "Spline smoothing (logical)"), dot_size = list(default = 4, desc = "Marker radius in px (numeric)") )
name, invisibly.
Adds a named palette to the highdir palette registry so it can be
referenced by name wherever colours are accepted
(e.g. hd_opts(colors = "my_palette")). This function is evaluated
when loading a file in zzz.R file.
register_palette(name, colors)register_palette(name, colors)
name |
Character. Unique palette identifier. |
colors |
Non-empty character vector of CSS/hex colour strings. |
Built-in palettes registered at package load time:
| Name | Description |
"hdir" |
Helsedirektoratet 10-colour brand palette |
"hdir2" |
2-colour teal / purple pair |
name, invisibly.
register_palette("blues", c("#084594", "#2171b5", "#4292c6", "#6baed6")) get_palette("blues")register_palette("blues", c("#084594", "#2171b5", "#4292c6", "#6baed6")) get_palette("blues")