首页 > 解决方案 > 标签乱序(ggplot2)

问题描述

当我在情节中添加标签时,它们的顺序错误。我想重新排列标签,而不是条形本身。示例代码:

df = data.frame(A = c("Apples", "Apples", "Apples", "Apples", "Apples", "Apples",
                      "Oranges", "Oranges", "Oranges", "Oranges", "Oranges", "Oranges"),
                B = c("Red", "Green", "Red", "Green", "Red", "Green",
                      "Red", "Green", "Red", "Green", "Red", "Green"),
                C = c(3, 4, 2, 3, 4, 6, 2, 2, 3, 8, 8, 6))

library(tidyverse)

df.summary = df %>%
  group_by(A, B) %>%
  summarise(new = list(mean_se(C))) %>%
  unnest(new)
df.summary$B <- factor(df.summary$B, levels = c("Red", "Green"))

df.labels = c(1, 2, 3, 4)

ggplot(df.summary, aes(x = A, y = y, fill = factor(B))) +
  geom_bar(stat = "identity", position = position_dodge(.95)) +
  geom_errorbar(aes(ymin = ymin, ymax = ymax, width = 0.5), 
                position = position_dodge(.95)) +
  geom_text(position = position_dodge(width = 1), size = 6, 
            label = df.labels, hjust = .5, vjust = 0, angle = 0)

我们得到:

标签顺序不正确的条形图(2-1-4-3 而不是 1-2-3-4):

在此处输入图像描述

以不同方式重构数据不会改变标签。无论我尝试什么,我都无法按正确的顺序排列它们。我假设这是一个问题,geom_text但我一生都无法弄清楚。

这是怎么回事?

标签: rggplot2geom-text

解决方案


这有帮助吗?假定(假设?)A 和 B 是因子。

 library(tidyverse)
    df.summary$A<-fct_reorder(df.summary$A,df.labels)
    df.summary$B<-fct_reorder(df.summary$B,df.labels)
    ggplot(df.summary, aes(x=A, y=y, fill=B))+
      geom_bar(stat = "identity", position = position_dodge(.95))+
      geom_errorbar(aes(ymin=ymin, ymax=ymax, width=0.5), position=position_dodge(.95))+
      geom_text(position = position_dodge(width = 1), size = 6, aes(label = df.labels),
                hjust = .5, vjust = 0, angle = 0)

阴谋: 在此处输入图像描述


推荐阅读