【问题标题】:Flip order of data in grouped bar plot after coord_flipcoord_flip 后分组条形图中数据的翻转顺序
【发布时间】:2018-09-26 02:21:21
【问题描述】:

我遇到了一个烦人的问题,我无法找到具体的解决方案。我正在尝试创建一个水平分组条形图;我想要的只是获取标准的垂直条形图并将其向右旋转 90 度。当我使用 coord_flip 时,它会将绘图向右旋转,但会翻转(反转)每组 数据的顺序。这是一个例子:

library("ggplot2")

df <- data.frame(Group = c("A","A","A","B","B","B","C","C","C"),
                 Sub = c("1","2","3","1","2","3","1","2","3"),
                 Score = c(1,2,3,1,2,3,1,2,3))

df$Group <- factor(df$Group,
                       levels = c("A","B","C"),
                       labels = c("A","B","C"),
                       ordered = TRUE)

df$Sub <- factor(df$Sub,
                  levels = c("1","2","3"),
                  labels = c("1","2","3"),
                  ordered = TRUE)

ggplot(data = df, aes(x = Group, y = Score, fill = Sub)) +
  geom_bar(stat="identity", position=position_dodge()) +
  coord_flip() +
  scale_x_discrete(limits = rev(levels(df$Group)))

我可以使用以下方法按正确的顺序排列组:

scale_x_discrete(limits = rev(levels(df$Group)))

但是,我无法让每个组 的顺序正确。图例和数据是相反的,在这种情况下,我想改变绘制数据的顺序,而不是图例的顺序。

我发现您可以通过将条形图的位置闪避设置为 -.9 来解决此问题,如下所示:

geom_bar(stat="identity", position=position_dodge(-.9))

鉴于我的分组变量是字符串,我不确定here 提出的解决方案是否可行。

任何帮助将不胜感激!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    如果您熟悉 forcats 包,fct_rev() 非常方便在绘图时反转因子水平,并且可以在翻转坐标之前轻松反转图例顺序/颜色映射以匹配原始版本:

    library(forcats)
    library(ggplot2)
    
    # unflipped version
    p1 <- ggplot(data = df, 
           aes(x = Group, y = Score, fill = Sub)) +
      geom_col(position="dodge") #geom_col is equivalent to geom_bar(stat = "identity")
    
    # flipped version
    p2 <- ggplot(data = df, 
           aes(x = fct_rev(Group), y = Score, fill = fct_rev(Sub))) +
      geom_col(position="dodge") +
      coord_flip() +
      scale_fill_viridis_d(breaks = rev, direction = -1)
    
    gridExtra::grid.arrange(p1, p2, nrow = 1)
    

    【讨论】:

    • 这绝对有效!我必须做一些修改才能正确使用我的实际数据集。 “direction = -1”参数也非常有用。非常感谢!
    猜你喜欢
    • 2023-03-08
    • 2018-09-01
    • 1970-01-01
    • 2016-03-17
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    相关资源
    最近更新 更多