【问题标题】:geom_text ignores position dodgegeom_text 忽略位置闪避
【发布时间】:2018-10-25 07:39:45
【问题描述】:

我正在尝试创建以下数据框的条形图:

df <- structure(list(HCT_range = c("Low", "Low", "Low", "Low", "Low", 
"Low"), HG1_range = c("High", "High", "Normal", "High", "High", 
"Normal"), HG2_range = c("High", "Normal", "High", "High", "Normal", 
"High"), n = c(17L, 54L, 66L, 15L, 61L, 60L), Type = c("LHH", 
"LHN", "LNH", "LHH", "LHN", "LNH"), File = c("a", "a", "a", "b", 
"b", "b"), Perc = c(0.0387, 0.123, 0.1503, 0.0342, 0.1389, 0.1366
 )), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))

我正在尝试使用以下命令创建一个闪避的条形图:

ggplot(data = df, aes(x = Type, y = n)) +
  geom_col(aes(fill = File), position = position_dodge(width = 0.9)) +
  geom_text(aes(label = Perc), position = position_dodge(0.9))

但由于某种原因,测试并没有被躲避而是堆叠 - 尽管有特定的位置调用。

有什么想法吗?

【问题讨论】:

  • group aes 添加到geom_textggplot,如帮助文本的几个示例 ?geom_text 中所述。在ggplot 中将fill = File 移动到aes 也可以。
  • 我添加了:ggplot(data = DF, aes(x = Type, y = n)) + geom_col(aes(fill = File), position = position_dodge(width = 0.9)) + geom_text (aes(label = Perc, group = 1), position = position_dodge(0.9)) - 它没有改变任何东西

标签: r ggplot2 geom-bar


【解决方案1】:

您只需要使用 fill 参数指定条形表示的内容。否则 ggplot 不知道在哪里放置文本。 这能解决您的问题吗?

ggplot(data = df, aes(x = Type, y = n, fill=File)) +
      geom_col(aes(fill = File), position = position_dodge(width = 0.9)) +
      geom_text(aes(label = Perc), position = position_dodge(0.9))

你也可以看看这个问题:Position geom_text on dodged barplot

【讨论】:

    猜你喜欢
    • 2011-08-26
    • 2016-01-09
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多