I'm enjoying using tile density plots to represent probability densities. I often use the second (y) dimension to illustrate comparisons of densities between factors, but I'm having trouble introducing a third dimension. I want to use colour to represent the third dimension. How can I do this? (I've tried inserting aes
references to Type
in the example below but they appear to collide with the ..density..
aesthetic.)
Beginning with the following plot,
library(ggplot2)
dz <- data.frame(Type = c(rep("A", 100), rep("B", 100)),
Costs = c(rnorm(100), rnorm(100, 5, 1))
)
ggplot(dz, aes(x = Costs, y = 1)) +
stat_density(aes(fill = ..density..), geom = "tile", position = "identity") +
scale_fill_gradient(low = "white", high = "black")
What I want is a combination of the following. For A
:
and
B
:
If you map fill
to Type
, and alpha
to the density, you get more or less what you want:
ggplot(dz, aes(x = Costs, y = 1, fill=Type)) +
stat_density(aes(alpha=..density..), geom = "tile", position = "identity") +
scale_fill_manual(values=c("red", "blue"))