You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2中为geom_hline水平参考线添加不重叠的正确图例

问题原因

图例重叠的核心原因是geom_hline的样式没有绑定到美学映射aes()内生成独立图例,同时你调用了未使用的fill比例尺,导致两个图例的层级混叠。

完整修改代码

library(ggplot2)
# 数据集结构保持不变
month=c("Jan","Feb","Mar","Apr","May","Jun")
rate=c(70,80,90,85,88,76) 
dd=data.frame(month,rate)
dd$type="Rate"
dd$month=factor(dd$month)

# 修改后的绘图代码
ggplot(dd,aes(x=month,y=rate,color=type, linetype=type)) + 
  geom_point(size=2) +
  geom_text(aes(label = paste(format(rate, digits = 4, format = "f"), "%")), 
            color="black",vjust = -0.5, size = 3.5) +
  geom_line(aes(group=1), size=1) + 
  # 将参考线样式移入aes生成独立Target映射项
  geom_hline(aes(yintercept=85, colour="Target", linetype="Target"), show.legend = T) +
  labs(y="", x="") + 
  # 统一配置两类元素的颜色
  scale_colour_manual(values = c("Rate"="#00BFC4", "Target"="#F8766D")) +
  # 统一配置两类元素的线型
  scale_linetype_manual(values = c("Rate"="solid", "Target"="dashed")) +
  theme(legend.position="bottom",
        legend.title = element_blank()) +
  # 合并颜色、线型图例,避免参考线图例出现多余点符号
  guides(colour = guide_legend(override.aes = list(shape = c(16, NA),
                                                   linetype = c("solid", "dashed"))))

关键修改说明

  • 将geom_hline的colour、linetype参数移入aes()内,自定义名称为Target,让ggplot识别为独立的映射项
  • 移除无用的scale_fill_discrete调用,调整scale_colour_manual同时覆盖Rate和Target的颜色配置
  • 新增scale_linetype_manual,分别配置Rate的实线样式和Target的虚线样式
  • 用guides()函数合并颜色和线型的图例,同时给Target图例设置shape=NA,避免出现多余的点符号

内容的提问来源于stack exchange,提问作者Robin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 02:12:01