问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/41895513/using-an-apply-function-with-ggplot2-to-create-bar-plots-for-more-than-one-varia