Consider the following example plot:
mtcars %>% ggplot() + stat_bin(aes(x=wt, y=..density..), binwidth=0.2)
The maximum value of density is near to 0.8. Is it possible to know its exact value?
According to stat_bin
documentation, ..density..
represents the density of points in bin, scaled to integrate to 1, but this does not help me to much to understand how these values are computed in practice, or how to get the maximum density point (as it also depends on the binwidth
set).
The closer I have get is with:
binwidth = 0.2
((mtcars$wt %/% binwidth)*binwidth) %>% table %>% prop.table %>% max
But it does return the value observed in the plot.
Any ideas?
you can try this
binwidth=0.2
x=mtcars$wt
x_bins <- table(cut(x,breaks=seq(min(x),max(x),by = binwidth)),useNA = "ifany" )
max(x_bins)/(sum(x_bins)*binwidth )
#[1] 0.78125
or
gg_plot <- mtcars %>% ggplot() + stat_bin(aes(x=wt, y=..density..), binwidth=binwidth)
max(ggplot_build(gg_plot)$data[[1]][[1]])