我使用mtcars
为cyl
创建条形图并填充gear
。没有配备 cyl == 8&gear == 4 的汽车。绘制时,我使用position_dodge(preserve = "single")
来保留条形的宽度。然后,使用geom_text
将标签添加到条形图。
library(ggplot)
library(dplyr)
df <- count(mtcars, cyl, gear)
ggplot(df, aes(x = factor(cyl), y = n, fill = factor(gear))) +
geom_col(position = position_dodge(preserve = "single")) +
geom_text(aes(label = n, y = n + .07), size = 5, vjust = 0,
position = position_dodge(width=.9))
出现两个问题:
答案 0 :(得分:1)
这是complete
中的tidyr
可以通过填写缺失值来提供帮助的地方。如果愿意,您也可以完全使用vjust
而不是将y值相加。
library(ggplot2)
library(dplyr)
library(tidyr)
df <- count(mtcars, cyl, gear) %>%
complete(cyl, gear, fill = list(n = 0))
ggplot(df, aes(x = factor(cyl), y = n, fill = factor(gear))) +
geom_col(position = position_dodge()) +
geom_text(aes(label = n, y = n), size = 5, vjust = -0.5,
position = position_dodge(width=.9))
由reprex package(v0.2.1)于2019-01-17创建