rggplot2geom-vline

Wrong legend in ggplot output


The output of this code gives a distribution and two vertical lines, one red and one blue. But in the legend the blue line is marked "red" and vice versa. What might be the reason? Distribution and 2 vertical lines

variances <- apply(matrix(rexp(40*1000,0.2),1000),1,var) 
hist(variances)
v_theo <- 45 ## need to define v_theo
g <- ggplot(data.frame(x=variances), aes(x = x)) 
g <- g + geom_density(alpha=0.2,size=1,fill="red")
g <- g + geom_vline(aes(xintercept = mean(variances),color="red"), size=1) 
g <- g + geom_vline(aes(xintercept = (v_theo),color="blue"), size=1) 
g

Solution

  • That's because the colors are mapped by the aes function. If you want to map them manually, you could either take them out of the aes like this

    variances <- apply(matrix(rexp(40*1000,0.2),1000),1,var) 
    hist(variances)
    g <- ggplot(data.frame(x=variances), aes(x = x)) 
    g <- g + geom_density(alpha=0.2,size=1,fill="red")
    g <- g + geom_vline(aes(xintercept = mean(variances)), color="red", size=1) 
    g <- g + geom_vline(aes(xintercept = (v_theo)), color="blue", size=1) 
    g
    

    You'll lose the legen by doing this though. If you want the legend, you can use scale_color_manual to fix the order of the colors.

    variances <- apply(matrix(rexp(40*1000,0.2),1000),1,var) 
    hist(variances)
    g <- ggplot(data.frame(x=variances), aes(x = x)) 
    g <- g + geom_density(alpha=0.2,size=1,fill="red")
    g <- g + geom_vline(aes(xintercept = mean(variances),color="red"), size=1) 
    g <- g + geom_vline(aes(xintercept = (v_theo),color="blue"), size=1) 
    g <- g + scale_color_manual(values = c("blue", "red"))
    g