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

如何为geom_jitter()与stat_summary()设置分组差异化尺寸?

ggplot2分组尺寸设置及图例标题修改方案

一、为均值点(stat_summary)设置分组不同尺寸

问题核心是geom_jitter和stat_summary对size参数的视觉尺度不同,直接共享scale会导致大小不协调。可以通过以下方式解决:

  1. 在stat_summary的aes中添加size = Group,让均值点的大小也映射到分组
  2. 使用after_scale调整均值点的大小缩放比例,匹配散点的视觉效果
  3. 单独设置误差线的宽度(linewidth),避免和点的大小混淆

修改后的stat_summary代码片段:

stat_summary(aes(group = Group, shape = Group, size = Group),
             fun.data = "mean_cl_normal",  
             geom = "pointrange",  
             position = position_dodge(0.6),
             linewidth = 1,  # 固定误差线宽度
             size = after_scale(. * 0.2)  # 调整均值点相对散点的大小比例,可按需修改
             )

保留原有的scale_size_manual设置,散点和均值点会按分组对应不同大小,且视觉比例协调:

scale_size_manual(values = c(6,7,5,7))

二、图例标题修改问题

labs(fill="lab group")不生效的原因是:你的图表中没有使用fill美学映射(仅用了color、shape、size),所以fill对应的图例不存在,自然无法修改标题。

正确的修改方式是统一修改所有相关图例的标题:

labs(y="lab value", x="lab time", color="lab group", shape="lab group", size="lab group")

如果希望合并这三个图例(均按Group分组),可以用guides设置让它们共用一个标题,更整洁:

labs(y="lab value", x="lab time") +
guides(color = guide_legend(title = "lab group"),
       shape = guide_legend(title = NULL),
       size = guide_legend(title = NULL))

完整修改后的代码

library(ggplot2)  
library(tidyverse)

x %>%
  ggplot(aes(x=Time, y=value, group=Group)) +
  geom_jitter(aes(color = Group, shape = Group, size = Group), 
              position = position_jitterdodge(jitter.width=0.2, dodge.width=0.6), alpha=0.3 ) +
  scale_shape_manual(values = c(15,16,17,18)) +
  scale_size_manual(values = c(6,7,5,7)) +
  scale_color_manual(values = c("green","orange", "red", "blue")) +
  stat_summary(aes(shape = Group, size = Group),
               fun.data = "mean_cl_normal",  
               geom = "pointrange",  
               position = position_dodge(0.6),
               linewidth = 1,
               size = after_scale(. * 0.2)) +
  scale_x_discrete(limits=c("90","150")) + 
  coord_cartesian(ylim=c(0,10)) +
  theme_classic() +
  labs(y="lab value", x="lab time", color="lab group", shape="lab group", size="lab group") +
  theme(axis.text.x=element_text(size=12, colour = "black"),
        axis.text.y=element_text(size=12, colour = "black"),
        axis.title=element_text(size=14, colour = "black"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 11:43:15