[英]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
? 有没有一种方法可以在R中使用apply函数来用
ggplot2
创建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.
就我而言,我有一个包含+40个变量的日期框架。 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. 您可以使用
lapply
来遍历变量名,然后使用get
来get
当前变量。
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. 遍历变量名的一个不错的功能是,您可以使用它们来动态命名图中的标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.