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

如何在R的ggplot绘图中为中位数(红色三角)添加图例标签

解决配对图中位数图例添加问题

要给现有sexe图例上方添加中位数的图例标签,核心是让中位数元素进入ggplot的图例系统,而非直接硬编码颜色/形状。修改后的完整代码如下:

library(tidyverse)

mydata <- data.frame(ID = c(1, 2, 3, 5, 6, 7, 9, 11, 12, 13),          #patient ID
                     t1 = c(37, 66, 28, 60, 44, 24, 47, 44, 33, 47),    #evaluation before
                     t4 = c(33, 45, 27, 39, 24, 29, 24, 37, 27, 42),    #evaluation after
                     sexe = c(1, 2, 2, 1, 1, 1, 2, 2, 2, 1))       

pval <- wilcox.test(x = mydata$t1,y = mydata$t4, paired = T,exact = F)$p.value %>% round(2)

df <- mydata %>% 
  pivot_longer(2:3,names_to = "Time") %>% # 转换为长格式
  mutate(sexe = as.factor(sexe),
         Time = as.factor(Time)) # 转为因子类型

ggplot(df,aes(Time,value,color = sexe,group = ID)) + 
  geom_point() + 
  geom_line() + 
  # 关键修改:将颜色、形状映射到aes内,指定分组为"Median"
  stat_summary(inherit.aes = F,aes(Time,value, color = "Median", shape = "Median"),
    geom = "point", fun = "median", 
    size = 3, fill = "red"
  ) +
  # 手动设置各分组颜色:保留sexe默认色,中位数设为红色
  scale_color_manual(values = c("1" = "#F8766D", "2" = "#00BFC4", "Median" = "red")) +
  # 手动设置形状:sexe用默认圆点,中位数用24号红色三角
  scale_shape_manual(values = c("1" = 16, "2" = 16, "Median" = 24)) +
  # 合并颜色与形状图例,调整顺序让中位数图例排最上方
  guides(color = guide_legend(order = 1), shape = guide_legend(order = 1)) +
  annotate("text", x = 1.7, y = 60, label = paste('P-Value is',pval)) + 
  coord_cartesian(xlim = c(1.4,1.6)) +
  theme_bw()

核心逻辑说明:

  1. 把stat_summary的颜色、形状参数从aes外部移到内部,指定分组名"Median",让ggplot识别并生成对应的图例项
  2. 通过scale_color_manual和scale_shape_manual统一控制所有分组的视觉样式,保证原有sexe点的样式不变
  3. 用guides()调整图例顺序,让中位数图例排在sexe图例之前
  4. 若需要统一图例标题,可在scale_color_manual中添加name参数设置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 07:25:06