how to get a geom_segment show a legend

后端 未结 1 1592
梦谈多话
梦谈多话 2021-01-20 23:29

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条回答
  • 2021-01-20 23:29
    #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())
    

    0 讨论(0)
提交回复
热议问题