【问题标题】:Export a series of plots created by looping through a list of variables (in R)导出通过循环变量列表创建的一系列图(在 R 中)
【发布时间】:2015-07-11 18:43:04
【问题描述】:

我正在使用的数据集有大约 300 个变量。我想创建一个变量子集(只是在一个列表中)并使用该列表为具有该变量名的每个变量创建和导出一个直方图。我正在使用 ggplot2。

到目前为止,我有:

variables = c("race","gender") #my list of variables to be used

for(i in 1:2){
#creates the name for the plot
  jpeg(file=paste("myplot_", variables[i], ".jpg", sep="")) 
#creates and saves the plot 
  print(qplot(variables[i], data=mydata, geom = "histogram"))
  dev.off()
}

现在它正在创建图表,但它只是一个大盒子,似乎没有从数据集(mydata)中读取变量

感谢您的帮助。我看过其他一些类似的帖子,但一直无法解决。 标记

【问题讨论】:

  • 对于ggplot 绘图使用ggsave 而不是jpeg。查看示例here
  • qplot() 中使用get(variables[i]) 而不仅仅是variables[i]
  • 谢谢!这正是我所需要的。

标签: r loops ggplot2


【解决方案1】:

纯粹出于愚蠢的运气,这似乎有效。有没有更好的方法来做到这一点?

variables = c("race","gender")

for(Var in variables){
  jpeg(file=paste("myplot_", Var, ".jpg", sep=""))
  print(qplot(mydata[,Var], data=mydata, geom = "histogram"))
  dev.off()
}

【讨论】:

    【解决方案2】:

    这是一个使用ggsaveaes_string 的带注释示例。它比您的示例长一点,但相对简单易懂。

     #load ggplot
     library(ggplot2)
    
     #make some data
     df <- data.frame(race=c(1,2,3),
                      gender=c(4,5,6), 
                      country=c("USA","Canada","Mexico"))
    
    # write a function to make a plot
    # note the ggsave and aes_string functions 
    makeplot <- function(df,name){
         title <- paste0("myplot_",name,".jpg")
         p     <- ggplot(data= df,aes_string(x=name)) + 
                    geom_histogram()
         ggsave(p, file=title)
     }
    
     # make your vector of column headings
     varlist = c('race','gender')
    
     # run your function on each column heading
     for (var in varlist) makeplot(df,var)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 2020-07-16
      相关资源
      最近更新 更多