jlhoward
jlhoward

Reputation: 59345

(ggplot) in stat_density, aes sometimes does not map variables from default dataset

Trying to understand how ggplot mapping works…

Consider data table dt with two columns:

group:  data grouping variable [a, b, … e]
values: the data [here, N(x,1) where x depends on group]

The following generates a sample dataset.

library(data.table)
set.seed(333)
dt  <- data.table(group=rep(letters[1:5],each=20))
dt[,values:=rnorm(100,mean=as.numeric(factor(group)))]

The following generates density plots for each group scaled to (0,1).

ggp <- ggplot(dt)      # establish dt as the default dataset
ggp + stat_density(aes(x=values, color=group, y=..scaled..), 
                   geom="line", position="identity")

The following generates density plots with scale changed from (0,1) to (-25,+25).

ggp + stat_density(aes(x=values, color=group, y=-25+50*..scaled..), 
                   geom="line", position="identity")

But the following generates and error:

ggp + stat_density(aes(x=values, color=group, y=min(values)+diff(range(values))*..scaled..), 
                   geom="line", position="identity")
Error in eval(expr, envir, enclos) : object 'values' not found

My question is: why does aes correctly map “values” to dt in x=values, but not in y=… ?

NB: The reason I am trying to do this is to put density plots in the diagonal facets in a scatterplot matrix. And yes, I know there are about 5 different ways to generate scatterplot matrices in ggplot.

Thanks in advance to anyone who can help.

Upvotes: 1

Views: 1319

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98429

It seems that stat_density() can only use values of x and y for calculation. So if you need scale data by range of values variable then you can write x instead of values because values are already mapped to x.

ggplot(dt)+stat_density(aes(x=values, color=group, y=min(x)+diff(range(x))*..scaled..), 
                        geom="line", position="identity")

enter image description here

Upvotes: 3

Related Questions