Search code examples
rggplot2plottransparencyalpha

Define alpha using ggplot to highlight single points


Reproducible code:

library(ggplot2)
library(data.table)

x = rnorm(10000, 0, 1)
y = rnorm(10000, 0, 1)

dat = data.table(x,y)
dat[,id := as.character(1:.N)]

ALPHA = 0.2 

dat[,alpha := ifelse(id == 42, 1, ALPHA)]
alpha2 = unique(dat[,list(id, alpha)])
alpha = alpha2[,alpha]
names(alpha) = dat[,id] 

u = ggplot(dat, aes(x, y, alpha = id)) + geom_point()
u = u + scale_alpha_manual(values = alpha, guide = FALSE) 
u

Output:

output of code

Issue:

The point with id = 42 is not highlighted, and continuous alpha-values are still applied to all observations. I would like to see only the point with id = 42 having an alpha of 1 and all the rest with a fixed value of alpha = 0.2.


Solution

  • Another option is to use annotate. Since the visibility is not very good when using alpha = 0.2, , I colored it red (but would work with an alpha argument too).

    library(ggplot2)
    library(data.table)
    
    x = rnorm(10000, 0, 1)
    y = rnorm(10000, 0, 1)
    
    dat = data.table(x,y)
    dat[,id := as.character(1:.N)]
    
    alphapoint <- 42
    
    ggplot(dat, aes(x, y)) + 
      geom_point(alpha = 0.2) +
      annotate("point",
               dat$x[alphapoint],
               dat$y[alphapoint],
               color = "red",
               size = 4)
    

    enter image description here

    Using alpha:

    ggplot(dat, aes(x, y)) + 
      geom_point(alpha = 0.05) +
      annotate("point",
               dat$x[alphapoint],
               dat$y[alphapoint],
               alpha = 1)
    

    enter image description here