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

如何在ggplot折线图例中添加子集数据的点符号及自定义标签?

ggplot折线图图例自定义方案

我们有如下基础数据集:

data <- data.frame(Day  = c(0,0,1,1,2,2,3,3,4,4,5,5),
              Treatment = c("C", "T","C", "T","C", "T","C", "T","C", "T","C","T"),
              Temp = c(10,10,10,12,10,14,10,16,10,18,10,20))

针对原始绘图代码的图例优化需求,以下是修改后的完整实现代码:

library(ggplot2)

ggplot(data, aes(Day, Temp, group = Treatment))+
  # 绘制分组折线,保留原有样式
  geom_line(linetype="dashed", linewidth = 1, position = position_dodge(width=1), 
            aes(color = Treatment))+
  # 自定义折线颜色、标签,统一图例标题
  scale_color_manual(name = "legend",
                     values=c("lightblue","darkred"),
                     labels = c("对照(control)", "处理(treatment)"))+
  # 测量日的点:通过shape映射生成图例项
  geom_point(data = subset(data, Day %in% c(0,3,5)), 
             aes(shape = "测量日"), 
             size = 3, color = "gray32")+
  # 自定义测量日点的图例设置,匹配统一标题
  scale_shape_manual(name = "legend",
                     values = c("测量日" = 1))+
  labs(y = expression(paste("Temperature [", degree, "C]")), x = "Experimental Day")+
  theme_bw()+
  # 调整图例顺序,合并同标题项
  guides(color = guide_legend(order = 1),
         shape = guide_legend(order = 2))

关键修改说明

  • 折线图例优化:在scale_color_manual中通过labels替换原分组标记为指定名称,同时用name设置统一图例标题。
  • 测量日点加入图例:将shape放入aes()映射并指定固定值,让ggplot识别为图例项,再通过scale_shape_manual匹配标题和指定形状。
  • 图例合并与排序:用guides()调整折线和点图例的显示顺序,确保同标题的图例项合并展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 12:02:50