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

ggscatter绘制Pearson相关图:调整系数文本位置及小写r显示

解决ggscatter相关性图文本重叠与小写r显示问题

核心修改方案

通过自定义相关性文本的生成逻辑与位置参数,同时调整绘图区域设置,解决两个问题:

  • 将文本移至图外顶部

    1. 手动设置文本的垂直位置为数据最大值的1.1倍(可根据实际密度调整比例)
    2. 关闭绘图区域裁剪,允许文本超出画布范围
    3. 为图顶部预留足够边距,避免文本被遮挡
  • 替换大写R为小写r
    放弃ggscatter默认的自动文本生成,手动定义相关性文本的格式,直接写入小写r。

单图示例代码

library(ggpubr)

# 替换为你的数据框和列名
p <- ggscatter(your_df, x = "x_var", y = "y_var", add = "reg.line") +
  # 自定义相关性文本格式与位置
  stat_cor(
    aes(label = paste0("r = ", round(r, 2), ", p = ", round(p.value, 3))),
    label.x = mean(your_df$x_var),  # 水平居中
    label.y = max(your_df$y_var) * 1.1,  # 文本置于数据顶部上方10%
    show.legend = FALSE
  ) +
  # 允许文本超出绘图区域不被裁剪
  coord_cartesian(clip = "off") +
  # 顶部预留30px空间放置文本,其他边距按需调整
  theme(plot.margin = margin(t = 30, r = 10, b = 10, l = 10))

print(p)

批量生成7张图并合并

可以封装成函数批量处理,再用ggarrange合并:

# 批量绘图函数
make_scatter_plot <- function(data, x_col, y_col) {
  ggscatter(data, x = x_col, y = y_col, add = "reg.line") +
    stat_cor(
      aes(label = paste0("r = ", round(r, 2), ", p = ", round(p.value, 3))),
      label.x = mean(data[[x_col]]),
      label.y = max(data[[y_col]]) * 1.1,
      show.legend = FALSE
    ) +
    coord_cartesian(clip = "off") +
    theme(plot.margin = margin(t = 30, r = 10, b = 10, l = 10))
}

# 生成7张图(替换为你的实际列名组合)
plot_list <- list(
  make_scatter_plot(your_df, "x1", "y1"),
  make_scatter_plot(your_df, "x2", "y2"),
  make_scatter_plot(your_df, "x3", "y3"),
  make_scatter_plot(your_df, "x4", "y4"),
  make_scatter_plot(your_df, "x5", "y5"),
  make_scatter_plot(your_df, "x6", "y6"),
  make_scatter_plot(your_df, "x7", "y7")
)

# 合并绘图,布局按需调整
ggarrange(plotlist = plot_list, ncol = 3, nrow = 3)

常见问题说明

  • 之前示例代码无效的原因:默认ggscatter(cor.coef = TRUE)会调用内置格式强制显示大写R,必须手动自定义label参数才能替换为小写。
  • 若文本仍被裁剪:增大plot.margin的t值(顶部边距),或微调label.y的比例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:25:35