Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates in two ggplot legend

Tags:

r

legend

ggplot2

I'm using ggplot2 in R and have a manual scale for colour (variable1) and line type (variable2). One of the levels is the same for both types and I would just like it to appear in a plain line and therefore disappear from the variable2 legend.

See minimal code below.

enter image description here

require(ggplot2)

data_0 <- expand.grid(x=1:2, 
    variable1=c("nothing", "A", "B"),
    variable2=c("nothing", "positif", "negatif") 
)
data <- subset(data_0, !((variable1=="nothing" & variable2 != "nothing") |
    (variable2=="nothing" & variable1 != "nothing")))
data$y <- rep(1:5, each = 2)

ggplot(data=data, aes(x=x, y=y, colour = variable1, lty = variable2))+
    geom_line(size=1.5)+
    theme_bw()+
    theme(legend.position="bottom")+
    scale_linetype_manual(values = c(1,3,5))
like image 593
PerrySun Avatar asked Dec 22 '15 17:12

PerrySun


1 Answers

You were very close. You need to specify breaks to scale_linetype_manual:

library(ggplot2)

ggplot(data=data, aes(x=x, y=y, colour = variable1, lty = variable2))+
  geom_line(size=1.5)+
  theme_bw()+
  theme(legend.position="bottom") +
  scale_linetype_manual(breaks = c("positif", "negatif"), values = c(1, 3, 5))

enter image description here

like image 186
jeremycg Avatar answered Nov 09 '22 23:11

jeremycg