user3022875 user3022875 - 2 months ago 20
R Question

how to get a geom_segment show a legend

I have the plot below with 2 segements.

How can I add a legend for the line segments?

Ideally the end result would have 2 legends:


  1. One would be the current "point legend" as it is

  2. The other legend would be a single legend with the red dashed line labeled "segment legend"



Here is the code

set.seed(11)
x = rnorm(100)

y = rnorm(100)

dat = data.frame(x = x, y = y)


ggplot(dat,aes(x=x,y=y)) + geom_point(aes(color="blue") ) +
geom_segment(aes(x = -2, xend = 2, y = 0, yend = 2), color="red", linetype="dashed", size=1.2) +
geom_segment(aes(x = -1, xend = 1, y = -2, yend = -1), color="red", linetype="dashed", size=1.2) +
scale_color_manual(name = "",values = c("blue"),labels="point legend")

Answer
#Generate data
x = rnorm(100)
y = rnorm(100)
dat = data.frame(x = x, y = y)

#Create new variable with same value as desired legend label
dat$cat<-rep('segment legend', 100) 
colnames(dat)<-c("x","y","segment legend") #change column name to legend label

#Plot
ggplot(dat,aes(x=x,y=y)) + geom_point(aes(color="blue") ) +
  geom_segment(aes(x = -2, xend = 2, y = 0, yend = 2, linetype=`segment legend`),
     color="red", size=1.2) + #move linetype= to inside aesthetics
  geom_segment(aes(x = -1, xend = 1, y = -2, yend = -1, linetype=`segment legend`), 
     color="red", size=1.2) + #move linetype= to inside aesthetics
  scale_color_manual(name = "",values = c("blue"),labels="point legend")+ 
  scale_linetype_manual("segment legend",values=c("segment legend"=2))+
  theme(legend.title=element_blank())

enter image description here