0

I'm try to make bar charts over a list of variables. I can get plots. But I want each plot has a title using its variable name, so that I can identify which variables are using in the plot. And the same thing for the legend.I tried the function as.character(), and as.name() to get their names. But they does no work. I don't know how to retrieve their variable names. The similar problems occurs in my second lappy function.My codes follow:

varlist1=c(name[11:40)
ev="aff"

lapply(varlist1, function(nm) 
{
     q1=ggplot(data,aes(fill=data[[as.name(nm)]],x=aff))
     q1+geom_bar(stat="count",position="dodge")+theme_bw()+
     ggtitle(as.character(data[[nm]]),"By Aff")
}) 

lapply(varlist1, function(nm) 
{
     table(data[[as.name(nm)]], data[[ev]])
 })

Thank you very much!!

  • This might help https://stackoverflow.com/a/49943976/786542 – Tung Apr 28 '18 at 20:41
  • If you want to do it using the `purrr` package's `map` functions, [this post](https://stackoverflow.com/questions/47482288/how-to-use-purrrpmap-to-plot-multiple-ggplot-in-nested-data-frame) might help – camille Apr 28 '18 at 20:43
  • There are fancy ways to do this, but it's generally a better idea to reshape your data to long form (e.g. with `tidyr::gather`) and use [`facet_wrap`](http://ggplot2.tidyverse.org/reference/facet_wrap.html). Also, [data will help you get a good answer](http://ggplot2.tidyverse.org/reference/facet_wrap.html). – alistaire Apr 28 '18 at 22:01
  • Thanks for the help. But I got error said :Error in typeof(x) : argument "varlist1" is missing, with no default. And my codes are `generate_plot2 <- function(registry, varlist1) { varlist1 <- rlang::sym(varlist1) ggplot(data = registry, aes(fill=!!varlist1, x=affiliation )) + geom_bar(stat="count",position="dodge")+theme_bw()+ ggtitle(varlist1) } lapply(registry, generate_plot2)` @Tung – Tong Zhang Apr 29 '18 at 17:55
  • @TongZhang: please share the data you're using for plotting. See this guide to learn how https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?rq=1 – Tung Apr 29 '18 at 18:19

0 Answers0