【问题标题】:calculate x-value of curve maximum of a smooth line in R and ggplot2计算 R 和 ggplot2 中平滑线的曲线最大值的 x 值
【发布时间】:2015-12-08 00:41:33
【问题描述】:
data <- dput(data): structure(list(x = 1:16, y = c(-79.62962963, -84.72222222, -88.42592593, -74.07407407, -29.62962963, 51.38888889, 79.62962963, 96.2962963, 87.96296296, 88.42592593, 73.14814815, 12.96296296, -63.42592593, -87.03703704, -87.5, -87.96296296)), .Names = c("x", "y"), row.names = c(NA, 16L), class = "data.frame")

我在 R 中使用 ggplot2 为我的数据集计算了一条平滑线:

p1 <- ggplot(data, aes(x=x(°), y=(%)))

library(splines)
library(MASS)
(p2 <- p1 + stat_smooth(method = "lm", formula = y ~ ns(x,3)) +
  geom_point()
)

如何计算平滑线的曲线最大值的 x 值?

【问题讨论】:

    标签: r ggplot2 curve-fitting best-fit-curve curvesmoothing


    【解决方案1】:

    您需要对stat_smooth 计算的结果 data.frame 进行一些数学运算:

    library(ggplot2)
    library(splines)
    library(MASS)
    
    data <- structure(list(x = 1:16, 
                           y = c(-79.62962963, -84.72222222, -88.42592593, 
                                 -74.07407407, -29.62962963, 51.38888889, 
                                 79.62962963, 96.2962963, 87.96296296, 
                                 88.42592593, 73.14814815, 12.96296296, 
                                 -63.42592593, -87.03703704, -87.5, 
                                 -87.96296296)), .Names = c("x", "y"), 
                      row.names = c(NA, 16L), class = "data.frame") 
    
    p1 <- ggplot(data, aes(x=x, y=y))
    p1 <- p1 + stat_smooth(method = "lm", formula = y ~ ns(x,3))
    p1 <- p1 + geom_point()
    p1
    

    gb <- ggplot_build(p1)
    
    exact_x_value_of_the_curve_maximum <- gb$data[[1]]$x[which(diff(sign(diff(gb$data[[1]]$y)))==-2)+1]
    
    p1 + geom_vline(xintercept=exact_x_value_of_the_curve_maximum)
    
    exact_x_value_of_the_curve_maximum
    [1] 9.164557
    

    还有more robust ways,但您仍然需要ggplot_build 部分来获取数据。

    【讨论】:

    • 非常感谢您的帮助!我的数据中的一个案例在 x 轴上只能有 16 个值(1、2、3、...、16)中的一个。不幸的是,它在我的数据中不起作用:我在绘图上收到了几条垂直线(而不是最多一条),它们总是在我的 x 值上(例如在 x = 3 处)。什么地方出了错?以及如何让控制台输出曲线最大值的 x 值?
    • 你能提供一个dput(data)吗?
    • 使用我的数据和上述代码,我在 x 值 8 和 10 处收到两条曲线最大值。但是,拟合线的最大值不在这两个值中的任何一个处。如何绘制拟合线? dput(data): structure(list(x = 1:16, y = c(-79.62962963, -84.72222222, -88.42592593, -74.07407407, -29.62962963, 51.38888889, 79.62962963, 96.2962963, 87.96296296, 88.42592593, 73.14814815, 12.96296296, -63.42592593 , -87.03703704, -87.5, -87.96296296)), .Names = c("x", "y"), row.names = c(NA, 16L), class= "data.frame") 谢谢!
    • 我已经使用您的数据更新了两个图的答案。我是不是画错了?
    • 剧情不错!如何检索曲线最大值的确切 x 值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    相关资源
    最近更新 更多