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

如何用ggplot2为ggpmisc的stat_poly_eq方程添加背景填充?

为ggpmisc包中stat_poly_eq生成的方程添加背景遮挡网格线

可以通过修改stat_poly_eq的geom参数实现,将默认的纯文本输出切换为带背景的文本框,具体操作如下:

修改后的完整代码

# Data
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
df$yy <- 2 + 3 * df$x + 0.1 * df$x^2 + rnorm(100, sd = 40)

# Graph
library(ggplot2)
library(ggpmisc)

ggplot(data = df, aes(x = x, y = y)) +
  scale_x_continuous(limits = c(0,100), expand = c(0,0)) +
  scale_y_continuous(limits = c(0,400), expand = c(0,0)) +
  theme(panel.grid.major=element_line(colour="black",size=0.1)) +
  stat_poly_line() +
  stat_poly_eq(
    aes(
      label = paste(after_stat(eq.label), after_stat(rr.label), sep = "*<br>*")
    ),
    geom = "label",    # 切换为带背景的文本框几何对象
    fill = "white",    # 设置背景色为白色以遮挡网格线
    label.size = 0,    # 移除文本框边框,优化视觉效果
    size = 6,
    label.x = 0.07,
    label.y = 0.78
  ) +
  geom_point()

关键参数说明

  • geom = "label":这是实现背景遮挡的核心,将默认的纯文本输出替换为带填充背景的文本框。
  • fill:可自定义背景颜色,比如换成"lightgray"、"lightblue"等,满足不同视觉需求。
  • label.size = 0:移除文本框的边框线条,让排版更简洁;若需要保留边框,可设置为大于0的数值(如0.2)。
  • sep = "*<br>*":用换行符替代原代码中的**,让方程和R²值分行显示,提升可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:15:43