R语言 ggplot2:将文本定位在条形图的底部(使用position_dodge)

mnemlml8  于 2023-04-03  发布在  其他
关注(0)|答案(1)|浏览(139)

我有下面的数据。框架,我用它来绘制一个平均值的条形图。

library(tidyverse)

# Some sample data
n <- 100
df <- data.frame(grp = sample(c("A", "B", "C", "Total"), size = n, replace = TRUE),
                 value = runif(n = n, min = 1, max = 5),
                 item = sample(c("Item1", "Item2", "Item3"), size = n, replace = TRUE))

# Barplot
df %>% 
  group_by(item, grp) %>%
  summarise(n = n(),
            mean = mean(value)) %>%
  ungroup() %>%
  ggplot(aes(x = item, group = grp, y = mean, fill = grp)) +
    geom_col(position = 'dodge') +
    coord_flip() +
    geom_text(aes(label = round(mean, 2)), position = position_dodge(width=0.9), size = 4) +
    geom_text(aes(label = n), position = ??, size = 4)

另外,我想在条形图的底部(或者在左侧,因为坐标被翻转)添加案例的数量(每个条形图)。我必须使用geom_text()position-参数吗?

vaqhlq81

vaqhlq811#

你可以在你的美学中使用y = 0来在你的条形图的底部添加标签,像这样:

library(tidyverse)
df %>% 
  group_by(item, grp) %>%
  summarise(n = n(),
            mean = mean(value)) %>%
  ungroup() %>%
  ggplot(aes(x = item, group = grp, y = mean, fill = grp)) +
  geom_col(position = 'dodge') +
  coord_flip() +
  geom_text(aes(label = round(mean, 2)), position = position_dodge(width=0.9), size = 4) +
  geom_text(aes(label = n, y = 0), position = position_dodge(0.9),
            size = 4)
#> `summarise()` has grouped output by 'item'. You can override using the
#> `.groups` argument.

创建于2023-03-28带有reprex v2.0.2

相关问题