在多个图中重用ggplot图层

时间:2013-09-11 16:58:13

标签: r ggplot2

我正在绘制大量基本上使用相同类型格式的图表。只是想知道是否可以将这些图层存储在变量中并重复使用它们。

方法1(不起作用)

t <- layer1() + layer2()
ggplot(df,aes(x,y)) + t

方法2(有效但不是很优雅)

t <- function(x) x + layer1() + layer2()
t(ggplot(df,aes(x,y))

有关方法1的任何建议吗?

谢谢!

3 个答案:

答案 0 :(得分:18)

在我等待澄清的同时,以下是一些示例,演示了如何将以前创建的图层添加到现有图中:

p <- ggplot(mtcars,aes(x = cyl,y = mpg)) + 
        geom_point()    
new_layer <- geom_point(data = mtcars,aes(x = cyl,y = hp),colour = "red")
new_layer1 <- geom_point(data = mtcars,aes(x = cyl,y = wt),colour = "blue")

p + new_layer

p + list(new_layer,new_layer1)

答案 1 :(得分:7)

基于Joran's answer,我现在将我的图层放入列表中,并将其添加到我的图中。像魅力一样:

r = data.frame(
  time=c(5,10,15,20),
  mean=c(10,20,30,40),
  sem=c(2,3,1,4),
  param1=c("A", "A", "B", "B"),
  param2=c("X", "Y", "X", "Y")
)
gglayers = list(
  geom_point(size=3),
  geom_errorbar(aes(ymin=mean-sem, ymax=mean+sem), width=.3),
  scale_x_continuous(breaks = c(0, 30, 60, 90, 120, 180, 240)),
  labs(
    x = "Time(minutes)",
    y = "Concentration"
  )
)
ggplot(data=r, aes(x=time, y=mean, colour=param1, shape=param1)) +
  gglayers +
  labs(
    color = "My param1\n",
    shape = "My param1\n"
  )
ggplot(data=r, aes(x=time, y=mean, colour=param2, shape=param2)) +
  gglayers +
  labs(
    color = "My param2\n",
    shape = "My param2\n"
  )

答案 2 :(得分:2)

我知道这是旧的,但这里有一个避免笨重的t(ggplot(...))

t<-function(...) ggplot(...) + layer1() + layer2()
t(df, aes(x, y))