【问题标题】:how to change the stacked bar chart using ggplot2 (percentage, sort) in R如何在R中使用ggplot2(百分比,排序)更改堆积条形图
【发布时间】:2021-10-22 07:32:44
【问题描述】:

我是 R 和 ggplot2 的新手。我有一个要使用堆积条形图可视化的数据集,其中

  • x 轴是分类变量(性别)
  • bar 由分类变量(天)组成
  • y 轴应该是百分位数。

示例..

total_bill tip sex smoker day time size
16.99 1.01 Female No Sun Dinner 2
10.34 1.66 Male No Sun Dinner 3
    data(tips, package='reshape2')
    
    ggplot(tips, aes(x=sex)) +
    geom_bar(aes(fill=day), width = 0.5, position = 'fill')+
    theme(axis.text.x = element_text(angle=65, vjust=0.6))

从这里开始,我想在图表中进行以下更改。

  1. 从图表中取出'Fri',但其他日子的百分比应保持不变。这意味着“周六、周日、周四”的百分比不会重新映射到 100%
  2. 按“周六”百分比的降序对“性别”进行排序。这意味着,如果“Male”在“Sat”中的百分比高于“Female”,则“Male”应该出现在左侧。

【问题讨论】:

    标签: r sorting ggplot2 stacked-chart


    【解决方案1】:
    library(tidyverse)
    
    data(tips, package='reshape2')
    
    tips %>% 
      #Calculating percentage by sex outside ggplot2
      count(sex,day) %>% 
      group_by(sex) %>% 
      mutate(p = 100*n/sum(n)) %>% 
      ungroup() %>%
      #Removing Friday 
      filter(day != "Fri") %>% 
      #Ordering sex by Saturday percentage
      mutate(
        sex = fct_reorder2(
        .f = sex,
        .x = p,
        .y = day,
        .fun = function(x,y) max(x[y == "Sat"])
          )
        ) %>% 
      ggplot(aes(x = sex, y = p)) +
      geom_col(aes(fill=day))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-16
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多