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:
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")
#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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With