这是一个条形图:
ggplot(mtcars) +
geom_bar(aes(x = reorder(factor(cyl), mpg), y = mpg), stat="identity") +
coord_flip()
Run Code Online (Sandbox Code Playgroud)
我想在最后添加标签,显示每个条形中 mpg 的总值。例如,仅从眼球上看,4cyl 就在 290 左右。我想为条形添加一个显示确切数字的标签。
我想尝试一下,看看它们的外观,所以为了完整性:
我找到了这篇SO 帖子,但一直在努力复制所选的答案。这是我的尝试:
ggplot(mtcars) +
geom_bar(aes(x = reorder(factor(cyl), mpg), y = mpg), stat="identity") +
coord_flip() +
geom_text(aes(label = mpg))
Run Code Online (Sandbox Code Playgroud)
这给出了一个错误:
错误:geom_text 需要以下缺失的美学:x, y
如何在条形末端添加标签?
这将通过为标签绘图生成新的 data.frame 来满足您的需求。您可以通过调整nudge_y和 来自定义文本的位置angle。
library(dplyr)
tmp <- mtcars %>% group_by(cyl) %>% summarise(tot_mpg = sum(mpg))
tmp$cyl <- factor(tmp$cyl)
ggplot(mtcars) +
geom_bar(aes(x = reorder(factor(cyl), mpg), y = mpg), stat="identity") +
coord_flip() + geom_text(data = tmp, nudge_y = 10, angle = 270,
aes(x = cyl, y = tot_mpg, label = tot_mpg))
Run Code Online (Sandbox Code Playgroud)