Reputation: 75
I've searched the interwebs hard for why I cannot add a legend to my 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 I do this, I get nothing, no errors in the console and no legend on the plot. Would someone please tell me what 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")
Upvotes: 1
Views: 3922
Reputation: 15937
Legends are drawn for aesthetics. Since colour
is not an aesthetic in your case, there is no legend. The trick is to convert your data from wide format (where every type of data has its own column) to long format (where there is a column indicating the data type and a column giving the corresponding value). This is done as follows:
library(reshape2)
plot.data <- melt(input_csv,
id="R_OD_MONTH",measure=c("DAMWAMT","SCALED_PERCENT_MW"))
melt
returns a data frame in long format with the column indicating the data type called variable
and the column with the values called value
.
Now you can let ggplot pick the colours by mapping the 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 two lines show, how you can add a plot title, change the axis labels and the legend title (labs()
), and change the labels in the legend (scale_colour_discrete
).
Upvotes: 2