1

I feel like I am asking a totally silly question, but I can't force ggplot to show the legend for lines colours.

The thing is that I have two data frames with the same data, just the first data.frame represents new data (plus additional numbers) and the second represents the old data. I am trying to compare new and old data, thus to understand which is which I have to see the legend. I have tried to use scale_colour_manual, but it still doesn't appear.

I have read a number of various answers on similar questions and non of them worked or led to a better. You can see a simple example of my problem below:

rm(list = ls())
library(ggplot2)

xnew<-3:10
y<-5:12
xold<-4:11
years<-2000:2007
xfact<-rep("x", times=8)
yfact<-rep("y", times=8)

Newdata<-data.frame(indicator=c(xfact,yfact),Years=c(years,years), data=c(xnew,y))
Olddata<-data.frame(indicator=xfact,Years=c(years), data=xold)

graph<-ggplot(mapping=aes(Years, data, group=1)) +
geom_line(,Newdata[Newdata=="x",], size=1.5, colour="lightblue")+
geom_line(,Olddata[Olddata=="x",], size=1.5, colour="orange")+
ggtitle("OLD vs NEW")+
scale_colour_manual(name="Legend", values=c("New"="lightblue", "Old"="orange"))

the result is without the legend.

Thanks for all the help I have already found on this website and thank you in advance for helping to solve this problem.

1 Answer 1

0

Legends are created in ggplot by mapping aesthetics to a single variable. Your mistake is that you're trying to set colors manually in each layer.

Newdata$type <- "New"
Olddata$type <- "Old"

all_data <- rbind(Newdata,Olddata)

ggplot(data = all_data[all_data$indicator == 'x',],aes(x = Years,y = data,colour = type)) +
    geom_line() + 
    ggtitle("OLD vs NEW") +
    scale_colour_manual(name="Legend", values=c("New"="lightblue", "Old"="orange"))

There are countless examples illustrating this basic technique in ggplot here.

Not the answer you're looking for? Browse other questions tagged or ask your own question.