I will try to describe my problem using a simplified example. I am trying to plot several densities with ggplot2, something like:
library(reshape2)
library(ggplot2)
set.seed(1)
x <- replicate(5, rnorm(100))
colnames(x) <- paste0("x", 1:5)
ggplot(melt(x), aes(value, color = Var2)) + geom_density()
This works as expected. Now, I would like to add a new variable with a very different scale:
z <- cbind(x, y = rnorm(100) * 50)
ggplot(melt(z), aes(value, color = Var2)) + geom_density()
This produces the expected graph, but not the one I would like to make unfortunately. I would like to keep the original scales of both axes, so that the differences between the first five densities would still be visible, and the density of the new variable would appear as flat.
Is it possible to do this in a simple way? Like telling ggplot to overlay the new density without changing the scaling? Or telling ggplot to ignore a variable when computing the limits of the axes?
I could consider a manual solution that would save the limits of the axes in a first step, and then specify them when the graph is made with the new variable. But that might not be the most elegant solution and might require a lot of extra code. I would prefer avoiding this kind of solution if possible (especially because my case is actually much more complex and implies multiple graphs with facet_wrap()
)
Any suggestions or hints would be most welcome. Many thanks in advance!
PS: To give you more background information, I am trying to plot several posterior distributions against their prior distribution (the flat one). I only have draws from the prior, not its exact density function - otherwise I would just have overlaid this prior with stat_function()
.
coord_cartesian(xlim = c(-4,4))
? - Jon Spring