关于 r:更改由 ggfortify::autoplot 创建的 ggplot 的构面标签

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

我正在尝试更改 stl 分解图的分面标签,如下所示:

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

情节源自 ggfortify 包。
我希望将构面标签更改为:

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

我尝试进入一个ggplot的结构(很多str'ing),发现下面存储了这些名字:

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

但是,当我就地更改此因素时。我得到四个空图,然后是正确的图:

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

Outcome

如何更改构面标签而不使这些空白图位于顶部?


一种可能性是更改绘图对象的相关组件。

1
2
3
4
5
6
7
8
9
10
11
# 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