Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to add an alpha value within geom_image in ggplot?

Tags:

r

ggplot2

I am currently trying to create a plot that has logos mapping to X and Y coordinates. The goal though is have another set of points with the same logos, but with an alpha value so that the logos are more transparent.

Here is a reproducible example. The goal is to have the logos on the left be transparent.

library(ggimage)
library(tidyverse)
library(RCurl)

Sample_X1 <- c(1,0,2,3,1)
Sample_X2 <- c(4,5,7,4,3)
Sample_Y <- c('A','B','C','D','E')
Logo <- 'https://i1.pngguru.com/preview/233/348/954/numix-circle-for-windows-rstudio-icon-png-icon-thumbnail.jpg'

data <- data.frame(cbind(Sample_X1, Sample_X2, Sample_Y, Logo))

ggplot(data = data) +
  geom_segment(aes(x = Sample_X1, xend = Sample_X2, y = Sample_Y, yend = Sample_Y), size = 1) +
  geom_image(aes(x = Sample_X1, y = Sample_Y, image = Logo), size = .05) +
  geom_image(aes(x = Sample_X2, y = Sample_Y, image = Logo), size = .05) +
  theme_minimal() +
  labs(title = 'Example for Stack Overflow')

Sample Output

Is there a way to accomplish this with ggplot? So far I have only been able to find ways to make background logos transparent, but they aren't able to be mapped to the XY data.

Any help is appreciated!

like image 963
NateWeller Avatar asked Mar 23 '20 19:03

NateWeller


1 Answers

The image_fun parameter can be used to define how the image should be processed. image_fx can be used to set the alpha channel.

library(ggplot2)

transparent <- function(img) {
  magick::image_fx(img, expression = "0.5*a", channel = "alpha")
}

ggplot(data.frame(x = runif(10), y = runif(10)), aes(x, y)) +
  ggimage::geom_image(
    image = system.file("extdata/Rlogo.png", package="ggimage"),
    image_fun = transparent,
    size = 0.3
  )

plot

like image 87
Paul Avatar answered Nov 11 '22 21:11

Paul