Description
Some changes introduced between ggplot2 version 3.2.1 and version 3.3.1 (I did not check version 3.3.0, but I reckon it has the same problem) have lead to weird outputs when using stat_density_2d()
and geom_density_2d()
.
Here a minimum reproducible example:
-
Dataset:
problem.df.RData.zip -
Code:
# #Load ggplot2
library(ggplot2)
# #Load dataset
# setwd(readClipboard())
# save(problem.df, file = "problem.df.RData.zip")
load(file = "problem.df.RData.zip")
# #Recreate problem
problem.facet <- ggplot(data = problem.df, aes(X, Y))
problem.facet <- problem.facet + geom_point(color = "lightgray", alpha = 0.1)
# #If we use geom_density_2d we already see a difference between different ggplot2 versions
problem.facet + geom_density_2d(aes(colour = Facet.Groups)) + facet_grid(. ~ Facet.Groups)
# #If we use stat_density_2d() different ggplot2 versions result in different plots which look even weirder
problem.facet <- problem.facet + stat_density_2d(aes(fill = stat(nlevel)), geom = "polygon") +
facet_grid(. ~ Facet.Groups) + scale_fill_viridis_c()
problem.facet
# #Check the differences in "Group3", "Group4", and the "NA" column
# #Based on visual inspection of the data (see also the geom_density_2d() plot) the behavior of
# #ggplot2 version 3.2.1 should be the correct one
Using the same dataset and the same code, ggplot2 version 3.2.1 produces the following two figures:
ggplot2_321_geom_density_2d.pdf
ggplot2_321_stat_density_2d.pdf
Using the same dataset and the same code, ggplot2 version 3.3.1 produces the following two figures:
ggplot2_331_geom_density_2d.pdf
ggplot2_331_stat_density_2d.pdf
Using the same dataset and the same code, ggplot2 version 3.3.2 produces the following two figures:
ggplot2_332_geom_density_2d.pdf
ggplot2_332_stat_density_2d.pdf
Notice, how weird the colouring/breaks in the newer ggplot2 versions look like ("Group3", "Group4", and "NA" column). Also note, that the left lower peak in "Group4" appears to have disappeared in the newer ggplot2 versions using stat_density_2d()
(it is still visible, however, if we use geom_density_2d()
). Since the issue appears in both version 3.3.1 and 3.3.2, it is probably not connected to these (solved) problems (?):
#3976
#4004
Is this intended behaviour? To me the output looks like either the result of changed defaults (I know, that version 3.3.0 changed quite a bit here relative to version 3.2.1) or a bug.