ggplot2: legends for different aesthetics

ggplot2, r

Solution

Without changing your data at all, you can specify literal `aes()` values that you can define later via manual scales.

df <- data.frame(x=rnorm(10^4))
p <- ggplot(df, aes(x=x)) + geom_histogram(aes(y=..density.., fill="samples"), 
    alpha=0.8, colour="black", width=0.2)
p <- p+scale_fill_manual("",breaks="samples", values="steelblue")

x <- seq(-4, 4, 0.01)
df <- data.frame(x=x, y=dnorm(x))
p <- p + geom_line(data=df, aes(x=x, y=y, colour="theory"), size=1.5)
p <- p+scale_color_manual("",breaks="theory", values="red")

Problem

I first plot histogram for a group of simulated data and fill the bars with one colour. Then I add the line of the density function from which the data was simulated from and make the line with a different colour. Now I want use legends to show one colour (the fill colour of the histogram) is for samples whereas the other (the colour of the line) is for theoretical density. How can I achieve this? The code is as follows ``` require(ggplot2) df <- data.frame(x=rnorm(10^4)) p <- ggplot(df, aes(x=x)) + geom_histogram(aes(y=..density..), fill='steelblue', colour='black', alpha=0.8, width=0.2) x <- seq(-4, 4, 0.01) df <- data.frame(x=x, y=dnorm(x)) p <- p + geom_line(data=df, aes(x=x, y=y), colour='red', size=1.5) p ```

Original source