如何在ggplot中添加非线性拟合曲线y=841C^0.395
为ggplot散点图添加Study 3的非线性拟合曲线
要添加非线性方程 y = 841*C^0.395 对应的曲线,由于这是幂函数形式的非线性关系,无法直接使用geom_abline(仅适用于线性直线),需要先生成覆盖数据中C取值范围的连续序列,再计算对应的y值,最后用geom_line绘制曲线。
修改后的完整代码
df <- structure(list(cast = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L), levels = c("20", "38", "39", "40", "64"), class = "factor"), pressure = c(35, 55, 80, 30, 60, 90, 120, 10, 30, 105, 10, 25, 50, 150, 10, 30, 50, 110), A = c(41.16839801075, 30.35583650075, 22.86016618075, 37.62401496575, 42.10374747575, 29.76534520575, 19.89095365075, 34.60109149575, 36.46829997575, 10.79044853575, 10.074408825375, 14.411792332875, 18.009666975375, 2.072538610375, 21.176471287875, 29.320954852875, 33.385755602875, 12.881251150375), B = c(0.167453363918363, 0.17518132016261, 0.15617506189818, 0.151344619899147, 0.147003925515812, 0.126873347608938, 0.090790417919621, 0.163199854779293, 0.169272560643038, 0.0713129535723068, 0.095766197060871, 0.0959198565223836, 0.0942295291663098, 0.0236323199767932, 0.158893301040358, 0.152347661380295, 0.148441223978157, 0.0844843828480995 ), C = c(0.00336278437771212, 0.00331746384695424, 0.0030822017959916, 0.00292870938310887, 0.00290212934310451, 0.00250957680053723, 0.00258302780282964, 0.0024001708579677, 0.00287706607094219, 0.00162719976673661, 0.00121769817135316, 0.00127846193728378, 0.00148592933354497, 0.000842030854863154, 0.00247519031767006, 0.00269025444986639, 0.00291526589547116, 0.00207540832089215)), row.names = c(NA, -18L), class = "data.frame") # 生成Study 3曲线的数据源:覆盖C的取值范围,生成100个连续点保证曲线平滑 c_range <- seq(min(df$C), max(df$C), length.out = 100) study3_data <- data.frame(C = c_range, A = 841 * (c_range)^0.395) # 绘制包含三条曲线的图表 (plot <- ggplot(df, aes(x = C, y = A)) + geom_point() + theme_minimal() + geom_abline(aes(intercept = -6.2, slope = 13115.87, colour = "This study")) + # This study geom_abline(aes(intercept = 9.43, slope = 380.7, colour="Study 2")) + # Study 2 geom_line(data = study3_data, aes(color = "Study 3"), linewidth = 1) + # Study 3非线性曲线 scale_color_manual(values = c("This study" = "blue", "Study 2" = "red", "Study 3" = "green")) + # 自定义颜色可选 labs(color = "研究")) # 图例标题
关键说明
- 用
seq()生成C的连续取值序列,length.out=100确保曲线足够平滑 - 通过幂函数计算
Study 3对应的y值,存入单独的数据框 - 使用
geom_line()而非geom_abline()绘制非线性曲线 - 可选的
scale_color_manual()可以统一三条曲线的颜色,让图表更易区分
内容的提问来源于stack exchange,提问作者L55
相关产品推荐
相关产品推荐

