如何在ggplot2的不同分面中添加对应水平线?
解决ggplot2分面柱状图水平线匹配分面的问题
问题场景
你用ggplot2绘制了按NutrientType分面的柱状图,想要给TN和TP两个分面分别添加对应指导值的水平线(TN对应900,TP对应250),但当前用geom_hline的方法会把两条水平线同时显示在每个分面中,无法实现分面对应。
数据与现有代码
原始数据
BARR1 <- tibble::tribble( ~Trip, ~Depth, ~NutrientType, ~ugL, "Before", "Surface", "TN", 1111, "Before", "Surface", "TP", 162, "Before", "Near bottom", "TN", 1428, "Before", "Near bottom", "TP", 191, "After", "Surface", "TN", 869, "After", "Surface", "TP", 756, "After", "Near bottom", "TN", 816, "After", "Near bottom", "TP", 487 )
现有绘图代码
colours <- c("#your_color1", "#your_color2") # 替换为你实际使用的颜色 BARR1plot <- ggplot( BARR1, aes( x = Depth, y = ugL, fill = Trip ) ) + geom_bar(colour = "black", stat = "identity", position = "dodge") + scale_fill_manual(values = colours) + theme_classic() + theme(text = element_text(size = 18)) + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 12)) + theme(axis.title.y = element_text(size = 16)) + theme(legend.title = element_blank()) + ylab("Concentration (µg/L)") + xlab("") + facet_grid(~NutrientType, scales = "fixed", switch = "x") + labs(title = "BARR1") + theme(plot.title = element_text(hjust = 0)) + theme(panel.spacing = unit(0, "mm"))
解决方案
问题出在水平线数据框的分组列名与分面变量不匹配,导致ggplot无法关联水平线和对应分面。只需调整水平线数据框的列名,让它和分面变量NutrientType一致即可:
修正后的水平线代码
# 创建匹配分面变量的水平线数据框 data_hline <- data.frame( NutrientType = c("TN", "TP"), # 列名与分面变量完全一致 hline = c(900, 250) # 对应各自的指导值 ) # 添加水平线到绘图 BARR1plot + geom_hline( data = data_hline, aes(yintercept = hline) )
可选:自定义水平线样式
如果需要突出显示水平线,可以添加颜色、线型等样式:
BARR1plot + geom_hline( data = data_hline, aes(yintercept = hline), color = "darkred", # 设置颜色 linetype = "dashed", # 设置线型 size = 1 # 设置线宽 )
修改后,ggplot会自动将TN对应的水平线显示在TN分面,TP对应的水平线显示在TP分面,不会再出现交叉显示的问题。
内容的提问来源于stack exchange,提问作者Lindsey
相关产品推荐
相关产品推荐

