Home > database >  Adding Logo to R plot dynamically
Adding Logo to R plot dynamically

Time:10-26

library(dagitty)
library(ggplot2)
library(ggdag)

get_jpg <- function(filename) {
  grid::rasterGrob(jpeg::readJPEG(filename), interpolate = TRUE)
    }
logo <- get_jpg("logo.jpg")

ex.1 <- dagitty("dag { 

X <- A -> B <- C -> Y
X <- B -> Y
X -> W -> Y
S-> T -> C
}")

exposures(ex.1) <- 'X'
outcomes(ex.1) <- 'Y'

tidy.1 <- ex.1 %>% 
  tidy_dagitty() %>%
  mutate(label = str_to_upper(name)) 


ggdag(tidy.1 , text = FALSE, use_labels = "label")   theme_dag()  
  theme_light()  
  annotation_custom(logo, xmin = 6.5, xmax = 8.5, ymin = -5, ymax = -8.5)  
  coord_cartesian(clip = "off")  
  theme(plot.margin = unit(c(1, 1, 3, 1), "lines"))

I have this code to put a JPG image within my plot. I understand that the xmin, xmax, ymin ymax coordinates are not aligning. Is there a way where I can display the image on the bottom right of the graph (similar to the ones shown here: https://www.markhw.com/blog/logos)? I want to do this dyanmically if possible without specifying coordinates because I'm not sure how ggdag plots x and y coordinates for the causal graphs.

Thanks!

CodePudding user response:

One option to achieve your desired result would be to position the logo by setting the coordinates via rasterGrob instead of via annotation_cutom. Making use of the example code in the post you linked in my code below I put the R logo on the bottom right. As you can see from the two examples I added this works fine independently of the range of the data and will put the logo always on the same position:

library(tidyverse)

download.file("https://www.r-project.org/logo/Rlogo.png", "logo.png")

get_png <- function(filename, x = unit(0.5, "npc"), y= unit(0.5, "npc"), 
                    width = NULL, height = NULL, gp = grid::gpar()) {
  grid::rasterGrob(png::readPNG(filename), interpolate = TRUE,
                   x = x, y = y, width = width, height = height, gp = gp)
}

species <- starwars %>% 
    count(species) %>% 
    filter(!is.na(species) & n > 1) %>% 
    arrange(-n) %>% 
    mutate(species = factor(species, species))

width = 3
l <- get_png("logo.png", 
             x = unit(1, "npc") - unit(width / 2, "lines"), 
             y = unit(-width, "lines"), 
             width = unit(width, "lines"))

p_fun <- function(x, width = 3) {
  ggplot(x, aes(x = species, y = n))  
    geom_bar(stat = "identity")  
    coord_cartesian(clip = "off")  
    theme_light()  
    theme(plot.margin = unit(c(1, 1, width, 1), "lines"))
}

p_fun(species)  
  annotation_custom(l)

p_fun(filter(species, n > 2))  
  annotation_custom(l)

  • Related