Home > Mobile >  Define alpha using ggplot to highlight single points
Define alpha using ggplot to highlight single points

Time:04-15

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.

CodePudding user response:

You could achieve your desired result by mapping your alpha column on the alpha aesthetic and using scale_alpha_identity:

Note 1: I set the number of points to 100 because otherwise it's nearly impossible to see that this approach works.

Note 2: IMHO using opacity is not the best way to highlight one point, especially with a large number of points.

library(ggplot2)
library(data.table)

set.seed(1)

x = rnorm(100, 0, 1)
y = rnorm(100, 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] 

ggplot(dat, aes(x, y, alpha = alpha))   
  geom_point()   
  scale_alpha_identity(guide = FALSE)
#> Warning: It is deprecated to specify `guide = FALSE` to remove a guide. Please
#> use `guide = "none"` instead.

CodePudding user response:

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

  • Related