简体   繁体   中英

ggplot2: legends for different aesthetics

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

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

在此输入图像描述

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

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM