Harry M
Harry M

Reputation: 2096

ggplot: How to add labels to stat_summary_bin (not stat_summary)?

I'm able to create a stat_summary_bin with each x bin (a continuous variable) showing the avg value of y like below. How can I add y value labels, showing the avg y value per bin above each bin?

ggplot(diamonds, aes(x=price, y=carat)) +
  stat_summary_bin(fun.y = "mean",
                   geom="bar",
                   binwidth=5000
                   )

enter image description here

The answer here which uses stat_summary() doesn't resolve my question. When I tried the solution there, it didn't handle the binwidths correctly.

ggplot(diamonds,
       aes(x=price, y=carat, label=round(..y..,2))
       ) +
  stat_summary_bin(fun = "mean",geom="bar", binwidth=5000) +
  stat_summary(fun = "mean",geom="text",binwidth=5000)

enter image description here

Upvotes: 1

Views: 426

Answers (1)

MrFlick
MrFlick

Reputation: 206546

The same solution for stat_summary works for stat_summary_bin

ggplot(diamonds, aes(x=price, y=carat, label=round(..y..,2))) + 
  stat_summary_bin(fun = "mean",geom="bar", binwidth=5000) + 
  stat_summary_bin(fun = "mean",geom="text",binwidth=5000, vjust=-0.5)

enter image description here

Tested with ggplot2_3.3.2. Note that fun.y is deprecated and the help page encourages you to use fun instead.

Upvotes: 4

Related Questions