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

在R中绘制两个含不同着色区间的正态分布图形

解决R中绘制G*Power风格双正态分布着色问题

方案一:使用ggplot2的stat_function(推荐,无需预生成数据)

直接用stat_function调用正态分布密度函数,通过xlim参数精准控制每个分布的着色区间,避免数据框拼接带来的颜色混乱问题。

完整可复现代码

library(ggplot2)

# 定义核心参数
cutoff <- 2          # 临界值
h0_mean <- 0         # H0分布均值
h0_sd <- 1           # H0分布标准差
h1_mean <- 2.5       # H1分布均值
h1_sd <- 1           # H1分布标准差

# 绘制图形
ggplot(data.frame(x = c(-3, 5)), aes(x = x)) +
  # 绘制H0分布:x≥2标红,其余灰色
  stat_function(fun = dnorm, args = list(mean = h0_mean, sd = h0_sd),
                geom = "area", fill = "gray70", xlim = c(-3, cutoff)) +
  stat_function(fun = dnorm, args = list(mean = h0_mean, sd = h0_sd),
                geom = "area", fill = "red", alpha = 0.5, xlim = c(cutoff, 5)) +
  # 绘制H1分布:x≤2标蓝,其余灰色
  stat_function(fun = dnorm, args = list(mean = h1_mean, sd = h1_sd),
                geom = "area", fill = "gray70", xlim = c(cutoff, 5)) +
  stat_function(fun = dnorm, args = list(mean = h1_mean, sd = h1_sd),
                geom = "area", fill = "blue", alpha = 0.5, xlim = c(-3, cutoff)) +
  # 添加临界虚线
  geom_vline(xintercept = cutoff, linetype = "dashed", color = "black") +
  # 标注分布名称
  annotate("text", x = h0_mean, y = dnorm(h0_mean, h0_mean, h0_sd),
           label = "H0", vjust = -0.5) +
  annotate("text", x = h1_mean, y = dnorm(h1_mean, h1_mean, h1_sd),
           label = "H1", vjust = -0.5) +
  # 调整标签和主题
  labs(x = "X", y = "Density", title = "G*Power Style Distribution Plot") +
  theme_minimal()

方案二:基于预生成数据框精准着色

如果坚持使用预生成数据,可通过为每个数据点指定颜色值,再用scale_fill_identity直接映射颜色,解决重叠区着色错误问题。

完整可复现代码

library(dplyr)
library(ggplot2)

# 生成H0分布数据并指定颜色
h0_data <- data.frame(x = seq(-3, 5, length.out = 1000)) %>%
  mutate(
    y = dnorm(x, mean = 0, sd = 1),
    dist = "H0",
    fill_color = ifelse(x >= 2, "red", "gray70")
  )

# 生成H1分布数据并指定颜色
h1_data <- data.frame(x = seq(-3, 5, length.out = 1000)) %>%
  mutate(
    y = dnorm(x, mean = 2.5, sd = 1),
    dist = "H1",
    fill_color = ifelse(x <= 2, "blue", "gray70")
  )

# 合并数据
both_data <- bind_rows(h0_data, h1_data)

# 绘图
ggplot(both_data, aes(x = x, y = y, fill = fill_color)) +
  geom_area(alpha = 0.5) +
  geom_vline(xintercept = 2, linetype = "dashed", color = "black") +
  scale_fill_identity() +  # 直接使用fill_color列的颜色值
  labs(x = "X", y = "Density", title = "G*Power Style Distribution Plot") +
  theme_minimal()

问题原因说明

你之前的代码出错,是因为合并数据框后,着色逻辑没有针对每个分布单独过滤x范围,导致重叠区域的颜色被错误覆盖。上面两种方案分别通过分段绘制函数、为每个数据点绑定专属颜色,精准实现了H0(x≥2红)、H1(x≤2蓝)的着色需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 00:11:11