R: Density plot with colors by group?
<p>I have data from 2 populations.
I'd like to get the histogram and density plot of both on the same graphic.
With one color for one population and another color for the other one.</p>

<p>I've tried this (example):   </p>

<pre><code>library(ggplot2)
AA &lt;- rnorm(100000, 70,20)
BB &lt;- rnorm(100000,120,20)

valores &lt;- c(AA,BB)
grupo &lt;- c(rep("AA", 100000),c(rep("BB", 100000)))
todo &lt;- data.frame(valores, grupo)


ggplot(todo, aes(x=valores, fill=grupo, color=grupo)) +
  geom_histogram(aes(y=..density..), binwidth=3)+  geom_density(aes(color=grupo))
</code></pre>

<p>But I'm just getting a graphic with a single line and a single color.
<a href="https://i.stack.imgur.com/7rsoA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7rsoA.png" alt="enter image description here"></a></p>

<p>I would like to have different colors for the the two density lines. And if possible the histograms as well.</p>

<p>I've done it with ggplot2 but base R would also be OK.</p>

<p>or I don't know what I've changed and now I get this:   </p>

<pre><code>ggplot(todo, aes(x=valores, fill=grupo, color=grupo)) + 
geom_histogram( position="identity", binwidth=3, alpha=0.5)+ 
geom_density(aes(color=grupo))
</code></pre>

<p>but the density lines were not plotted.
<a href="https://i.stack.imgur.com/hVcXb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hVcXb.png" alt="enter image description here"></a></p>

<p>or even strange things like
<a href="https://i.stack.imgur.com/gG9J4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gG9J4.png" alt="enter image description here"></a></p>