r - ggplot2 - highlighting selected points and strange behavior

前端 未结 3 1584
误落风尘
误落风尘 2020-12-03 01:57

I want to highlight selected points and encountered some strange behaviour. First some dummy data:

a <- 1:50
b <- rnorm(50)
mydata <- data.frame(a=a         


        
相关标签:
3条回答
  • 2020-12-03 02:08

    If your data is different between different layers, then you need to specify the new data for each layer.

    You do this with the data=... argument for each geom that needs different data:

    set.seed(1)
    mydata <- data.frame(a=1:50, b=rnorm(50))
    ggplot(mydata,aes(x=a,y=b)) + 
      geom_point(colour="blue") +
      geom_point(data=mydata[10:13, ], aes(x=a, y=b), colour="red", size=5)
    

    enter image description here

    0 讨论(0)
  • 2020-12-03 02:08

    Another option adding the conditions for both attributes, colour and size, inside geom_point. Then we control manually those using scale_colour_manual and scale_size_manual respectively.

    set.seed(1)
    mydata <- data.frame(a = 1:50, b = rnorm(50))
    ggplot(mydata) + 
      geom_point(aes(x = a, y = b, colour = a > 9 & a < 14, size = a > 9 & a < 14)) + 
      scale_colour_manual(values = c("blue", "red")) + 
      scale_size_manual(values =c(1, 4))+
      theme(legend.position = "none")
    

    0 讨论(0)
  • 2020-12-03 02:10

    Another solution with gghighlight:

    a <- 1:50
    b <- rnorm(50)
    mydata <- data.frame(a=a,b=b, type = sample(letters, 50, replace = T))
    
    library(gghighlight)
    gghighlight_point(mydata, aes(x=a, y=b), label_key = type, 
                      a <= 14 & a >= 10 & b >= 0 , col="red")
    
    0 讨论(0)
提交回复
热议问题