1
votes

I have to admit that it has been a while since I used ggplot, but this seems a bit silly. Either I am missing something fundamental when trying to make a density plot, or there is a bug in ggplot2 (v3.3.2)

test <- data.frame(Time=rnorm(100),Age=rnorm(100))
ggplot(test,aes(y=Time,x=Age)) + 
  geom_density(aes(y=Time,x=Age))

produces

ggplot(test,aes(y=Time,x=Age)) +

  • geom_density(aes(y=Time,x=Age)) Error: geom_density requires the following missing aesthetics: y

how could the 'y' aesthetic be missing??

2
What's your desired result? If you'd like to plot a 2-dimensional density, you should use geom_density_2d. Otherwise it's either a density over x OR y and you should specify only one.Dave

2 Answers

6
votes

There are two cases when using geom_density(). It depends which stat layer you're specifying:

  1. The standard case is the stat density which makes the geom_density() function compute its y values based on the frequency distribution of the given x values. In this case you must NOT proved a y aesthetic because those are computed behind the curtain.
  2. Then there is a second case, which is yours, and which you have to specify explicitly by changing the stat to identity: This is needed if, for some reason, you've precalculated values which you want to feed directly into the density function.

Your problem arises, if you're mixing case 1) and 2). But I agree, the error message is not really clear, it could be mentioned to make sure that the used stat is the desired one.

library(ggplot2)
test <- data.frame(time = rnorm(100), age = rnorm(100))
#if you want to use precalculated y values you have to change the used stat to identity:
ggplot(test) + 
  geom_density(aes(x = age, y = time), 
               stat = "identity")


# compared to the case with the default value of stat: stat = "density"

ggplot(test) + 
  geom_density(aes(x = age))

Created on 2020-08-04 by the reprex package (v0.3.0)

0
votes

If you want to plot the two variables in the graphic you need to "melt" it first.

test <- data.frame(Time=rnorm(100),Age=rnorm(100))
dt <- data.table(test)
dt_melt <- melt.data.table(dt)
ggplot(dt_melt,aes(x=value, fill=variable)) + geom_density(alpha=0.25)