简体   繁体   中英

using an apply function with ggplot2 to create bar plots for more than one variable in a data.frame

Is there a way to use an apply function in R in order to create barplots with ggplot2 ?

Say, we have a dataframe containing only factor variables out of which one is boolean. In my case I have a dateframe with +40 variables. Can one plot all the variables against the boolean one with a single line of code?

  data("diamonds")
factors <- sapply(diamonds, function(x) is.factor(x))
factors_only <- diamonds[,factors]
factors_only$binary <- sample(c(1, 0), length(factors_only), replace=TRUE)
factors_only$binary <- as.factor(factors_only$binary)

But I want to create barplots like this one:

qplot(factors_only$color, data=factors_only, geom="bar", fill=factors_only$binary)

This does not work:

  sapply(factors_only,function(x) qplot(x, data=factors_only, geom="bar", fill=binary))

Please advise

You can use lapply to run through the variable names and then use get to pull up the current variable.

temp <- lapply(names(factors_only),
               function(x) qplot(get(x), data=factors_only, geom="bar", fill=binary, xlab=x))

To print a list item,

print(temp[[1]])

will produce

在此处输入图片说明

A nice feature of running through the variable names is that you can use these to dynamically name the labels in the figure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM