R -GGPLOT2:每层传递新数据参数以减少代码冗余



当我在一个需要许多类似地块的项目中工作时,我发现自己重写了非常相似的ggplot2编码行,并进行了较小的调整。由于很多重复通常意味着我在做错事(并且很烦人和错误的错误(,因此我正在寻找更明智的工作流程,以与ggplot2一起使用。

绘图之间相同的层可以保存到变量中,并通过此变量调用:

library(ggplot2)
myPoints <- geom_point(data = mtcars, aes(disp,mpg, size = qsec, colour = cyl))
ggplot() +
  myPoints 

但是,如果我想用包含相同柱状的不同数据集重新创建相同的图怎么办?如果我使用一个数据集,这将很简单(在初始的ggplot() -command中调用(。但是我至少有两个数据集,并希望使用相同的样式重新创建相同的图,但只需切换输入数据。

# Creating a second dataset for the plot:
rectangle <- data.frame(minx= c(100,200),maxx= c(150,300),miny= c(15,30),maxy= c(18,32))
# Saving it to a layer:
myRectangles <- geom_rect(data = rectangle,aes(xmin=minx,xmax=maxx,ymin=miny,ymax=maxy))
# This creates my first plot with all data
ggplot() +
  myPoints +
  myRectangles

现在我将创建一些新数据:

mtcars_new <- mtcars[1:16,]
rectangle_new <- data.frame(xmin = c(100,200),xmax = c(150,300),ymin = c(15,30),ymax = c(18,32))

我现在想通过简单地将新数据集传递到以下几行来重新创建第一个图:

  ggplot() +
    myPoints +   # <- pass "mtcars_new" to this layer
    myRectangles # <- pass "rectangle_new" to this layer

我希望我能阐明我的目标是什么,我对这个例子进行了很多思考。

使用功能语言时通常是解决方案,使用函数!

myPoints <- function(data)
    geom_point(data = data, aes(disp,mpg, size = qsec, colour = cyl))
myRectangles <- function(data) 
    geom_rect(data = data, aes(xmin=minx,xmax=maxx,ymin=miny,ymax=maxy))
ggplot() +
  myPoints(mtcars) +
  myRectangles(rectangle)
ggplot() +
  myPoints(mtcars_new) +
  myRectangles(rectangle_new)

您还可以为对象分配美学并重复使用它们

aes_point <- aes(disp,mpg, size = qsec, colour = cyl)
aes_rect <- aes(xmin=minx, xmax=maxx, ymin=miny, ymax=maxy)
ggplot() +
  geom_point(aes_point, data=mtcars) +
  geom_rect(aes_rect, data=rectangle)

我认为最简单的解决方案是创建绘图函数。线上的东西:

myplot_fun <- function(my_data_points, my_data_rect){
   p <- ggplot()
   p <- p + geom_point(data = my_data_points, aes(......), .....)
   p <- p + geom_rect(data = my_data_rect, aes(......), .....)
   print(p)  # if you want to immediately plot, and not "store" 
   return(p) # if you want to "store" the plot for later use
 }

然后,您可以使用主脚本或控制台的任何数据来调用它:

p1 <- myplot_fun(mydata_point1, mydata_rec1)
....
....
p2 <- myplot_fun(mydata_point1, mydata_rec2) 

hth!

最新更新