1

I need to add the legend for some geom_point I am adding in a geom_line graph. The example goes below.

require(dplyr)
require(ggplot2)
set.seed(1111)

My Objects

Sum <- sample(1:50, 10)
year <- c(1990:1999)
index.one <- sample(0:1, 10,replace=TRUE)
index.two <- sample(0:1, 10,replace=TRUE)

df <- data_frame(Sum, year, index.one, index.two)

Graph

graph <- ggplot(df, aes(x=year,y=Sum))+ geom_line() +
geom_point(data=df[df$index.one==1,], aes(x=year, y=Sum), colour="red", 
fill="red", shape=22) +
geom_point(data=df[df$index.two==1,], aes(x=year, y=Sum), colour="blue", 
fill="blue", shape=22) +
scale_x_continuous(breaks = seq(1990,1999, by=1))

graph

I need to add the legend for the blue and red points in the graph.

Thank you!

aosmith
  • 34,856
  • 9
  • 84
  • 118
Tiago Ventura
  • 37
  • 1
  • 6

2 Answers2

2

You don't need to add a geom for each colour. Colour is an aesthetic that you connect to a variable, in your case index.one (or .two but they are confounded).

Your example is a bit more tricky because you added geom_line. No problem, just add the aesthetic to geom_point.

ggplot(df, aes(x=year, y=Sum)) +
  geom_point(aes(colour=as.factor(index.one))) + geom_line() +
  scale_colour_manual(values=c(`1`='blue', `0`='red'))

Additionally, because index.one is numeric, ggplot2 will try to use it as a continuous variable, but it is really a discrete, hence the as.factor.

enter image description here

Edit: I've noticed that you do not have a point at 1995. Simply replace the value in index.one for the corresponding year with NA, and the point will not be plotted. It will not affect the line because that draws it value from a different variable.

MrGumble
  • 5,631
  • 1
  • 18
  • 33
1

This uses tidyr::gather() to create a long data set, then filters the points that it's only plotting the points where value is equal to 1.

library(tidyr)
df1 <- gather(df, index, value, 3:4)
ggplot(df1, aes(x = year, y = Sum)) + 
  geom_line() + 
  geom_point(data = df1 %>% filter(value == 1), 
             aes(colour = index, fill = index), shape = 22) + 
  scale_x_continuous(breaks = seq(1990,1999, by=1)) + 
  scale_fill_manual(values = c("red", "blue")) + 
  scale_colour_manual(values = c("red", "blue"))
jtcies
  • 11
  • 1