0

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.

7
  • 1
    I think you are looking for ?aes_ or ?aes_string. Commented Mar 4, 2019 at 18:28
  • @Axeman is correct. You would replace your aes() call with aes_string(x='location', y=i, fill='response') so that all arguments are character. Commented Mar 4, 2019 at 18:29
  • Sorry, but this is still not working. Commented Mar 4, 2019 at 18:49
  • I start by creating a list of the column names.... i represents each column name... y=i is only grabbing the column name but not the actual data in the column name Commented Mar 4, 2019 at 18:50
  • Well, we can't reproduce this, so it's very hard to help. The problem you are describing, i as a string only referring to the column name, is exactly what aes_string is supposed to deal with. For what it's worth, you can also just include ggsave in your lapply call, if that is indeed working (although using vectors as straight input in aes is not generally recommended). The for loop should do the same as the lapply if you give as.numeric(final_fam_beliefs_percs[[i]]) instead of as.numeric(i). (But, again, aes_string or aes_ are the proper ways to do this.) Commented Mar 4, 2019 at 19:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.