Ggplot2: legends for different aesthetics

First, I draw a histogram for a group of simulated data and fill the bars with one color. Then I add a line to the density function with which the data is modeled, and draw a line with a different color. Now I want to use legends to show one color (histogram fill color) for samples, while another (line color) 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 
+6
source share
2 answers

Without changing the data at all, you can specify literal aes() values, which you can determine later using 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

+6
source

You can do this by adding a new column to each of your data frames to create fill and colour aesthetics to move on to the legend. In each case, there is only one category, but placing them inside 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

+7
source

Source: https://habr.com/ru/post/970134/


All Articles