jamesotto852 / ggdensity

An R package for interpretable visualizations of bivariate density estimates

Home Page:https://jamesotto852.github.io/ggdensity/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`uniroot` failing when `method = "histogram"`

jamesotto852 opened this issue · comments

For particular datasets, method = "histogram" results in an error (most likely from uniroot). This does not happen for any other method choices.

library("ggdensity"); theme_set(theme_bw())
#> Loading required package: ggplot2
library("patchwork")

set.seed(1) 
df <- data.frame(
  x = rexp(1000, 1),
  y = rexp(1000, 1)
)


p1 <- ggplot(df, aes(x^2, y^2)) + 
  geom_hdr(method = "histogram", smooth = TRUE)

p2 <- ggplot(df, aes(x^2, y^2)) + 
  geom_hdr(method = "kde")

p3 <- ggplot(df, aes(x^2, y^2)) + 
  geom_hdr(method = "mvnorm")

p4 <- ggplot(df, aes(x^2, y^2)) + 
  geom_hdr(method = "freqpoly")

p1 
#> Warning: Computation failed in `stat_hdr()`:
#> f() values at end points not of opposite sign

p2 + p3 + p4 & coord_fixed() & theme(legend.position = "none")

Created on 2021-11-18 by the reprex package (v2.0.1)

Also fails for smooth = FALSE:

library("ggdensity"); theme_set(theme_bw())
#> Loading required package: ggplot2

set.seed(1) 
df <- data.frame(
  x = rexp(1000, 1),
  y = rexp(1000, 1)
)


ggplot(df, aes(x^2, y^2)) + 
  geom_hdr(method = "histogram", smooth = FALSE)
#> Warning: Computation failed in `stat_hdr()`:
#> f() values at end points not of opposite sign

Created on 2021-11-18 by the reprex package (v2.0.1)

Hm. I'd look into why the values aren't + and -. Worst case scenario, you try() around that computation, then if it fails do a 1d grid search to find the root. See https://adv-r.hadley.nz/conditions.html for refresher on handling conditions as necessary.

Fixed with 8228134, method = "histogram" now uses something other than uniroot to find cutoff values.

library("ggdensity"); theme_set(theme_bw())
#> Loading required package: ggplot2
#> Loading required package: ggplot2

set.seed(1) 
df <- data.frame(
  x = rexp(1000, 1),
  y = rexp(1000, 1)
)

ggplot(df, aes(x^2, y^2)) + 
  geom_hdr(method = "histogram")

Created on 2022-01-12 by the reprex package (v2.0.1)