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

如何在ggplot2轴上重新排序类别

  •  0
  • Jenny  · 技术社区  · 2 年前

    我试着对它们重新排序,条形图显示了正确的顺序,但介质和光的标签没有切换以反映正确的顺序。

    df = data.frame(Group = c(rep('A',6), rep('B',6), rep('C',6)),
                   Status = c('0', '0', '0', '1', '1', '1', '0', '0', '0', '1', '1', '1','0', '0', '0', '1', '1', '1'),
                   Color = c('Dark','Light','Medium','Dark','Light','Medium','Dark','Light','Medium','Dark','Light','Medium','Dark','Light','Medium','Dark','Light','Medium'),
                   Count = c(3,6,9,3,4,1,5,2,7,3,4,8,5,3,7,6,2,6))
    
    df <- df %>% group_by(Group, Status) %>% dplyr::mutate(percent = round(Count*100/sum(Count), 1))
    
    
    ggplot(data = df, aes(x = Color, fill = Group, alpha= Status)) +
     scale_alpha_manual(values = c(1, 0.5)) +
     geom_bar(data=df[df$Status=="1",], aes(y=percent), stat="identity") +
     geom_bar(data=df[df$Status=="0",], aes(y=-percent), stat="identity") +
     scale_x_discrete(labels = df$Color) +
     coord_flip(ylim=c(-80,80)) +
     theme(text = element_text(size=16)) +
     scale_y_continuous(breaks=seq(-80,80,20),labels=abs(seq(-80,80,20))) + 
     scale_fill_brewer(palette="Set2") +
     facet_wrap(~Group, ncol=1) + theme(legend.position="right") +
     labs(y="Percentage", x="Colour", fill="Group", alpha = "Status") +
     theme_light()
    

    下面是生成的绘图:

    Plot

    我试着用一些方法重新排序类别,比如增加限制

    scale_x_discrete(labels = df$Color, limits = c("Dark", "Medium", "Light"))
    

    df$Color2 <- factor(df$Color, level = c('Dark', 'Medium', 'Light'))
    

    我得到的是图的表示方式,我希望他们被调平,但与标签媒体和轻,而不是被切换:

    Plot with inaccurate labels

    1 回复  |  直到 2 年前
        1
  •  0
  •   Adam Quek    2 年前

    这是你想要的吗?

    df$Color <- factor(df$Color, levels=c("Light", "Medium", "Dark"))
    
    ggplot(data = df, aes(x = Color, fill = Group, alpha= Status)) +
      scale_alpha_manual(values = c(1, 0.5)) +
      geom_bar(data=df[df$Status=="1",], aes(y=percent), stat="identity") +
      geom_bar(data=df[df$Status=="0",], aes(y=-percent), stat="identity") +
      #scale_x_discrete(labels = df$Color) +
      coord_flip(ylim=c(-80,80)) +
      theme(text = element_text(size=16)) +
      scale_y_continuous(breaks=seq(-80,80,20),labels=abs(seq(-80,80,20))) + 
      scale_fill_brewer(palette="Set2") +
      facet_wrap(~Group, ncol=1) + theme(legend.position="right") +
      labs(y="Percentage", x="Colour", fill="Group", alpha = "Status") +
      theme_light()
    

    enter image description here