A family of small helpers that build Excel/Office number
format codes for common presentation needs (percentages, thousands /
millions / billions scaling, currency, plain numbers and scientific
notation). They return a plain character string suitable for the
num_fmt argument of chart_ax_x(), chart_ax_y() and
chart_data_labels().
The original mschart only accepted raw Excel format codes, which are
powerful but awkward to write by hand (see issue #98). These helpers
wrap the most common cases so that, for example, a "12,300,000" axis can
be shown as "12.3M" with fmt_millions(1).
Usage
fmt_number(decimals = 0, thousands = TRUE, negative_parens = FALSE)
fmt_percent(decimals = 0)
fmt_thousands(decimals = 0, suffix = "K")
fmt_millions(decimals = 0, suffix = "M")
fmt_billions(decimals = 0, suffix = "B")
fmt_currency(
symbol = "$",
decimals = 2,
thousands = TRUE,
symbol_after = FALSE,
negative_parens = FALSE
)
fmt_scientific(decimals = 2)Arguments
- decimals
number of decimal places to display. Default
0.- thousands
if
TRUE(default) group digits with a thousands separator (#,##0); ifFALSEuse a plain0integer group.- negative_parens
if
TRUE, render negative numbers in parentheses (accounting style) rather than with a minus sign. DefaultFALSE.- suffix
text appended after the (scaled) number. Provide your own unit label, or
NULLto omit it. Defaults are"K","M"and"B"forfmt_thousands(),fmt_millions()andfmt_billions().- symbol
currency symbol to place before the number, e.g.
"$","\u00a3","\u20ac". For locale-aware symbols you can pass an Excel currency token such as"[$\u20ac-407]".- symbol_after
if
TRUE, place the currencysymbolafter the number instead of before it. DefaultFALSE.
Details
Excel scales a number by 1000 for every trailing comma placed after the
integer part of a format code. fmt_thousands(), fmt_millions() and
fmt_billions() use one, two and three trailing commas respectively and
append a unit suffix, so the axis keeps showing compact numbers while the
underlying data stays unscaled.
Note that these helpers return format codes only; they do not modify a
chart. Pass the result to a num_fmt argument.
Examples
fmt_percent(1) # "0.0%"
#> [1] "0.0%"
fmt_thousands() # "#,##0,\"K\""
#> [1] "#,##0,\"K\""
fmt_millions(1) # "#,##0.0,,\"M\""
#> [1] "#,##0.0,,\"M\""
fmt_currency() # "$#,##0.00"
#> [1] "$#,##0.00"
fmt_number(2) # "#,##0.00"
#> [1] "#,##0.00"
library(officer)
lc <- ms_linechart(
data = data.frame(x = 1:3, y = c(1.2e6, 3.4e6, 2.1e6)),
x = "x", y = "y"
)
lc <- chart_ax_y(lc, num_fmt = fmt_millions(1))
