2

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?

Henrik
  • 65,555
  • 14
  • 143
  • 159
MattV
  • 1,353
  • 18
  • 42
  • You will have to dig into the attributes of `x$time.series` and I think `Data` is semi-hard coded (see for example https://github.com/sinhrks/ggfortify/blob/fea0b6f54ed814583d9a53f4815ecc65265f5d3c/R/base_fortify_ts.R). – Roman Luštrik May 20 '15 at 13:07

1 Answers1

3

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

Henrik
  • 65,555
  • 14
  • 143
  • 159
  • This is great. I just had an issue with ggsave not liking the draw.table part. Loading gridExtra and modifying ggsave as described in http://stackoverflow.com/a/18407452/3191230 completely solved it. Thanks alot! – MattV May 22 '15 at 09:03