Home > Blockchain >  Adding image in title spaces using ggplot2
Adding image in title spaces using ggplot2

Time:12-22

I am a data scientist who is relatively new to R. In many of the data vizzes I generate, stakeholders usually prefer to have some "branding elements" when I create charts and figures. Within ggplot2, fonts and color schemes appear fairly simple and straightforward. What I am struggling with is to include branding images outside of the chart area. More specifically, I am trying to produce the image below without considering fonts and color schemes. Ideally, I could shift the title and subtitle over several centimeters to the right, and snap an image just to the left of it.

Is there any advice, or sample solution anyone can provide?

Figure I am trying to create

Here is the base code I am working with. I am using data within ggplot2, and the image is from the web.

library(ggplot2)
library(tidyverse)

# The image I am interested in embedding in ggplot figure
myurl = "https://pngimg.com/uploads/bmw_logo/bmw_logo_PNG19705.png"
z = tempfile()
download.file(myurl,z,mode="wb")

sampleImage = png::readPNG(z) %>%
  rasterGrob(interpolate = TRUE)

# Sample ggplot plot where I would like to embed image in "title spaces"
# image is saved as "sampleImage", I do not know how to integrate it below
plot = ggplot(mtcars, aes(wt, mpg))   
  geom_point()  
  labs(title = "Primary Title",
       subtitle = "Secondary Title") 


plot

What I have created so far

CodePudding user response:

You could use annotation_custom to annotate your image and use clip = "off" in coord_cartesian to place the image outside of the plot area. You could slightly place the title and subtitle to the right like this:

library(ggplot2)
library(tidyverse)
library(grid)

# The image I am interested in embedding in ggplot figure
myurl = "https://pngimg.com/uploads/bmw_logo/bmw_logo_PNG19705.png"
z = tempfile()
download.file(myurl,z,mode="wb")

sampleImage = png::readPNG(z) %>%
  rasterGrob(interpolate = TRUE)

# Sample ggplot plot where I would like to embed image in "title spaces"
# image is saved as "sampleImage", I do not know how to integrate it below
plot = ggplot(mtcars, aes(wt, mpg))   
  geom_point()  
  labs(title = "Primary Title",
       subtitle = "Secondary Title")  
  coord_cartesian(clip = 'off')  
  annotation_custom(sampleImage, x = 1, y = 38, ymax = 35.5, xmax = 1.8)  
  theme(plot.title = element_text(hjust = 0.07),
        plot.subtitle = element_text(hjust = 0.07))

plot

Created on 2022-12-21 with reprex v2.0.2

  • Related