ggplot 中不同颜色点拟合两条曲线教程 - 使用 geom_smooth() 和 scale_color_manual()
可以使用 geom_smooth() 函数来拟合两条曲线,并使用 scale_color_manual() 函数为不同颜色的点分配颜色。下面是示例代码:
library(ggplot2)
# 创建数据框
df <- data.frame(
x = c(1, 2, 3, 4, 5, 6, 7, 8),
y = c(2, 3, 5, 6, 8, 10, 11, 13),
group = c('A', 'A', 'A', 'B', 'B', 'B', 'B', 'B')
)
# 绘制散点图并拟合两条曲线
ggplot(df, aes(x, y, color = group)) +
geom_point() +
geom_smooth(method = 'lm', formula = y ~ x, se = FALSE) +
geom_smooth(method = 'lm', formula = y ~ x, se = FALSE, linetype = 'dashed') +
scale_color_manual(values = c('red', 'blue'))
上述代码将 x 作为自变量,y 作为因变量,group 作为颜色分组变量。使用 geom_point() 函数绘制散点图,使用 geom_smooth() 函数拟合两条曲线。使用 scale_color_manual() 函数为不同颜色的点分配颜色,这里分别为 'A' 组和 'B' 组分配了红色和蓝色。其中,linetype 参数用于指定第二条曲线的类型,这里使用虚线。
原文地址: https://www.cveoy.top/t/topic/nfeQ 著作权归作者所有。请勿转载和采集!