r - ggplot2 manual legend not displaying -
i've searched interwebs hard why cannot add legend ggplot2.
g.2plot1<-ggplot(input_csv,aes(x=r_od_month,y=damwamt))+ geom_line(colour = "black")+ geom_line(aes(x=r_od_month,y = scaled_percent_mw), colour = "blue") + scale_colour_manual(name="legend", values = c("black", "blue")) + scale_linetype_manual(name="legend", values = c("dashed", "dotted")) g.2plot1
when this, nothing, no errors in console , no legend on plot. please tell me i'm dong wrong?
dput(head(input_csv)) structure(list(od_month = c("12/1/2010", "1/1/2011", "2/1/2011", "3/1/2011", "4/1/2011", "5/1/2011"), damwamt = c(219869.89, 214323.24, 193976.03, 249174.62, 213529.32, 226318.98), nb_made_whole = c(39l, 37l, 26l, 45l, 74l, 64l), nb_consid_mw = c(818l, 871l, 874l, 831l, 1060l, 1418l), percent_mw = c(0.0404, 0.048, 0.0371, 0.0616, 0.0604, 0.0525), scaled_percent_mw = c(151898.635570388, 183223.057973301, 138297.241632282, 239277.287536408, 234331.326104369, 201770.413343447 ), r_od_month = structure(c(14944, 14975, 15006, 15034, 15065, 15095), class = "date")), .names = c("od_month", "damwamt", "nb_made_whole", "nb_consid_mw", "percent_mw", "scaled_percent_mw", "r_od_month" ), row.names = c(na, 6l), class = "data.frame")
legends drawn aesthetics. since colour
not aesthetic in case, there no legend. trick convert data wide format (where every type of data has own column) long format (where there column indicating data type , column giving corresponding value). done follows:
library(reshape2) plot.data <- melt(input_csv, id="r_od_month",measure=c("damwamt","scaled_percent_mw"))
melt
returns data frame in long format column indicating data type called variable
, column values called value
.
now can let ggplot pick colours mapping column variable
on colour:
ggplot(plot.data,aes(x=r_od_month,y=value,colour=variable)) + geom_line() + labs(title="my plot",x="x-axis",y="y-axis",colour="colours") + scale_colour_discrete(labels=c("this","that"))
the last 2 lines show, how can add plot title, change axis labels , legend title (labs()
), , change labels in legend (scale_colour_discrete
).
Comments
Post a Comment