如何在R中以降序绘制每列 [英] How to Plot Every Column in Descending Order in R

查看:220
本文介绍了如何在R中以降序绘制每列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算按降序排列数据框中的每个分类列,取决于变量中的层级频率。

我已经找到了如何绘制每列并重新排列级别的方法,但我无法弄清楚如何将它们组合在一起。你能给我一些建议吗?



代码绘制每一列:

  require(purrr)
图书馆(tidyr)
图书馆(ggplot2)


钻石%>%
保留(is.factor)%>%
gather()%>%
ggplot(aes(value))+
facet_wrap(〜key,scales =free)+
geom_bar()


$ p

对一个变量的级别进行重新排序的代码:

 因子(x,levels = names(tb [order(tb,decrease = TRUE)]))
pre>

顺便说一句,如果你觉得写这些代码有更好的方法,请告诉我。
Thanks。

解决方案

替代方案1

$ b

不需要使用 gridExtra 来模拟 facet_wrap ,只需包含函数在$ aes 里面的reorder_size
$ b

  reorder_size< ;函数(x){
factor(x,levels = names(sort(table(x),decrease = TRUE)))
}

diamonds%>%
keep(is.factor)%>%
gather()%>%
ggplot(aes(x = reorder_size(value)))+
facet_wrap(〜key ,scale =free)+
geom_bar()

/ strong>



使用 dplyr 按键和值计算计数分组。然后我们按照 aes 中的计数降序排列值 reorder

  library(dplyr)
diamonds%>%
keep(is.factor)%>%
gather()%> %
group_by(key,value)%>%
汇总(n = n())%>%
ggplot(aes(x = reorder(value,-n),y = n))+
facet_wrap(〜key,scales =free)+
geom_bar(stat ='identity')

输出


I intend to plot every categorical column in the dataframe in a descending order depends on the frequency of levels in a variable.

I have already found out how to plot every column and reorder the levels, but I cannot figure out how to combine them together. Could you please give me some suggestions?

Code for plot every column:

require(purrr)
library(tidyr)
library(ggplot2)


diamonds %>% 
  keep(is.factor) %>%
  gather() %>%
  ggplot(aes(value)) +
  facet_wrap(~ key, scales = "free") +
  geom_bar()  

Code for reorder the levels of one variable:

tb <- table(x)
factor(x, levels = names(tb[order(tb, decreasing = TRUE)]))

BTW, if you feel there is a better way writing these codes, please let me know. Thanks.

解决方案

Alternative 1

No need to use gridExtra to emulate facet_wrap, just include the function reorder_size inside aes:

reorder_size <- function(x) {
  factor(x, levels = names(sort(table(x), decreasing = TRUE)))
}

diamonds %>% 
  keep(is.factor) %>%
  gather() %>%
  ggplot(aes(x = reorder_size(value))) +
  facet_wrap(~ key, scales = "free") +
  geom_bar()  

Alternative 2

Using dplyrto calculate the count grouping by key and value. Then we reorder the value in descending order by count inside aes.

library(dplyr)
diamonds %>% 
  keep(is.factor) %>%
  gather() %>%
  group_by(key,value) %>% 
  summarise(n = n()) %>% 
  ggplot(aes(x = reorder(value, -n), y = n)) +
  facet_wrap(~ key, scales = "free") +
  geom_bar(stat='identity') 

Output

这篇关于如何在R中以降序绘制每列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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