【问题标题】:Labels are out of order (ggplot2)标签乱序(ggplot2)
【发布时间】:2019-06-18 03:33:19
【问题描述】:

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

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 的问题,但我终生无法弄清楚。

发生了什么事?

【问题讨论】:

  • 我在图片中没有看到这些数字。无论如何,您可以尝试将标签放入 data.frame 中吗?此外,您应该以不需要加载某些未知包的方式提供数据。
  • 抱歉,上传了错误的文件。现已修复,并已更新以接受 NelsonGon 的回答。

标签: r ggplot2 geom-text


【解决方案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)

剧情:

【讨论】:

  • 看起来将 label = df.labels 更改为 aes(label = df.labels) 就可以了。谢谢!
猜你喜欢
  • 2018-11-02
  • 1970-01-01
  • 2011-11-13
  • 1970-01-01
  • 1970-01-01
  • 2018-01-31
  • 2010-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多