要在使用 geom_smooth 拟合的图形上添加显著性星号,并使颜色与公式对应,可以使用 ggplot2 软件包中的 annotate 函数。具体步骤如下:

  1. 首先,在 ggplot 函数中添加两条 geom_smooth 语句来拟合两条线。

  2. 在拟合语句中使用 aes 函数来指定颜色变量,并设置颜色的取值范围。

  3. 在 ggplot 函数中添加 annotate 函数来添加星号标注。在 annotate 函数中,使用 geom_text 语句来添加文本标注,使用 aes 函数来指定文本的位置和颜色。

  4. 在 annotate 函数中,使用 parse 函数来解析公式字符串,并添加星号标注。

下面是一个示例代码,其中拟合了两条线,并使用颜色变量来区分不同的线。在 annotate 函数中,使用 parse 函数来解析公式字符串,并添加星号标注。

library(ggplot2)

# 创建示例数据
set.seed(123)
df <- data.frame(x = 1:10, y1 = rnorm(10), y2 = rnorm(10, mean = 1))

# 绘制散点图和两条拟合线
ggplot(df, aes(x = x)) +
  geom_point(aes(y = y1), color = 'red') +
  geom_point(aes(y = y2), color = 'blue') +
  geom_smooth(aes(y = y1, color = 'red'), se = FALSE) +
  geom_smooth(aes(y = y2, color = 'blue'), se = FALSE) +
  # 添加星号标注
  annotate('text', x = 5, y = 1, label = parse(text = 'italic(p) < 0.05~'*''), color = 'blue') +
  annotate('text', x = 5, y = -0.5, label = parse(text = 'italic(p) < 0.05~'*''), color = 'red') +
  # 设置图例
  scale_color_manual(values = c('red', 'blue'), name = 'Group', labels = c('Group 1', 'Group 2')) +
  # 设置x轴和y轴标签
  xlab('X') + ylab('Y')

运行代码后,可以得到一张带有星号标注的拟合线图,其中红色线和蓝色线分别对应“Group 1”和“Group 2”。在拟合线的公式中,显著性水平小于0.05的地方会添加一个星号标注。

ggplot2 geom_smooth 拟合线添加显著性星号标注 - 简单方法

原文地址: https://www.cveoy.top/t/topic/nDL1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录