简体   繁体   中英

Adding labels to ends of bars in ggplot geom_bar

Here's a bar chart:

ggplot(mtcars) +
  geom_bar(aes(x = reorder(factor(cyl), mpg), y = mpg), stat="identity") +
  coord_flip()

Should produce this: 在此处输入图片说明

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:

  • Inside at the top of the bars
  • Outside the bars along the top
  • Bonus is I'm able to control whether the labels display vertically or horizontally.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM