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

ggplot2多折线图:折线按lab着色、点按y值着色及图例优化

解决方案

先给个示例数据集方便你测试,假设你的数据结构类似这样:

set.seed(123)
df <- data.frame(
  x = rep(1:10, 3),
  y = c(rnorm(10, 5, 1), rnorm(10, 7, 1), rnorm(10, 9, 1)),
  lab = rep(c("A", "B", "C"), each = 10),
  series = rep(c("Y1", "Y2", "Y3"), each = 10) # 用来区分Y1和其他系列
)

下面是完全满足你需求的ggplot2代码:

library(ggplot2)
library(cowplot) # 用来处理图例排列

# 基础绘图逻辑:拆分图层实现折线和点的颜色分离
p <- ggplot(df, aes(x = x, y = y, group = lab)) +
  # 折线按lab变量着色
  geom_line(aes(color = lab), linewidth = 1) +
  # 非Y1系列的点:颜色和对应折线保持一致
  geom_point(data = subset(df, series != "Y1"), aes(color = lab), size = 3) +
  # Y1系列的点:按y值着色,放大点尺寸
  geom_point(data = subset(df, series == "Y1"), aes(color = y), size = 6) +
  # 配置离散颜色(对应lab)
  scale_color_manual(
    name = "Group",
    values = c("A" = "#1f77b4", "B" = "#ff7f0e", "C" = "#2ca02c"),
    limits = c("A", "B", "C")
  ) +
  # 配置连续颜色条(对应Y1的y值)
  scale_color_viridis_c(
    name = "Y Value",
    guide = guide_colorbar(title.position = "top", title.hjust = 0.5)
  ) +
  # 主题调整,先隐藏默认图例,后面手动排列
  theme(legend.position = "none")

# 提取两个独立图例:lab的分类图例和y值的颜色条
leg_lab <- get_legend(
  p + guides(color = guide_legend(order = 1)) + 
    theme(legend.position = "right", legend.title.align = 0.5)
)
leg_colorbar <- get_legend(
  p + guides(color = guide_colorbar(order = 2)) + 
    theme(legend.position = "right")
)

# 组合图表和排列好的图例:颜色条会自动占满图表高度
final_plot <- plot_grid(
  p,
  plot_grid(leg_lab, leg_colorbar, ncol = 1, align = "v"),
  rel_widths = c(4, 1)
)

final_plot

核心逻辑拆解

  1. 折线与点的颜色分离

    • 把折线和点拆成多个图层:折线绑定lab的离散颜色,Y1的点单独绑定y的连续颜色,其他点和折线颜色保持统一
    • 直接给Y1的点设置size = 6,满足放大符号的需求
  2. 图例优化

    • 用scale_color_manual和scale_color_viridis_c分别定义两种颜色映射,避免冲突
    • 用cowplot提取并垂直排列两个图例,这样lab的分类图例和颜色条就能并排显示
    • 因为点的大小是固定值(没有映射到变量),所以不会生成size相关的图例,自然就移除了“size”和“6”的条目
    • 通过plot_grid的宽度比例设置,颜色条会自动匹配图表的高度,不用额外调整
  3. 细节调整

    • 给折线设置linewidth = 1,和放大的点形成视觉平衡
    • 调整图例标题的位置,让布局更整齐

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:12:36