更改ggfortify :: autoplot创建的ggplot的facet标签

时间:2015-05-20 12:26:51

标签: r ggplot2 ggfortify

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

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

情节起源于ggfortify package。 我希望将facet标签更改为:

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

我试图进入ggplot(很多str&#39; ing)的结构,发现以下内容存储了这些名称:

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

然而,当我在原地改变这个因素时。我得到四个空图,然后是正确的图:

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

如何更改刻面标签而不在顶部显示这些空图?

1 个答案:

答案 0 :(得分:2)

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

# 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