ggplot2
ggplot2 copied to clipboard
Confusing error message and documentation for `geom_density`
The documentation and - in the greatest part - error message for geom_density is confusing and should be corrected.
Documentation states that the
geom_density() understands the following aesthetics (required aesthetics are in bold):
- x
- y
When providing eiter x or y easthetic, everything works as expected. If trying to map BOTH x and y, following occurs:
ggplot(diamonds, aes(x = x, y = y)) +
geom_density()
Error in `check_required_aesthetics()`:
! geom_density requires the following missing aesthetics: y
Whereas the y aesthetic is clearly provided. IMO it should lead the user to the geom_density2d.
Thanks, I agree the error message is confusing and probably we can add some check like this:
https://github.com/tidyverse/ggplot2/pull/3519
But,
it should lead the user to the
geom_density2d.
should it? I heard this kind of confusion for the first time. Shouldn't the error message simply be something like x and y must not be specified both?
Very subjective, but the only time I've seen this is error is when somebody tried to do in reality geom_density2d. You know, the density of x and y planes.
But I think that the x and y must not be specified both will be enough
I suggest we just copy geom_histogram()
library(ggplot2)
ggplot(diamonds, aes(x, y)) +
geom_density()
#> Error in `check_required_aesthetics()`:
#> ! geom_density requires the following missing aesthetics: y
ggplot(diamonds, aes(x, y)) +
geom_histogram()
#> Error in `f()`:
#> ! stat_bin() can only have an x or y aesthetic.
Created on 2022-04-14 by the reprex package (v2.0.1)
Similar problem in #4566
Just putting a reminder here of this comments, that illustrates why we can't just throw a warning when both x and y are specified. The following is a legitimate use-case where both x and y are used appropriately.
library(ggplot2)
ggplot(mtcars, aes(mpg, factor(cyl))) +
stat_density(
aes(fill = after_stat(density)),
geom = "raster", position = "identity"
)

Created on 2023-02-28 with reprex v2.0.2
In any case, the error message now is much clearer than it was, explaining that y has been dropped in addition to reporting its missingness.
library(ggplot2)
ggplot(diamonds, aes(x, y)) +
geom_density()
#> Warning: The following aesthetics were dropped during statistical transformation: y
#> ℹ This can happen when ggplot fails to infer the correct grouping structure in
#> the data.
#> ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
#> variable into a factor?
#> Error in `geom_density()`:
#> ! Problem while setting up geom.
#> ℹ Error occurred in the 1st layer.
#> Caused by error in `compute_geom_1()`:
#> ! `geom_density()` requires the following missing aesthetics: y
Created on 2023-02-28 with reprex v2.0.2
So I think we may close this issue.