Reputation:
The dataset I'm working with has about 300 variables. I would like to create a subset of variables(just in a list) and use that list to create and export a histogram for each variable with that variable name. I am using ggplot2.
So far I have:
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()
}
Right now it is creating the graph, but it's just a big box and doesn't seem to be reading the variable from the dataset (mydata)
Thanks for any help. I've seen some other posts similar, but haven't been able to work it out. Mark
Upvotes: 0
Views: 114
Reputation: 30983
Here is an annotated example that uses ggsave
and aes_string
. Its a little longer than your example but relatively straightforward to follow.
#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)
Upvotes: 0
Reputation:
Out of sheer dumb luck, this seems to be working. Is there a better way to do this?
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()
}
Upvotes: 1