Change facet labels for a ggplot created by ggfortify::autoplot

1.8k Views Asked by At

I'm trying to change the facet labels for an stl decomposition plot like the following:

library(ggplot2)
library(ggfortify)
p <- autoplot(stl(AirPassengers, s.window = 'periodic'), ts.colour = "black", ts.size = 0.2)
p

The plot originates from the ggfortify package. I wish to change the facet labels to:

c("Original Data", "Seasonal component", "Trend component", "Remainder")

I've tried to get into the structure of a ggplot (a lot of str'ing), and found that the following stores these names:

str(p$layers[[1]]$data$variable)
# Factor w/ 4 levels "Data","seasonal",..: 1 1 1

However, when I change this factor in-place. I get four empty plots followed by the proper plots:

p$layers[[1]]$data$variable <- factor(p$layers[[1]]$data$variable,
                                      labels=c("Original series", "Seasonal Component", "Trend component", "Remainder"))    

Outcome when editing factor in-place

How do I change the facet labels without getting these empty plots at the top?

1

There are 1 best solutions below

1
On BEST ANSWER

One possibility is to change the relevant components of the plot object.

# generate plot data which can be rendered
g <- ggplot_build(p)

# inspect the object and find the relevant element to be changed
# str(g)

# perform desired changes
g$panel$layout$variable <- c("Original Data", "Seasonal component", "Trend component", "Remainder")

# build a grob and 'draw' it
grid.draw(ggplot_gtable(g))

enter image description here