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

分面绘制联合直方图与箱线图的需求及代码修正

修正后的分面直方图+箱线图代码

你的代码核心问题有两个:一是箱线图的group=1会让所有分面共用全局数据集的统计量,而非当前集群的;二是orientation="y"参数设置错误,导致箱线图方向不符合预期。以下是修正后的完整代码:

set.seed(123) # 设置随机种子保证结果可复现
de <- data.frame(
  F3A7_1 = c(
    rnorm(1000, mean = 2, sd = 1),
    rnorm(1000, mean = 4, sd = 1.5),
    rnorm(1000, mean = 1, sd = 0.5),
    rnorm(1000, mean = 3, sd = 1)
  ),
  cluster_n = rep(paste("Cluster", 1:4), each = 1000)
)

library(ggplot2)
ggplot(de, aes(x = F3A7_1)) +
  facet_wrap(~ cluster_n, scales = "free_y") +
  # 绘制直方图
  geom_histogram(bins = 7,
                 fill = "darkseagreen2",
                 color = "darkgreen",
                 alpha = 0.7) +
  # 绘制位于直方图下方的横向箱线图
  geom_boxplot(aes(y = -0.5, group = cluster_n),  
               orientation = "x", # 对应x轴数值的横向箱线图
               width = 0.5,
               outlier.shape = NA,
               fill = "darkseagreen2",
               color = "darkgreen",
               alpha = 0.7) +
  # 扩展y轴范围,确保箱线图可见
  coord_cartesian(ylim = c(-1, NA)) +
  theme_bw()

关键修正点说明

  • 箱线图分组:将group=1改为group=cluster_n,确保每个分面的箱线图仅计算当前集群的F3A7_1统计量(中位数、四分位数等)。
  • 箱线图方向:将orientation="y"改为orientation="x",匹配直方图的x轴数值维度,生成横向箱线图。
  • 随机种子:添加set.seed(123)保证随机数据完全可复现,便于调试验证。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 18:56:01