Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing ggplot2: Create faceted scatterplot with scaled and moved density
    text
    copied!<p>I would like to plot some data as a scatter plot using facet_wrap, while superimposing some information such as a linear regression and the density. I managed to do all that, but the density values are out of proportion with respect to my points, which is a normal thing since these points are far away. Nevertheless, I'd like to scale and move my density curve so that it is clearly visible; I don't care about it's real values but more about its shape.</p> <p>Here is an exaggerated minimum working example of what I have:</p> <pre><code>set.seed(48151623) mydf &lt;- data.frame(x1=rnorm(mean=5,n=100),x2=rnorm(n=100,mean=10),x3=rnorm(n=100,mean=20,sd=3)) mydf$var &lt;- mydf$x1 + mydf$x2 * mydf$x3 mydf.wide &lt;- melt(mydf,id.vars='var',measure.vars=c(1:3)) ggplot(data=mydf.wide,aes(x=value,y=var)) + geom_point(colour='red') + geom_smooth(method='lm') + stat_density(aes(x=value,y=..scaled..),position='identity',geom='line') + facet_wrap(~variable,scale='free_x') </code></pre> <p>Which results in: <img src="https://i.stack.imgur.com/73gr6.png" alt="example of current plot"></p> <p>What I would like resembles to this ugly hack:</p> <pre><code>stat_density(aes(x=value,y=..scaled..*100+200),position='identity',geom='line') </code></pre> <p>Ideally, I would use <code>y=..scaled..* diff(range(value)) + min(value)</code> but when I do this I get an error saying that 'value' was not found. I suspect the problem is related to the faceting, but I would prefer to keep my facets.</p> <p>How can I scale and move the density curve in this case?</p> <p><img src="https://i.stack.imgur.com/kNS4x.png" alt="cool result but ugly hack"></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload