Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何获得显示图例的几何图形段_R_Ggplot2 - Fatal编程技术网

R 如何获得显示图例的几何图形段

R 如何获得显示图例的几何图形段,r,ggplot2,R,Ggplot2,我有下面的2段图 如何为线段添加图例 理想情况下,最终结果有两个图例: 一个是当前的“点图例” 另一个图例是带有红色虚线的单个图例,标记为“段图例” 这是代码 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段图

如何为线段添加图例

理想情况下,最终结果有两个图例:

  • 一个是当前的“点图例”
  • 另一个图例是带有红色虚线的单个图例,标记为“段图例”
  • 这是代码

    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")
    
    生成数据 x=rnorm(100) y=rnorm(100) dat=数据帧(x=x,y=y) #创建与所需图例标签具有相同值的新变量 dat$猫
    #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())