Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a geom_segment show a legend

Tags:

r

ggplot2

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")

enter image description here

like image 235
user3022875 Avatar asked Feb 07 '23 03:02

user3022875


1 Answers

#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

like image 156
Cyrus Mohammadian Avatar answered Feb 09 '23 00:02

Cyrus Mohammadian