rggplot2ggimage

Adding jitter to ggimage geom_image() plots when they overlap


Let's take this example of displaying images instead of points on a ggplot.

set.seed(2017-02-21)
d <- data.frame(x = rnorm(10),
                y = rnorm(10),
                image = sample(c("https://www.r-project.org/logo/Rlogo.png",
                                 "https://jeroenooms.github.io/images/frink.png"),
                               size=10, replace = TRUE)
)
# plot2
ggplot(d, aes(x, y)) + geom_image(aes(image=image), size=.08)

I need to modify the code so that it adds some distance/jitter once the images overlap (or are closer to each other based on x,y). Is that possible without too complicated workarounds?


Solution

  • Try position = position_jitter():

    (You can set a seed in position_jitter for reproducibility if needed.)

    library(ggplot)
    library(ggimage)
    
    set.seed(2)
    d <- data.frame(
      x = rnorm(10),
      y = rnorm(10),
      image = sample(
        c(
          "https://www.r-project.org/logo/Rlogo.png",
          "https://jeroenooms.github.io/images/frink.png"
        ),
        size = 10,
        replace = TRUE
      )
    )
    
    ggplot(d, aes(x, y)) +
      geom_image(aes(image = image), size = .08, position = position_jitter(width = 0.2))
    

    enter image description here