如何在R语言facet_wrap()拆分的每个面板中绘制对应水平线?
解决ggplot分面面板中仅显示对应水平线的问题
问题背景
你有如下数据:
variety<- c("CV1","CV1") trt<- c("N0","N1") yield<- c(100,150) dataA<- data.frame(variety,yield,trt)
使用facet_wrap()绘制分面柱状图并添加水平线时,编写了如下代码:
ggplot(data=dataA, aes(x=variety, y=yield))+ geom_bar(stat="identity", position="dodge", width=0.7, size=1) + coord_flip() + facet_wrap(~ trt) + geom_hline(yintercept=100, linetype = "dashed", color="Dark blue") + geom_hline(yintercept=150, linetype = "dashed", color="Dark blue") + windows(width=10, height=6)
遇到的问题是:两条水平线会在每个分面面板中重复显示,希望每个面板仅显示对应的一条水平线。
解决方案
核心思路是让水平线的位置与分面变量trt绑定,通过单独的数据集指定每个分面对应的水平线位置
步骤1:创建水平线对应数据框
新建包含分面变量trt和对应水平线y值的数据集,确保每个trt对应唯一的y值:
# 定义每个分面对应的水平线位置 hline_data <- data.frame(trt = c("N0", "N1"), y_val = c(100, 150))
步骤2:修改绘图代码
在geom_hline()中使用上述数据集,并通过aes()映射yintercept到对应的y值。ggplot会自动根据分面的trt值匹配对应的水平线:
ggplot(data=dataA, aes(x=variety, y=yield))+ geom_bar(stat="identity", position="dodge", width=0.7, size=1) + coord_flip() + facet_wrap(~ trt) + # 使用绑定了分面变量的数据集绘制水平线 geom_hline(data = hline_data, aes(yintercept = y_val), linetype = "dashed", color="Dark blue") + windows(width=10, height=6)
修改后,每个分面面板只会显示与自身trt对应的那条水平线,不会重复显示所有线。
内容的提问来源于stack exchange,提问作者J.K Kim
相关产品推荐
相关产品推荐

