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

如何使用ggstatsplot绘制无分面的分组折线图?

问题:无法用ggstatsplot复现ggplot2的分组折线图效果

我可以用ggplot2绘制出符合要求的分组折线图,但无法借助自带美观默认样式的ggstatsplot包实现相同效果。核心问题在于ggstatsplot默认采用分面展示,无法按预期处理分组交互逻辑。以下是我的ggplot2实现代码,以及两次ggstatsplot的尝试代码:

library(dplyr)
library(ggplot2)
library(ggstatsplot)

set.seed(42)

d1 <-  data.frame(time_serie = as.factor(rep(rep(1:3, each = 6), 3)),
                  treatment = as.factor(rep(c("HIGH", "MEDIUM", "LOW"), 
                                            each = 18)),
                  value = runif(54, 1, 10))

d2 <- d1 %>%
  summarize(mean_value = mean(value), 
            sd_value = sd(value),
            .by = c(time_serie, treatment))

# 使用ggplot2绘制目标图
ggplot(data = d2,
       aes(x = time_serie, y = mean_value, 
           color = treatment, group = treatment)) + 
  geom_violin(data = d1,
              aes(x = time_serie, y = value, 
                  color = treatment, fill = treatment,
                  group = interaction(treatment, time_serie)), 
              alpha = 0.1, position = position_dodge(0.3), 
              inherit.aes = FALSE) +
  geom_errorbar(aes(ymin = mean_value - sd_value, 
                    ymax = mean_value + sd_value), 
                width = .2, position = position_dodge(0.3), linewidth = 1) +
  geom_point(position = position_dodge(0.3), size = 3) + 
  geom_line(aes(color = treatment), 
            position = position_dodge(0.3), linewidth = 1) 

# 使用ggstatsplot的两次尝试

# 第一次尝试
grouped_ggwithinstats(data = d1, 
                      x = time_serie, y = value, 
                      grouping.var = treatment)

# 第二次尝试
grouped_ggwithinstats(data = d1, 
                      x = time_serie, y = value, 
                      grouping.var = interaction(treatment, time_serie))

效果对比

  • 目标效果(ggplot2绘制):
    ggplot2绘制的分组折线图,包含小提琴图、均值点、误差棒和分组折线

  • ggstatsplot第二次尝试的效果:
    ggstatsplot分面展示的结果,未实现单图分组折线效果

内容的提问来源于stack exchange,提问作者Muhammad Aaqib Shamim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 06:03:14