代码之家  ›  专栏  ›  技术社区  ›  Laura

根据R中另一个变量的“是”值,按比例对ggplot中的柱状图排序

  •  0
  • Laura  · 技术社区  · 7 年前

    我有像这样的数据

    df <- data.frame (
    cancer = c(1, 0, 1, 0, 0, 1, 0, 0, 0, 0),
    CVD =    c(0, 1, 1, 0, 1, 0, 0, 0, 0, 0),
    diab =   c(0, 0, 0, 1, 0, 1, 0, 0, 1, 0),
    stroke = c(0, 1, 1, 0, 1, 0, 0, 0, 1, 0),
    asthma = c(1, 1, 1, 0, 1, 1, 0, 0, 0, 0),
    SR_hlt = c(1, 2, 2, 2, 1, 1, 2, 2, 2, 1))
    

    我要做的是制作一个条形图,只为有兴趣疾病的人制作,其中条形图的条形图是按照sr_hlt==1的比例排序的。

    为了绘制这个图,我使用以下代码

    1)收集数据

    df_grp <- df %>%
    gather(key = condition, value = Y_N, -SR_hlt) %>%
    group_by(condition, Y_N, SR_hlt) %>%
    summarise(count = n()) %>%
    mutate(freq = round(count/sum(count) * 100, digits = 1))
    

    2)绘制此数据

    df_plot <- df_grp  %>%
    filter(Y_N == 1) %>%
    ggplot(aes(x = reorder(condition, -freq), y = freq, fill = factor(SR_hlt)), width=0.5) +
    geom_bar(stat="identity", position = position_dodge(0.9))
    df_plot
    

    这个 x = reorder(condition, -freq) 应该是命令条的东西,但我认为在这种情况下不起作用,因为freq值依赖于第三个变量sr_hlt的值。是否可以按以下值订购钢筋 freq 当sr_hlt的值=1?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Dave Gruenewald    7 年前

    这可以通过使用方便的软件包来完成。 forcats ,具体地说 fct_reorder2

    df_plot <- df_grp  %>%
      filter(Y_N == 1) %>%
      ggplot(aes(x = fct_reorder2(condition, SR_hlt, -freq), 
                 y = freq, fill = factor(SR_hlt)), width=0.5) +
      geom_bar(stat="identity", position = position_dodge(0.9))
    df_plot
    

    这就是设定 condition 作为一个因素, SR_hlt == 1 有兴趣,我们从低到高安排 SR_hlt 紧随其后 -freq 或从高到低 freq .


    或者,可以在 ggplot 使用标准呼叫 dplyr 只有:

    df_plot <- df_grp  %>%
      ungroup() %>% 
      filter(Y_N == 1) %>%
      arrange(SR_hlt, desc(freq)) %>% 
      mutate(condition = factor(condition, unique(condition))) %>% 
      ggplot(aes(x = condition, y = freq, fill = factor(SR_hlt)), width=0.5) +
      geom_bar(stat="identity", position = position_dodge(0.9))
    df_plot
    

    在上面,我使用 arrange 对数据帧进行最高排序 弗雷克 对于 SRH-HLT . 接下来,我使用 mutate 通过分解利用已排序的数据帧 条件 按外观顺序排列。