选择geom_point和geom_segment的颜色(后者使用条件颜色)

时间:2017-01-30 12:11:08

标签: r plot ggplot2

我一直试图同时绘制来自两个不同变量(作为点)的数据和根据条件采用不同颜色的段。我的数据如下:

    x = rep(rnorm(100),2)
    y = rnorm(200)
    z=rep(c("var1","var2"),each=100)
    dat = data.frame(x = x, y = y,z = z)

现在我绘制点数:

    p1 <- ggplot(dat, aes(x = x,y=y,col=z)) +
          geom_point(stat="identity") 
    plot(p1)

看起来像这样: 没有细分的情节:

enter image description here

现在我包含了段颜色的条件,并再次绘制:

    s="j"

    if(s=="a"){  
       color_line <- "red" 
    }else{ 
       color_line <- "blue"
    }

    p1 <- p1 + 
          geom_segment(show.legend = F,aes(x=1,xend=0,y=0,yend=0,col=color_line)) 

    plot(p1)

带有细分的情节:

enter image description here

如您所见,即使该段应为蓝色,也是红色。而且我不希望任何参考图例中的线条。所以我理想的是:

  1. 该段是我在条件中指定的颜色,并且这些点的颜色既不是蓝色也不是红色。
  2. 图例仅显示数据中变量的名称(“var1”&amp;“var2”)。
  3. 感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

手动设置细分时,请勿将col = color_line放在aes()内。这样做,您的代码就像假设一样。

那是:

p1 <- p1 + geom_segment(show.legend = F,aes(x=1,xend=0,y=0,yend=0),col=color_line)