Reputation: 277
I'm following up an old question addressed here:
calculate x-value of curve maximum of a smooth line in R and ggplot2
How could I calculate the Y-value of curve maximum?
Cheers
Upvotes: 0
Views: 980
Reputation: 263362
It would seem to me that code changes of "x" to "y" and 'vline' to 'hline' and "xintercept" to "yintercept" would be all that were needed:
gb <- ggplot_build(p1)
exact_y_value_of_the_curve_maximum <- gb$data[[1]]$y[which(diff(sign(diff(gb$data[[1]]$y)))==-2)+1]
p1 + geom_hline( yintercept =exact_y_value_of_the_curve_maximum)
exact_y_value_of_the_curve_maximum
I don't think I would call these "exact" since they are only numerical estimates. The other way to get that value would be
max(gb$data[[1]]$y)
As the $data element of that build-object can be examined:
> str(gb$data)
List of 2
$ :'data.frame': 80 obs. of 7 variables:
..$ x : num [1:80] 1 1.19 1.38 1.57 1.76 ...
..$ y : num [1:80] -123.3 -116.6 -109.9 -103.3 -96.6 ...
..$ ymin : num [1:80] -187 -177 -166 -156 -146 ...
..$ ymax : num [1:80] -59.4 -56.5 -53.5 -50.3 -46.9 ...
..$ se : num [1:80] 29.3 27.6 25.9 24.3 22.8 ...
..$ PANEL: int [1:80] 1 1 1 1 1 1 1 1 1 1 ...
..$ group: int [1:80] 1 1 1 1 1 1 1 1 1 1 ...
$ :'data.frame': 16 obs. of 4 variables:
..$ x : num [1:16] 1 2 3 4 5 6 7 8 9 10 ...
..$ y : num [1:16] -79.6 -84.7 -88.4 -74.1 -29.6 ...
..$ PANEL: int [1:16] 1 1 1 1 1 1 1 1 1 1 ...
..$ group: int [1:16] 1 1 1 1 1 1 1 1 1 1 ...
Upvotes: 3