按降序排列两个变量条形图 [英] Arrange a two variable Bar Plot in Descending Order

查看:47
本文介绍了按降序排列两个变量条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按降序绘制带有两个变量的数据框.这两个变量都是因素.我想在绘图时考虑两个变量的频率,就像excel中的数据透视表一样.

I am trying to plot a data frame with two variables by descending order. Both variables are factors. I want to consider the frequency of both variables when plotting, just like a pivot table in excel.

我试图使用整洁的方式对变量进行降序分组,计数和排序.

I tried to use tidy to group, count, and sort order of the variables by descending order.

library(tidyverse)

# Create a data frame that simulates the data that needs to be modeled

#Create data frame that will hold data for simulation
df1 = as.data.frame(replicate(2, 
                              sample(c("A", "B", "C", "D", "E","F","G","H","I","J"), 
                                     50, 
                                     rep=TRUE)))

#Replace V2 column with System Nomenclature (Simulated)
df1$V2 <- sample(1:4, replace = TRUE, nrow(df1))

#Make V2 into a Factor
df1$V2 = as.factor(df1$V2)

#Create frequency table
df2 <- df1 %>% 
  group_by(V1, V2) %>%
  summarise(counts = n()) %>%
  ungroup() %>%
  arrange(desc(counts))

#Plot the 2 variable data
ggplot(df2, 
       aes(reorder(x = V1, -counts) , 
           y = counts, 
           fill = V2)) +
 geom_bar(stat = "identity")

我希望该图以V1的频率但以V2填充的降序排列数据.就像excel中的数据透视表功能一样.我也只想按V1的频率显示前5名,并用V2填充.

I expect to the graph to plot the data in descending order by the frequency of V1 but with the fill of V2. Just like the pivot table feature in excel. I also want to only display the Top-5 by frequency of V1 and fill with V2.

推荐答案

您可以使用fct_reorder和fct_rev来实现所需的目标

You can use fct_reorder and fct_rev to achieve what you want

#Create data frame that will hold data for simulation
df1 = as.data.frame(replicate(2, sample(c("A", "B", "C", "D", "E","F","G","H","I","J"), 50, rep=TRUE)))

#Replace V2 column with System Nomenclature (Simulated)
df1$V2 <- sample(1:4, replace = TRUE, nrow(df1))

#Make V2 into a Factor
df1$V2 = as.factor(df1$V2)

#Create frequency table
df2 <- df1 %>% group_by(V1, V2) %>%
    summarise(counts = n()) %>%
    ungroup() %>%
    arrange(desc(counts))

#Plot the 2 variable data.
##fct_reorder rearranges the factors, and fct_rev reverses the order, so it is descending[![enter image description here][1]][1]
ggplot(df2, aes(fct_rev(fct_reorder(V1, counts,fun = sum)) , y = counts, fill = V2)) +
    geom_bar(stat = "identity")

##Keeping only top 5
df2 %>% group_by(V1) %>%
filter(sum(counts) > 5) %>%
ggplot(aes(x = fct_rev(fct_reorder(V1,
                    counts,fun = sum)),
            y = counts, fill = V2)) +
geom_bar(stat = "identity")

这篇关于按降序排列两个变量条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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