tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.51k stars 2.03k forks source link

support loess in stat_density2d #2859

Closed kendonB closed 5 years ago

kendonB commented 6 years ago

The current implementation uses kde2d which has edge effects for points within the bandwidth of an edge. I believe a 2d loess wouldn't have such a problem. I believe one can calculate the loess using something like loess(z ~ x + y).

To illustrate the edge effects:

library(tidyverse)
set.seed(4393)
dsmall <- diamonds[sample(nrow(diamonds), 1000), ] 

# This one just zooms in on the correct plot
p1 <- dsmall %>% 
    ggplot(aes(x, y)) + 
    stat_density_2d(geom = "raster", aes(fill = stat(density)), contour = FALSE) + 
    coord_cartesian(xlim = c(4.5, 9), expand = FALSE)

# This one recalculates the density after subsetting
p2 <- dsmall %>% 
    ggplot(aes(x, y)) + 
    stat_density_2d(geom = "raster", aes(fill = stat(density)), contour = FALSE) + 
    scale_x_continuous(limits = c(4.5, 9)) + 
    coord_cartesian(expand = FALSE)

cowplot::plot_grid(plotlist = list(p1, p2), ncol = 1)

Top plot here is visually correct; bottom one is incorrect (see left part of the plots).

Created on 2018-08-26 by the reprex package (v0.2.0.9000).

hadley commented 5 years ago

It would not be easy to change the default, but we could make this an additional option.

@clauswilke, @paleolimbot do you have any thoughts about this as part of a bigger density/contouring reconsideration?

clauswilke commented 5 years ago

If we implement a geom that does the contouring at draw time, then the underlying data grid can be created by a variety of different stats, and one could be a 2d loess. I think that separately we need to retain the current stat_contour(), and probably also add a stat_filled_contour(). I'm not sure we want to add the 2d loess option to those stats, since it makes for a busy and complicated API.

hadley commented 5 years ago

Ok, this sounds like it would best belong in an extension package then.

lock[bot] commented 4 years ago

This old issue has been automatically locked. If you believe you have found a related problem, please file a new issue (with reprex) and link to this issue. https://reprex.tidyverse.org/