Adds a native 'Microsoft Office' trendline (regression / fit line) to one or more series of a bar, line or scatter chart. The trendline is computed and rendered by the host application (PowerPoint, Word or Excel), so it remains editable and updates when the underlying data changes.
This exposes the native c:trendline chart element and supports linear,
polynomial, exponential, logarithmic, power and moving-average fits,
optional forecasting, a fixed intercept, and display of the fit equation
and R-squared value.
Usage
chart_trendline(
x,
series = NULL,
type = c("linear", "poly", "exp", "log", "power", "movingAvg"),
order = 2,
period = 2,
forward = 0,
backward = 0,
intercept = NULL,
display_equation = FALSE,
display_r_squared = FALSE,
name = NULL,
line = NULL
)Arguments
- x
an
ms_chartobject created withms_barchart(),ms_linechart()orms_scatterchart().- series
character vector of series names the trendline should be added to. When
NULL(default), the trendline is added to every series.- type
the trendline type, one of
"linear","poly","exp","log","power"or"movingAvg".- order
polynomial order, an integer between 2 and 6. Only used when
type = "poly".- period
moving-average period, an integer of at least 2. Only used when
type = "movingAvg".- forward
number of periods (units) to forecast forward. Not used when
type = "movingAvg".- backward
number of periods (units) to forecast backward. Not used when
type = "movingAvg".- intercept
optional numeric value forcing the trendline to cross the y axis at a fixed point. Only valid for
"linear","poly"and"exp"trendlines. UseNULL(default) to let Office compute it.- display_equation
if
TRUE, display the fit equation on the chart. Not available for moving-average trendlines.- display_r_squared
if
TRUE, display the R-squared value on the chart. Not available for moving-average trendlines.- name
optional label for the trendline shown in the legend. When
NULL, Office generates a default name.- line
an
officer::fp_border()describing the trendline colour, width and dash style. WhenNULL, Office uses its default styling.
Examples
library(officer)
dat <- data.frame(
x = 1:20,
y = 2 * (1:20) + rnorm(20, sd = 3)
)
sc <- ms_scatterchart(data = dat, x = "x", y = "y")
sc <- chart_trendline(
sc,
type = "linear",
display_equation = TRUE,
display_r_squared = TRUE
)
