首页 > 解决方案 > ggplot:geom_text 不在 geom_col 上方打印

问题描述

我已经看到了很多关于如何在条形上方自动打印文本项的主题。但是,我无法弄清楚为什么这不起作用。

我有

在此处输入图像描述

p %>% 
  as_tibble() %>% 
  mutate(nystudie=as.character(nystudie),
         n.stage=as.factor(n.stage)) %>% 
  bind_rows(., mutate(., nystudie="all")) %>% 
  count(nystudie, n.stage) 

作为

# A tibble: 13 x 3
   nystudie n.stage     n
   <chr>    <fct>   <int>
 1 A        0           4
 2 A        2           4
 3 A        3           1
 4 all      0          22

我想nn.stage每个nystudie.

所以这给出了条形图

  ggplot(aes(nystudie, n, color = n.stage, fill= n.stage, label=n)) +
  geom_col(position = position_dodge2(preserve = "single", padding = 0.1))

但添加

+ geom_text(vjust=0)

产生错误:

映射必须由 aes() 创建

为什么会这样,我怎样才能geom_text打印aes(label=n)

p <- structure(list(nystudie = c("B", "B", "B", "B", "B", "B", "B", 
"B", "B", "B", "B", "B", "A", "A", "B", "B", "B", "B", "B", "B", 
"B", "B", "A", "B", "B", "A", "B", "A", "A", "A", "B", "B", "B", 
"B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", 
"B", "B", "B", "B"), n.stage = structure(c(3L, 5L, 1L, 1L, 1L, 
1L, 5L, 4L, 3L, 2L, 3L, 4L, 1L, 3L, 3L, 1L, 3L, 1L, 2L, 2L, 1L, 
4L, 2L, 1L, 2L, 4L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 4L, 1L, 2L, 1L, 
4L, 4L, 1L, 1L, 5L, 1L, 1L, 2L, 4L, 1L, 4L, 1L, 2L), .Label = c("0", 
"1", "2", "3", "4"), class = "factor")), row.names = c(NA, -50L
), class = "data.frame")

标签: rggplot2plotbar-chart

解决方案


也许你正在寻找这个:

library(tidyverse)
#Data and plot
p %>% 
  as_tibble() %>% 
  mutate(nystudie=as.character(nystudie),
         n.stage=as.factor(n.stage)) %>% 
  bind_rows(., mutate(., nystudie="all")) %>% 
  count(nystudie, n.stage) %>%
  ggplot(aes(nystudie, n, color = n.stage, fill= n.stage, label=n)) +
  geom_col(position = position_dodge2(preserve = "single", padding = 0.1))+
  geom_text(aes(label=n),position = position_dodge2(0.9),vjust=-0.5)

输出:

在此处输入图像描述


推荐阅读