【问题标题】:Vertical line between bins on histogram in ggplotggplot中直方图上的箱之间的垂直线
【发布时间】:2020-08-09 12:49:55
【问题描述】:

我希望能够在 28.5、26.5 和 30.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)

【问题讨论】:

  • 您的 x 轴是离散的,因此您无法根据数值添加垂直线。请提供X2miledata 的可重现示例。

标签: r ggplot2 plot histogram probability-density


【解决方案1】:

在您的数据集上,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。在下面的代码中,我将此选项绘制为“红”线。

对于第二个,您可以手动计算 26.5 和 30.5 的柱数并将geom_vline 设置为此值。对于每个条,您从左侧开始数一个单位。在我的示例中,我有 13 个不同的条,第 4 个是 26.5,第 5 个是 30.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() 

它回答了你的问题吗?

【讨论】: