标签乱序(ggplot2)

时间:2019-01-24 11:48:05

标签: r ggplot2 geom-text

当我将标签添加到绘图中时,它们的顺序错误。我想重新排列标签,而不是重新排列标签本身。示例代码:

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):

enter image description here

以不同方式重构数据不会更改标签。无论如何尝试,我都无法以正确的顺序获得它们。我假设geom_text存在问题,但我无法终生解决。

这是怎么回事?

1 个答案:

答案 0 :(得分:1)

这有帮助吗?假定(假设?)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)

图: enter image description here

相关问题