Reputation: 318
Dataframe:
df <- data.frame('X' = c('a','a','b','b','c','c','d','d'), 'legend' = c('a','b','a','b','c','d','c','d'), 'Y' = c(100,50,50,100,150,100,150,100))
Graph:
ggplot(data=df, aes(x=X, y=Y, group=legend, colour=legend)) +
geom_line(size = 1) +
geom_point(size = 3) +
scale_color_manual(values=c("blue", "red","blue", "red"), labels = c('blue','red')) +
scale_x_discrete(labels = c('Group 1','Group 1','Group 2','Group 2'))
Output:
https://i.sstatic.net/v0QfO.jpg
When I do this the legend reads 'blue', 'red', 'NA', 'NA'. How do I remove the NAs from the legend so it only says 'blue, red'?
Upvotes: 1
Views: 116
Reputation: 14360
You could always set the breaks
inside you scale_color_manual
. Something like this should work:
ggplot(data=df, aes(x=X, y=Y, group=legend, colour=legend)) +
geom_line(size = 1) +
geom_point(size = 3) +
scale_color_manual(values=c("blue", "red","blue", "red"),
labels = c('blue','red'), breaks = c("a", "b")) + #Set the breaks here
scale_x_discrete(labels = c('Group 1','Group 1','Group 2','Group 2'))
We keep only the first two groups since we want to relabel to only have 2 values in the legend red
and blue
Upvotes: 3