rggplot2legendggfortify

Problems adding legend to ggplot2 + ggfortify


I'm having troubles using

scale_colour_manual 

function of ggplot. I tried

guide = "legend" 

to force legend appears, but it doesn't work. Rep code:

library(ggfortify)
library(ggplot2)
p  <- ggdistribution(pgamma, seq(0, 100, 0.1), shape = 0.92, scale = 22, 
                     colour = 'red')
p2 <- ggdistribution(pgamma, seq(0, 100, 0.1), shape = 0.9, scale = 5, 
                     colour = 'blue', p=p)

p2 + 
theme_bw(base_size = 14) +
theme(legend.position ="top") +
xlab("Precipitación") +
ylab("F(x)") +
scale_colour_manual("Legend title", guide = "legend", 
                      values = c("red", "blue"), labels = c("Observado","Reforecast")) +
ggtitle("Ajuste Gamma")

enter image description here


Solution

  • A solution with stat_function:

    library(ggplot2)
    library(scales)
    
    cols <- c("LINE1"="red","LINE2"="blue")
    df <- data.frame(x=seq(0, 100, 0.1))
    ggplot(data=df, aes(x=x)) + 
    stat_function(aes(colour = "LINE1"), fun=pgamma, args=list(shape = 0.92, scale = 22)) +
    stat_function(aes(colour = "LINE2"), fun=pgamma, args=list(shape = 0.9, scale = 5)) +
    theme_bw(base_size = 14) +
    theme(legend.position ="top") +
    xlab("Precipitación") +
    ylab("F(x)") +
    scale_colour_manual("Legend title", values=c(LINE1="red",LINE2="blue"),
                        labels = c("Observado","Reforecast")) +
    scale_y_continuous(labels=percent) +
    ggtitle("Ajuste Gamma")
    

    enter image description here