Skip to contents

Turn the category axis of a bar, line or area chart into a native multi-level category axis. Office renders the levels as stacked rows of labels (for example a "Quarter" row grouped underneath a "Year" row), with the outer levels visually merged across the categories they span.

This exposes the native c:multiLvlStrRef chart element. The original mschart package could not produce it (see the discussion in ardata-fr/mschart issues #75 and #103); the only workaround was to pre-format the category strings by hand.

Usage

chart_multilevel_axis(x, levels)

Arguments

x

an ms_chart object created with ms_barchart(), ms_linechart() or ms_areachart().

levels

a character vector of column names found in the chart's data, ordered from the outermost level to the innermost level. The innermost level (the last element) defines the primary categories and should correspond to the chart's x aesthetic. At least two columns are required.

Details

The category values are taken in the order in which the chart lays out its categories. For each category, the value of every level column is read from the chart data. Outer levels are emitted as merged spans: a label is written once at the first category of each run of identical values and is then visually spanned across the following categories. For this reason the data should be ordered so that each outer-level group is contiguous (this mirrors how Excel merges multi-level axis labels).

Multi-level axes only apply to charts with a category axis (ms_barchart(), ms_linechart(), ms_areachart()). They are not meaningful for value-axis charts such as scatter or bubble charts.

Examples

library(officer)

dat <- data.frame(
  year = rep(c("2023", "2024"), each = 4),
  quarter = rep(c("Q1", "Q2", "Q3", "Q4"), 2),
  sales = c(10, 12, 9, 14, 11, 13, 12, 16),
  stringsAsFactors = FALSE
)

bc <- ms_barchart(data = dat, x = "quarter", y = "sales")
bc <- chart_multilevel_axis(bc, levels = c("year", "quarter"))

doc <- read_pptx()
doc <- add_slide(doc, "Title and Content", "Office Theme")
doc <- ph_with(doc, bc, location = ph_location_fullsize())
print(doc, target = tempfile(fileext = ".pptx"))