【问题标题】:Reordering categories in stacked bar chart based on count根据计数对堆积条形图中的类别重新排序
【发布时间】:2018-10-22 21:22:56
【问题描述】:

我想在 ggplot2 中生成一个堆积条形图,其中堆栈中的条形图根据该类别的计数进行排序。当我使用以下代码尝试此操作时,似乎 ggplot2 根据字母顺序排列堆叠图中的条形顺序。 Stackoverflow 上的其他答案表明 ggplot2 根据 R 使用数据的顺序对条形图进行排序,但是在“a”数据框中,设备列的顺序为“收音机”、“笔记本电脑”、“电视”“冰箱” '(前 4 行),这也不是图表中的显示方式。

 library(ggplot2)
 library(tidyr)

 #some data 
 SalesData<-data.frame(Appliance=c("Radio", "Laptop", "TV", "Fridge"), ThisYear=c(5,25,5,8), LastYear=c(6,20,5,8))

 #transform the data into 'long format' for ggplot2
 a<- gather(SalesData, Sales, Total, ThisYear, LastYear)

 #Produce the bar chart
 p<-ggplot(a, aes(fill=Appliance, y=Total, x=Sales)) + 
 geom_bar( stat="identity")
 p

我希望最大的计数位于图表的底部,因此我需要一种以这种方式对数据进行排序的方法。因此,在本例中,底部是“笔记本电脑”,然后是“冰箱”、“收音机”和“电视”,图例与此顺序相匹配。

有人有什么建议吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    在绘制堆积条形图之前,您需要重新排序因子水平。为此,有几种可能:

    以 R 为基数

    order_appliance <- unique(a$Appliance[order(a$Total)])
    a$Appliance <- factor(a$Appliance, levels = order_appliance)
    

    使用 dplyr

    library(dplyr)
    a <- a %>% 
      arrange(Total) %>% 
      mutate(Appliance = factor(Appliance, levels = unique(Appliance)))
    

    用forcats

    library(forcats)
    a$Appliance <- fct_reorder(a$Appliance, a$Total)
    
    For the plot you can use `geom_col` instead of `geom_bar(stat = "identity")`: 
    
    ggplot(a, aes(fill = Appliance, y = Total, x = Sales)) +
      geom_col()
    

    【讨论】:

      【解决方案2】:

      Geom_bar 使用因子来创建堆栈。您可以使用factor(a$Appliance) 查看数据中存在的级别。默认情况下,这些级别按字母顺序排序。但是,您可以手动设置级别的顺序,如下所示:

      a$Appliance = factor(a$Appliance, levels=c("TV", "Radio", "Fridge", "Laptop"))
      

      如果您在创建 ggplot 之前执行此操作,您将获得所需的顺序。

      【讨论】:

        【解决方案3】:

        我们可以根据总和重新排序因子,然后绘图,参见示例:

        # reorder labels based on row sums
        myFac <- SalesData$Appliance[ order(rowSums(SalesData[, 2:3])) ]
        
        # wide-to-long, then reorder factor
        a <- gather(SalesData, Sales, Total, ThisYear, LastYear) %>% 
          mutate(Appliance = factor(Appliance, labels = myFac, levels = myFac ))
        
        # then plot
        ggplot(a, aes(fill = Appliance, y = Total, x = Sales)) + 
          geom_bar(stat = "identity")
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-07
        • 2022-07-07
        相关资源
        最近更新 更多