ggplot 中直方图上 bin 之间的垂直线

Vertical line between bins on histogram in ggplot

我希望能够在 26.5 和 30.5 柱之间的恰好 28.5 处添加一条垂直线。这是我到目前为止的图表。如何为此添加一行?

生成此数据所需的数据是单个向量,其值介于 0 到 76.5 之间。然后将其分成多个箱,如下所示。此直方图的目的是显示每个 bin 中的项目数。

这是我目前使用的代码。代码的最后一行是我尝试添加垂直线,但它不起作用。为了绘制它,我使用了指令 here

breaks <- c(0, 0.5, 4.5, 8.5, 12.5, 16.5, 20.5, 24.5, 28.5, 32.5, 36.5, 40.5, 44.5, 
        48.5, 52.5, 56.5, 60.5, 64.5, 68.5, 72.5, 76.5)
tags <- c(0, 2.5, 6.5, 10.5, 14.5, 18.5, 22.5, 26.5, 30.5, 34.5, 38.5, 42.5, 46.5, 
      50.5, 54.5, 58.5, 62.5, 66.5, 70.5, 74.5)
group_tags <- cut(X2miledata_2020$hrs_82, breaks = breaks, include.lowest = TRUE, 
right = FALSE, labels = tags)
summary(group_tags)

ggplot(data = as_tibble(group_tags), mapping = aes(x = value)) + 
  geom_bar(fill = "bisque", color = "white", alpha = 0.7) +
  stat_count(geom="text", 
aes(label=sprintf("%.2f",..count../length(group_tags))), vjust=0) +
  labs(x='HRS scores') +
  theme_minimal() + 
  geom_vline(xintercept = 28.5)

在您的数据集上,28.5 的值不在 26.5 和 30.5 之间,因为如果您在传递 include.lowest = TRUE 时查看 cut 函数,您会将值 28.5 算作一部分组“30.5”。

举个例子:

df <- data.frame(x = rnorm(100, mean = 38.5, sd = 10))

library(dplyr)

df %>% add_row(x = 28.5) %>%
  mutate(group_tags = cut(x, breaks = breaks, include.lowest = TRUE, 
                          right = FALSE, labels = tags)) %>%
  filter(x == 28.5)

     x group_tags
1 28.5       30.5

因此,您有两种选择,具体取决于您是想在 28.5 的精确值处(因此组“30.5”)还是在 26.5 和 30.5 之间画一条线。

对于第一个选项,您只需要如上所述创建具有该特定值的第二个数据集,并使用 geom_segment 在相应 group_tags 的位置绘制一条线,值为28.5。在下面的代码中,我将此选项绘制为 "red" 行。

对于第二个,您可以手动计算 26.5 和 30.5 的柱数并将 geom_vline 设置为此值。对于每个条,您从左侧开始计算一个单位。在我的示例中,我有 13 个不同的柱,26.5 是第 4 个,30.5 是第 5 个,所以我将 geom_vline 放在 4.5(蓝线)。在您的示例中,geom_vline(xintercept = 8.5) 应该有效。

这里是生成下图的代码:

library(dplyr)

DF <- df %>% mutate(group_tags = cut(x, breaks = breaks, include.lowest = TRUE, 
                          right = FALSE, labels = tags)) 

gv <- df %>% add_row(x = 28.5) %>%
  mutate(group_tags = cut(x, breaks = breaks, include.lowest = TRUE, 
                          right = FALSE, labels = tags)) %>%
  filter(x == 28.5)

library(ggplot2)

ggplot(DF, aes(x = as.character(group_tags)))+
  geom_bar(fill = "bisque", color = "white", alpha = 0.7)+
  geom_segment(data = gv, 
             aes(x = group_tags, xend = group_tags, 
                 y = -Inf, yend = Inf,group = 1),color = "red" )+
  geom_vline(xintercept = 4.5, color = "blue")+
  stat_count(geom="text", 
             aes(label=sprintf("%.2f",..count../length(DF$group_tags))), 
             vjust=0) +
  labs(x='HRS scores') +
  theme_minimal() 

它是否回答了您的问题?