如何解决使用 ggplot 和 facet_wrap 在每组 vline 旁边放置标签
我正在尝试使用 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。现在我想:
- 在每个 vline 旁边放置一个标签,上面写着“T1 = 'the value of the cut'”。例如,第 1 组将读取“T1 = 1000”,第 2 组将读取“T1 = 2000”等。
- 我希望它位于图表顶部的 vline 旁边。请注意,我的原始数据中的频率非常不同,所以一个我最多有 10,000 个,另一个可能只有 100 个。这就是我使用 scales="free" 的原因。
谢谢。
解决方法
也许这就是您要找的。p>
- 利用
dplyr::distinct
创建一个帮助数据框,其中仅包含 vline 和标签所需的值,即group
标识符和cut
值。 - 这个帮助 df 然后可以作为
data
参数传递给geom_vline
和geom_text
。您可以通过label = paste0('T1 = ',cut)
创建标签
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`.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。