Search code examples
rggplot2plotgeom

Adding images to R plots using ggplot2 and ggpattern - image is missing?


I am using the ggpattern package in R for the first time and I can't get the image to work in my plot. A simplified version of my code is here:

x = seq(-1.5, 3.5, 0.1)

y = c( rep(1.0, 22), rep(0.2, 12), rep(0.7, 7), rep(1,10))

ref = data.frame(x = x, y = y)

library(dplyr)
library(ggplot2)
library(ggpattern)

coral = system.file("Coral", "coral.jpg", package="ggpattern")

p = ggplot(ref, aes(x = x, y = y))+
scale_y_reverse(lim = c(1, 0))+
theme_classic()+
geom_ribbon_pattern(aes(x = x, ymin = 1, ymax = y),
color = "darkblue",
fill = NA,
size = 1.5,
pattern = 'image',
pattern_type = 'squish',
pattern_filename = coral) +
geom_ribbon(aes(x = x, ymin = 0, ymax = y), fill = "lightblue")

When I run this code, all I get is this: Plot with missing image fill

enter image description here

But with this code, I think the white area under the curve should be filled in with the coral image. Does anyone know what I'm doing wrong here? I have searched StackOverflow and GitHub and cannot find an answer.


Solution

  • I think the problem here is that there is no "coral.jpg" file in the img folder of ggpattern.

    When i edit your code with one of the images present in the folder, it works fine.

    x = seq(-1.5, 3.5, 0.1)
    
    y = c( rep(1.0, 22), rep(0.2, 12), rep(0.7, 7), rep(1,10))
    
    ref = data.frame(x = x, y = y)
    
    library(dplyr)
    library(ggplot2)
    library(ggpattern)
    
    coral = system.file("img", "magpie.jpg", package="ggpattern")
    
    p = ggplot(ref, aes(x = x, y = y))+
        scale_y_reverse(lim = c(1, 0))+
        theme_classic()+
        geom_ribbon_pattern(aes(x = x, ymin = 1, ymax = y),
                            color = "darkblue",
                            fill = NA,
                            size = 1.5,
                            pattern = 'image',
                            pattern_type = 'squish',
                            pattern_filename = coral) +
        geom_ribbon(aes(x = x, ymin = 0, ymax = y), fill = "lightblue")
    
    p
    

    enter image description here

    enter image description here