Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: legends for different aesthetics

Tags:

r

ggplot2

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?

enter image description here

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
like image 561
William Zhang Avatar asked Jun 01 '14 00:06

William Zhang


2 Answers

You can do this by adding a new column to each of your data frames to create fill and colour aesthetics to go into the legend. In each case, there's only one category, but putting them inside the aes() gives you the legends you want:

require(ggplot2)

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

x <- seq(-4, 4, 0.01)
df <- data.frame(x=x, y=dnorm(x), colour=rep("Theoretical Density",length(x)))
p <- p + geom_line(data=df, aes(x=x, y=y, colour=line), size=1.5) +
         scale_colour_manual(values="red") + labs(colour="")

enter image description here

like image 75
eipi10 Avatar answered Oct 15 '22 03:10

eipi10


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")

enter image description here

like image 43
MrFlick Avatar answered Oct 15 '22 03:10

MrFlick