ggplot:如何将标签添加到stat_summary_bin(不是stat_summary)?

时间:2020-07-07 05:43:26

标签: r ggplot2 tidyverse

我能够创建一个stat_summary_bin,每个x bin(一个连续变量)显示y的平均值,如下所示。如何添加y值标签,在每个bin上方显示每个bin的平均y值?

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

enter image description here

使用stat_summary()的答案here无法解决我的问题。当我在那里尝试解决方案时,它无法正确处理二进制宽度。

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

1 个答案:

答案 0 :(得分:3)

stat_summary的相同解决方案适用于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

经过ggplot2_3.3.2测试。请注意,fun.y已过时,帮助页面鼓励您改用fun