【问题标题】:create a function that generate plots from a data创建一个从数据生成图的函数
【发布时间】:2018-05-28 00:08:31
【问题描述】:

我有一个包含 8 个变量(x1、y1、x2、y2、x3、y3、x4、y4)的数据,我应该执行一个函数来生成 4 个图 x1vsy1、x2vsy2、x3vsy3 和 x4vsy4。

所以我试图一个一个地做到这一点,用变量做一个新数据,然后生成de plot。

minidata<-select(alldata,x1,y1)
ggplot(minidata,aes(x1,y1))+geom_point()+ggtitle("m VS n")

这可行,但是当我尝试将其放入函数中时

graph<-function(m,n){
 minidata<-select(alldata,m,n)
  ggplot(minidata,aes(x=m,y=n))+geom_point()+ggtitle("m VS n")
}
graph(y1,x1)

这不起作用说“FUN中的错误(X [[i]],...):找不到对象'y1'” 我能做些什么来生成一个创建 4 个图的函数?

【问题讨论】:

标签: r gplots


【解决方案1】:

有很多方法可以做到这一点。一种方法是:

minidata <- data.frame( x1 = 1:20,
                        y1 = rnorm(20), 
                        x2 = 1:20,
                        y2 = runif(20))


myGraph <- function( df, x, y ){

  mdf <- df[ ,c(x,y)]
  names(mdf) <- c("x","y")
  ggplot(mdf,aes(x=x,y=y))+geom_point() + ggtitle(paste(y,"~",x)) + labs (x =x, y = y)
}

# call function by passing names of the column using names() function
myGraph (minidata, names(minidata)[1], names(minidata)[2])

# or simply giving a name
myGraph (minidata, "x2", "y2")

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 2013-09-25
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2020-10-13
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多