使用ggplot2的apply函数为data.frame中的多个变量创建条形图 [英] using an apply function with ggplot2 to create bar plots for more than one variable in a data.frame

查看:63
本文介绍了使用ggplot2的apply函数为data.frame中的多个变量创建条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在R中使用apply函数,以便使用 ggplot2 创建条形图?

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

说,我们有一个仅包含因子变量的数据框,其中一个是布尔值.就我而言,我有一个带有+40个变量的日期框架.可以用一行代码将所有变量与布尔值相对应吗?

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)

这不起作用:

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

请告知

推荐答案

您可以使用 lapply 遍历变量名,然后使用 get 提取当前变量变量.

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))

要打印列表项,

print(temp[[1]])

会产生

遍历变量名的一个不错的功能是,您可以使用它们来动态命名图中的标签.

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

这篇关于使用ggplot2的apply函数为data.frame中的多个变量创建条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆