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

如何用ggplot绘制含主散点图与两个直方图的组合可视化图?

带直方图的散点图相关性可视化(ggplot2实现)

以下是满足需求的完整代码,包含数据生成、颜色分组、回归线添加、相关系数标注以及边缘直方图的绘制:

# 加载所需包
library(ggplot2)
library(ggExtra)
library(dplyr)

# 生成示例数据(与提问中的示例一致)
n <- 300; percent_zeros <- 0.2; n_zeros <- percent_zeros * n
set.seed(123)  
x <- runif(n, min = 0, max = 0.6)  
noise <- runif(n, min = -0.05, max = 0.05)  
y <- 0.8 * x + noise  
y <- pmax(0, pmin(0.6, y))
zero_indices_x <- sample(1:n, n_zeros)   
zero_indices_y <- sample(setdiff(1:n, zero_indices_x), n_zeros)  
x[zero_indices_x] <- 0
y[zero_indices_y] <- 0
df <- data.frame(x, y)

# 按规则定义点的分组(用于颜色映射)
df$group <- case_when(
  x != 0 & y != 0 ~ "X/Y均非零",
  x != 0 & y == 0 ~ "仅X非零",
  x == 0 & y != 0 ~ "仅Y非零",
  TRUE ~ "X/Y均为零"
)

# 计算X/Y均非零子集的相关系数与p值
cor_subset <- df %>% filter(x != 0 & y != 0)
cor_result <- cor.test(cor_subset$x, cor_subset$y)
cor_label <- paste0("r = ", round(cor_result$estimate, 3), "\np = ", format(cor_result$p.value, scientific = TRUE, digits = 3))

# 绘制主散点图
main_plot <- ggplot(df, aes(x = x, y = y, color = group)) +
  geom_point(size = 2, alpha = 0.7) +
  # 仅为X/Y均非零的点添加回归线
  geom_smooth(data = cor_subset, method = "lm", se = FALSE, color = "darkgreen", linewidth = 1.2) +
  # 添加相关系数与p值标注
  annotate("text", x = max(df$x)*0.1, y = max(df$y)*0.9, label = cor_label, hjust = 0, size = 4) +
  # 自定义颜色映射
  scale_color_manual(values = c(
    "X/Y均非零" = "green",
    "仅X非零" = "yellow",
    "仅Y非零" = "blue",
    "X/Y均为零" = "gray50"
  )) +
  labs(x = "X变量", y = "Y变量") +
  theme_minimal() +
  theme(legend.position = "bottom", legend.title = element_blank())

# 添加边缘直方图(X轴用黄色,Y轴用蓝色)
ggMarginal(main_plot, 
           type = "histogram", 
           fill = c("yellow", "blue"),
           col = "white",
           size = 5)

关键说明

  • 颜色规则:通过case_when明确分组,再用scale_color_manual匹配对应颜色,保留所有零值/NA点并标记为灰色
  • 回归线:geom_smooth通过data参数指定仅使用X/Y均非零的子集数据,确保回归线仅针对有效相关分析样本
  • 统计标注:用cor.test计算子集的Pearson相关系数与p值,通过annotate添加到图中
  • 边缘直方图:借助ggMarginal实现,X轴直方图填充黄色对应仅X非零的点,Y轴填充蓝色对应仅Y非零的点

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:20:05