使用 ggplot 和 facet_wrap 在每组 vline 旁边放置标签

问题描述

enter image description here

我正在尝试使用 ggplot 和 facet_wrap 绘制图表。

library(ggplot2)

year <- rep(2014:2015,length.out = 10000)
group <- sample(c(0,1,2,3,4,5,6),replace=TRUE,size=10000)
value <- sample(10000,replace = T)
dta1 <- data.frame(year = year,group = group,value = value)

dta2 <- data.frame( group = c(0,cut = c(1000,2000,3000,4000,5000,6000,7000))

merged <- merge(dta1,dta2,by="group")

ggplot(merged,aes(x=value))+
  geom_histogram(fill="red")+
  facet_wrap(~ group,scales="free")+
  geom_vline(aes(xintercept = cut),color="black")+
  geom_text(data=data.frame(merged$cut),aes(label = 'T1 =',x = data.frame(merged$cut),y = Inf),hjust = 0,vjust = 1)

我设法为每个组绘制了单独的 vlines。现在我想:

  1. 在每个 vline 旁边放置一个标签,上面写着“T1 = 'the value of the cut'”。例如,第 1 组将读取“T1 = 1000”,第 2 组将读取“T1 = 2000”等。
  2. 我希望它位于图表顶部的 vline 旁边。请注意,我的原始数据中的频率非常不同,所以一个我最多有 10,000 个,另一个可能只有 100 个。这就是我使用 scales="free" 的原因。

谢谢。

解决方法

也许这就是您要找的。​​p>

  1. 利用 dplyr::distinct 创建一个帮助数据框,其中仅包含 vline 和标签所需的值,即 group 标识符和 cut 值。
  2. 这个帮助 df 然后可以作为 data 参数传递给 geom_vlinegeom_text。您可以通过 label = paste0('T1 = ',cut)
  3. 创建标签
library(ggplot2)

year <- rep(2014:2015,length.out = 10000)
group <- sample(c(0,1,2,3,4,5,6),replace=TRUE,size=10000)
value <- sample(10000,replace = T)
dta1 <- data.frame(year = year,group = group,value = value)

dta2 <- data.frame( group = c(0,cut = c(1000,2000,3000,4000,5000,6000,7000))

merged <- merge(dta1,dta2,by="group")

df_vline <- dplyr::distinct(merged,group,cut)

ggplot(merged,aes(x=value))+
  geom_histogram(fill="red")+
  facet_wrap(~ group,scales="free")+
  geom_vline(data = df_vline,aes(xintercept = cut),color="black")+
  geom_text(data = df_vline,aes(x = cut,label = paste0('T1 = ',cut),y = Inf),hjust = 0,vjust = 1) +
  coord_cartesian(clip = "off")
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.