提问人:jamborta 提问时间:9/12/2013 最后编辑:jamborta 更新时间:2/1/2018 访问量:4507
在多个图中重用 ggplot 图层
Reuse ggplot layers in multiple plots
问:
我正在绘制大量基本上使用相同类型格式的图表。只是想知道是否可以将这些层存储在变量中并重用它们。
方法 1(不起作用)
t <- layer1() + layer2()
ggplot(df,aes(x,y)) + t
方法 2(有效但不是很优雅)
t <- function(x) x + layer1() + layer2()
t(ggplot(df,aes(x,y))
对方法1有什么建议吗?
谢谢!
答:
23赞
joran
9/12/2013
#1
在我等待澄清的同时,这里有一些示例演示了如何将以前创建的图层添加到现有绘图中:
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)
4赞
user3763801
12/14/2016
#2
我知道这很旧,但这里有一个避免笨拙的 t(ggplot(...)))
t<-function(...) ggplot(...) + layer1() + layer2()
t(df, aes(x, y))
20赞
Dan Chaltiel
6/23/2017
#3
根据 Joran 的回答,我现在将我的图层放入一个列表中,并将其添加到我的绘图中。像魅力一样工作:
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"
)
评论
3赞
jimjamslam
8/9/2017
这个答案对我来说是赢家,因为我不需要指定数据源(这意味着我可以回收一堆结构相似的数据帧的图层)
评论
layer1()
layer2()
geom_*
t()
scale_*
theme()