r - 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
我想n
在n.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")
解决方案
也许你正在寻找这个:
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)
输出:
推荐阅读
- python - 如何在现有 csv 文件的第二列添加新列(带有标题名称)?
- java - gwhalin memcached java客户端设置对象大小> 1 MB增加slab大小
- domain-driven-design - DDD - 由于聚合数据不同而导致多个有界上下文?
- python - 如何在 GAE 应用程序中执行异步 api 请求?
- javascript - 无法解构“未定义”或“空”的属性“变量名称”
- javascript - Native Base Toast - TypeError:TypeError:TypeError:null不是对象(评估'this.toastInstance._root.getModalState')
- dynamics-crm - 如何防止从仪表板网格创建新记录?
- r - 在 R 中保持 ggplot 中的宽度不变
- google-data-studio - 如何在 Google Data Studio 连接器中获取查看者电子邮件?
- c - 简单的 IF Else,但是当我尝试生成错误时会导致命令框崩溃