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

基于ggplot2绘制带均值绿线的分面直方图求助

调整ggplot2直方图至目标样式(含均值绿色竖线)

以下是修改后的代码,可实现你需要的效果——添加均值绿色竖线,同时优化直方图样式以匹配标准可视化风格:

library(ggplot2)

sample.range <- 50:150
mean_val <- 100  # 重命名变量避免与内置函数`mean`冲突
sd_val <- 15
set.seed(1)
n.samples <- c(1000, 10000)
my.df <- do.call(
  rbind, 
  lapply(
    n.samples, 
    function(x) data.frame(
      "SampleSize" = factor(x),  # 转为因子让分面标签更直观
      "control" = rnorm(x, mean_val, sd_val)
    )
  )
)

ggplot(my.df, aes(x = control)) + 
  # 调整直方图分箱与样式,提升整洁度
  geom_histogram(binwidth = 3, fill = "#f0f0f0", color = "black", alpha = 0.8) + 
  # 添加均值绿色竖线,加粗增强辨识度
  geom_vline(xintercept = mean_val, color = "#2ecc71", linewidth = 1.2) + 
  # 分面布局,固定x轴范围、允许y轴自由缩放
  facet_wrap(.~SampleSize, scales = "free_y") + 
  # 统一两个面板的x轴范围
  xlim(range(sample.range)) + 
  # 添加清晰的坐标轴标签与标题
  labs(x = "Control Value", y = "Count", title = "Histogram of Control Samples by Sample Size") + 
  # 优化主题样式,简化背景突出数据
  theme_minimal() + 
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
    axis.title = element_text(size = 12),
    strip.text = element_text(size = 11, face = "bold")
  )

关键改动说明:

  • 变量重命名:将mean改为mean_val、sd改为sd_val,避免与R内置函数冲突
  • 直方图细节:设置binwidth控制分箱宽度,调整填充色与边框色,让图表更规整
  • 均值竖线:通过geom_vline添加对应均值的绿色竖线,加粗线条使其更醒目
  • 分面优化:将SampleSize转为因子,同时固定x轴范围,保证两个面板横轴一致
  • 主题调整:使用theme_minimal简化背景,调整标题、标签的样式提升可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:55:22