wilkelab / ggridges

Ridgeline plots in ggplot2
https://wilkelab.org/ggridges
GNU General Public License v2.0
411 stars 31 forks source link

quantile vignette example does not work with larger numbers of quantiles #65

Open nickreich opened 3 years ago

nickreich commented 3 years ago

I tried to reproduce the quantile vignette example but with 10 quantiles instead of 4. The resulting color scale is mis-ordered and mis-labeled.

library(ggplot2)
library(ggridges)
library(viridis)
#> Loading required package: viridisLite
ggplot(iris, aes(x=Sepal.Length, y=Species, fill = factor(stat(quantile)))) +
  stat_density_ridges(
    geom = "density_ridges_gradient", calc_ecdf = TRUE,
    quantiles = 10, quantile_lines = TRUE
  ) +
  scale_fill_viridis_d(name = "Quantiles")
#> Picking joint bandwidth of 0.181

Created on 2020-12-28 by the reprex package (v0.3.0)

nickreich commented 3 years ago

For what it's worth, it does work with 9 quantiles (and lower numbers as well):

library(ggplot2)
library(ggridges)
library(viridis)
#> Loading required package: viridisLite
ggplot(iris, aes(x=Sepal.Length, y=Species, fill = factor(stat(quantile)))) +
  stat_density_ridges(
    geom = "density_ridges_gradient", calc_ecdf = TRUE,
    quantiles = 9, quantile_lines = TRUE
  ) +
  scale_fill_viridis_d(name = "Quantiles")
#> Picking joint bandwidth of 0.181

Created on 2020-12-28 by the reprex package (v0.3.0)

clauswilke commented 3 years ago

I suspect the problem is this line: https://github.com/wilkelab/ggridges/blob/ec658440928fa160750d3dce28a4f59501d6e6a9/R/stats.R#L290

We're converting the quantiles into a factor separately for each group, and that will go wrong if some groups don't contain all levels. Solutions would be to explicitly set the levels or to do the factor conversion on the entire resulting data frame, not by group.

clauswilke commented 3 years ago

To do the factor conversion on the entire data frame, we could follow the template of StatDensity2d: https://github.com/tidyverse/ggplot2/blob/feaa4bc341d1df8663ed478b448754b3bca3a375/R/stat-density-2d.r#L127-L132