首页 > 解决方案 > 如何在ggplot2中为我的直方图的每个条添加标签?

问题描述

我目前正在使用 ggplot2 在 R 中制作直方图。我想为直方图中的每个条形图(或至少前 5 个条形图)添加直方图的 y 值(占总数的百分比)。我试图复制我在这里看到的示例,但没有成功。

这是我的代码。

df_2 %>%
  ggplot(aes(x = day_difference)) +
  geom_histogram(aes(y = stat(count)/sum(stat(count))), color="darkblue", fill="deepskyblue2", binwidth = 10, boundary = 9) +
  stat_bin(binwidth = 10, geom="text", colour="black", size=3.5, aes(label=stat(count)/sum(stat(count)))) +
  scale_x_continuous(breaks = breaks_width(10)) +
  scale_y_continuous(labels = percent, breaks = breaks_width(0.1)) +
  labs(x = "difference (days)", y = "count", title = "Difference between first and second invitations (2021)") +
  theme_bw()

这样做时,我的结果是:

图像

基本上,标签似乎实际上没问题,因为它遵循我的直方图分布(我现在将乘以 100 以获得百分比并将其四舍五入).. 问题是其他一切,正如您在图片中看到的那样,情节不是t 创建,感觉就像所有的条都堆叠在左侧。

有没有办法解决这个问题?这也需要很多时间,而我的情节通常需要几秒钟才能创建。谢谢。

标签: rggplot2

解决方案


你可以试试

mtcars %>%
  ggplot(aes(x = disp, y=stat(count)/sum(stat(count)))) +
  stat_bin(binwidth = 10, geom="bar", boundary = 9)+
  stat_bin(binwidth = 10, geom="text", boundary = 9,angle=90,hjust=0,
           aes(label = scales::percent(stat(count)/sum(stat(count)))))

在此处输入图像描述


推荐阅读