[英]How to plot multiple categorical variables in R
My data set contains several categorical variables that I would like visualise to see the distribution. 我的数据集包含一些类别变量,我希望这些变量可以可视化以查看分布。
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: 例如,如果要可视化ggplot2的mpg数据集中的4个变量(制造商,trans,fl,class),则必须编写4行代码:
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()
Resulting barplot: 结果条形图:
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.
如果可能,我希望一次查看一张图表。
Your idea to use lapply
is one solution. 您使用
lapply
想法是一种解决方案。
This requires aes_string
to be used instead aes
. 这要求使用
aes_string
代替aes
。
Single plots 单一地块
This creates single plots per column (name) you supply as first argument to lapply
: 这
lapply
第一个参数提供的每列(名称)创建单个图:
lapply(c("manufacturer", "trans", "fl", "class"),
function(col) {
ggplot(mpg, aes_string(col)) + geom_bar() + coord_flip()
})
Combined plots 组合地块
If you require all plots on one plotting area, you can use miscset::ggplotGrid
: 如果需要在一个绘图区域上进行所有绘图,则可以使用
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()
}))
The result looks like: 结果看起来像:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.