6

我想知道是否可以在 ggplot2 中创建一组类似的图形并以某种方式更改数据。例如,我可以创建一个函数来完成这个任务:

plot1 <- function(data) ggplot(data) + geom_line(aes(x,y)) + theme_bw()
plot1(data)
plot1(newdata)

但是有可能以这样的方式保存和重用一组组件吗?(显然这不起作用):

g <- geom_line(aes(x,y)) + theme_bw()
ggplot(data) + g
ggplot(newdata) + g
4

1 回答 1

14

here+.gg描述的方法

这些是 %+%并且%+replace% 将更新/替换ggplots 和中的元素themes

例如

p <- ggplot(mtcars, aes(x =wt, y = mpg,colour = hp)) + geom_point()

# change the variable mapped to y
p %+% aes(y = am)
# change the data set
p %+% mtcars[1:10,]

或者您可以将元素组合为列表

例如

#
g <- list(geom_line(aes(x,y)),theme_bw())
ggplot(data) + g
于 2013-05-24T03:45:02.553 回答