I can't seem to get my legend labels and colours to match correctly in ggplot2. I have some geom_segments that I don't want to include in the legend. I have tried various options and none work. None of the existing questions seem to deal with the issue of not labelling some elements on the plot, so maybe that is adding complexity. The code is below:
library("distr")
library("ggplot2")
Percent_values<-c(0.5,0.75,0.9,0.95,0.995,0.999)
Dist1_mean=20219
Dist1_CV=3235/20219
Dist1_SDEV<-Dist1_mean*Dist1_CV
Dist1_parm2<-sqrt(log(1+Dist1_CV^2))
Dist1_parm1<-log(Dist1_mean)-(Dist1_parm2^2)/2
Dist1_quant<-qlnorm(Percent_values,meanlog=Dist1_parm1,sdlog=Dist1_parm2)
#Now draw CDF with vertical line at mean, median and chosen percentile
a1<-stat_function(fun =
plnorm,args=list(meanlog=Dist1_parm1,sdlog=Dist1_parm2),geom="line",
colour="blue",size=1.25)
lowerx<-0
upperx<-1.1*Dist1_quant[6]
plot1<-ggplot(data.frame(x = c(lowerx, upperx)), aes(x = x))+a1
plot1<-
plot1+scale_x_continuous(name="Value")+scale_y_continuous(name="Cumulative
probability")
#add mean vertical line and associated horizontal line to axis
mean_yvalue<-plnorm(Dist1_mean,meanlog=Dist1_parm1,sdlog=Dist1_parm2)
plot1<-plot1+geom_segment(aes(x=Dist1_mean,y=0,
xend=Dist1_mean,yend=mean_yvalue,colour="red"),size=1.25)
plot1<-
plot1+geom_segment(aes(x=0,y=mean_yvalue,xend=Dist1_mean,
yend=mean_yvalue,colour="red"),size=1.25,linetype="dotted",show.legend =
FALSE)
#and 75th percentile
perc<-0.75
p75<-Dist1_quant[2]
plot1<-
plot1+geom_segment(aes(x=p75,y=0,xend=p75,
yend=perc,colour="green"),size=1.25)
plot1<-plot1+geom_segment(aes(x=0,y=perc,xend=p75,
yend=perc,colour="green"),size=1.25,linetype="dotted",show.legend = FALSE)
#and 99.5th
perc2<-0.995
p995<-Dist1_quant[6]
plot1<-
plot1+geom_segment(aes(x=p995,y=0,xend=p995,
yend=perc2,colour="orange"),size=1.25)
plot1<-
plot1+geom_segment(aes(x=0,y=perc2,xend=p995,
yend=perc2,colour="orange"),size=1.25,linetype="dotted",show.legend = FALSE)
plot1<-plot1+ggtitle("Cumulative density function of estimated future claims
outgo")+
scale_colour_discrete(name="", labels=c("Lognormal", "Mean","75th
%ile","99.5th %ile"))
plot1
This produces a chart (that I can't seem to load for some reason) which a) only has three legend items ("Lognormal", "Mean" and "75th %ile") when I want four (additionally "99.5th %ile" added to these three) and the three items are coloured red, green and blue, respectively, whereas I want Lognormal as blue, Mean as red, 75th as green and 99.5th as orange. The dotted lines should remain on the plot, but not appear in the legend.
What am I doing wrong? Presumably it is something to do with aesthetics and "scale_colour_discrete", but I can't work out what to do. Any help would be much appreciated.
Thanks.