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

如何手动调整ggplot2图例,正确展示vlines垂直线的对应样式

ggplot图例样式匹配调整方案

以下是调整后的完整代码,可直接运行得到符合要求的绘图效果:

library(ggplot2)

# 原始数据集
df <- data.frame(value = c(80,75,50,60,5,91,68,50,40,50),
                 event = c("a","b","c","d","e","a","b","c","d","e"), 
                 cell = c("A","A","A","A","A","B","B","B","B","B"))

lines <- data.frame(intercepts = c("b","d"), names = c('treatment1','treatment2'))

# 调整后的绘图代码
ggplot(df, aes(x=event , y=value, group = cell, color =cell)) + 
  geom_line(aes(linetype=cell), linewidth =1) +
  geom_point(aes(shape=cell), size = 2) +
  theme(panel.grid = element_blank(), 
        legend.key = element_rect(fill="white"),
        legend.title = element_blank(),
        panel.background = element_blank()) +
  # 新增key_glyph参数指定垂直线图例为垂直样式
  geom_vline(data = lines, aes(xintercept = intercepts, color = names, linetype = names),
             key_glyph = draw_key_vline) +
  scale_color_manual(values = c("A" = "red", "B" = "blue", "treatment1" = "green", "treatment2" = "purple"),
                     breaks = c("A", "B", "treatment1", "treatment2")) +
  scale_linetype_manual(values = c("A" = "solid", "B" = "solid", "treatment1" = "dashed","treatment2"="dashed"),
                        breaks = c("A", "B", "treatment1", "treatment2")) +
  # shape仅保留cell分类,排除treatment项
  scale_shape_manual(values = c("A" = 18, "B" = 20),
                     breaks = c("A", "B")) +
  # 图例规则调整
  guides(
    # A、B的点图例叠加显示对应实线
    shape = guide_legend(order = 1, override.aes = list(linetype = "solid", linewidth = 1)),
    # 关闭独立的线型图例,合并到颜色图例
    linetype = "none",
    # 颜色图例隐藏点,仅显示线条
    color = guide_legend(order = 2, override.aes = list(shape = NA, linewidth = 1))
  )

核心调整说明

  • 给geom_vline添加key_glyph = draw_key_vline参数,修正垂直线图例默认显示为水平线的问题
  • 限定shape映射的生效范围仅为A、B两个cell分类,避免treatment出现在点图例中
  • 通过guides函数合并重复图例,分别定义两类图例的显示规则:cell分类显示「对应颜色实线+对应形状标记点」,treatment分类显示「对应颜色垂直虚线」

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 04:06:03