我正在绘制大量使用相同格式的图表。只是想知道是否可以将这些层存储在一个变量中并重用它们。
方法1(不起作用)
t <- layer1() + layer2()
ggplot(df,aes(x,y)) + t
方法2(有效但不是很优雅)
t <- function(x) x + layer1() + layer2()
t(ggplot(df,aes(x,y))
与方法 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)
根据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"
)
我知道这是旧的,但这是一个避免笨重的 t(ggplot(...)))
t<-function(...) ggplot(...) + layer1() + layer2()
t(df, aes(x, y))