Here's a bar chart:
ggplot(mtcars) +
geom_bar(aes(x = reorder(factor(cyl), mpg), y = mpg), stat="identity") +
coord_flip()
I would like to add labels on the end showing the total value of mpg in each bar. For example, 4cyl looks to be around about 290 just from eyeballing. I want to add a label showing the exact number to the bars.
I'd like to experiment and see how they look, so for completeness:
I found this SO post but have struggled to replicate the chosen answer. Here's my attempt:
ggplot(mtcars) +
geom_bar(aes(x = reorder(factor(cyl), mpg), y = mpg), stat="identity") +
coord_flip() +
geom_text(aes(label = mpg))
Which gives an error:
Error: geom_text requires the following missing aesthetics: x, y
How can I add labels to the ends of the bars?
This would do what you need through generating a new data.frame for label plotting. You can customize the location of texts by adjusting nudge_y
and 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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.