2015-07-11 74 views
0

我正在使用的數據集有大約300個變量。我想創建一個變量的子集(只是在一個列表中),並使用該列表爲每個變量創建和導出一個直方圖並使用該變量名稱。我正在使用ggplot2。導出通過循環變量列表創建的一系列圖(在R中)

到目前爲止,我有:

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)

謝謝你的幫助。我見過其他一些類似的帖子,但一直未能解決。 馬克

+0

對於'ggplot'圖,使用'ggsave'而不是'jpeg'。參見示例[here](http://docs.ggplot2.org/0.9.2.1/ggsave.html) – LyzandeR

+0

在'qplot()'中使用'get(variables [i])'而不是'variables [i]' 。 – christoph

+0

謝謝!那是我需要的。 – mch

回答

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() 
} 
0

下面是一個使用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)