I want to create and save a different graph for every column in a dataframe (df).
Background: my df is called final_fam_beliefs_percs Using R using ggplot
So far I have been able to create a graphing function using ggplot and used "lapply" to apply the function to each columneach column. See following code:
graph_outputs <- lapply(final_fam_beliefs_percs, function(i) ggplot(final_fam_beliefs_percs, aes(x=location, y=as.numeric(i), fill=response)) +
geom_bar(stat="identity", position=position_dodge()) +
geom_text(aes(label=i), position=position_dodge(width=0.9), vjust=-0.25) +
labs(x= "location", y="percentage"))
link for a above code graph output for one of the df columns
I would now like to save each graph as individual png files. I have tried the code below, however when my graphs print they no longer contain the data.
var_list= colnames(final_fam_beliefs_percs)
for (i in var_list) {
plots = ggplot(final_fam_beliefs_percs, aes(x=location, y=as.numeric(i), fill=response)) +
geom_bar(stat="identity", position=position_dodge()) +
geom_text(aes(label=i), position=position_dodge(width=0.9), vjust=-0.25) +
labs(x= "location", y="percentage") + ggtitle(i)
ggsave(plots, file=paste0("rr_",i,".png"))
}
I believe I need to change the y=as.numeric(i) statement, or use some other mapping method.
?aes_or?aes_string.aes()call withaes_string(x='location', y=i, fill='response')so that all arguments are character.ias a string only referring to the column name, is exactly whataes_stringis supposed to deal with. For what it's worth, you can also just includeggsavein yourlapplycall, if that is indeed working (although using vectors as straight input inaesis not generally recommended). The for loop should do the same as the lapply if you giveas.numeric(final_fam_beliefs_percs[[i]])instead ofas.numeric(i). (But, again,aes_stringoraes_are the proper ways to do this.)