如何在R中绘制多个类别变量 [英] How to plot multiple categorical variables in R
问题描述
我的数据集包含几个类别变量,我希望这些变量可以可视化以查看分布.
My data set contains several categorical variables that I would like visualise to see the distribution.
例如,如果我想可视化ggplot2的mpg数据集中的4个变量(制造商,trans,fl,class),我必须编写4行代码:
For example, if I wanted to visualise the 4 variables (manufacturer, trans, fl, class) in the mpg data set in ggplot2, I have to write 4 lines of code:
ggplot(mpg, aes(manufacturer)) + geom_bar() + coord_flip()
ggplot(mpg, aes(trans)) + geom_bar() + coord_flip()
ggplot(mpg, aes(fl)) + geom_bar() + coord_flip()
ggplot(mpg, aes(class)) + geom_bar() + coord_flip()
生成的条形图:
如何编写代码以更有效地执行此操作?环形?应用功能?如果可能的话,我希望一次查看一张图表.
How can I write a code to do this more efficiently? loop? apply function? I would like to see each chart one at a time, if possible.
推荐答案
您使用lapply
的想法是一种解决方案.
Your idea to use lapply
is one solution.
这要求使用aes_string
代替aes
.
单图
这将为您作为lapply
的第一个参数提供的每列(名称)创建单个图:
This creates single plots per column (name) you supply as first argument to lapply
:
lapply(c("manufacturer", "trans", "fl", "class"),
function(col) {
ggplot(mpg, aes_string(col)) + geom_bar() + coord_flip()
})
组合图
如果需要在一个绘图区域上进行所有绘图,则可以使用miscset::ggplotGrid
:
If you require all plots on one plotting area, you can use miscset::ggplotGrid
:
library(miscset) # install from CRAN if required
ggplotGrid(ncol = 2,
lapply(c("manufacturer", "trans", "fl", "class"),
function(col) {
ggplot(mpg, aes_string(col)) + geom_bar() + coord_flip()
}))
结果如下:
这篇关于如何在R中绘制多个类别变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!