How to plot multiple categorical variables in R

为君一笑 提交于 2019-12-12 19:25:33

问题


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:

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.


回答1:


Your idea to use lapply is one solution.

This requires aes_string to be used instead aes.

Single plots

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

Combined plots

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

The result looks like:



来源:https://stackoverflow.com/questions/39242727/how-to-plot-multiple-categorical-variables-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!