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.

scartar
  • 21
  • 2
  • 1
    I think you are looking for `?aes_` or `?aes_string`. – Axeman Mar 04 '19 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. – qdread Mar 04 '19 at 18:29
  • Sorry, but this is still not working. – scartar Mar 04 '19 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 – scartar Mar 04 '19 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.) – Axeman Mar 04 '19 at 19:13
  • @scartar: https://stackoverflow.com/a/50522928/786542 & https://stackoverflow.com/a/52045111/786542 & https://stackoverflow.com/a/52902877/786542 – Tung Mar 04 '19 at 19:24
  • Thank you!! The as.numeric(df [ [ i ] ] ) worked!! I kept trying to grab it as either df$i or df [ i ] but was missing the extra set of brackets. – scartar Mar 04 '19 at 19:30

0 Answers0