Pedro BP
Pedro BP

Reputation: 73

Put images with text as ticklabels with ggplot2

How can I put local image files as tickslabels and the country name under the flag using ggplot2?

I would like to achive something like this:

enter image description here

The data looks like:

countries = c("Norway", "Spain", "Germany", "Canada", "China")
values = c(10, 20, 30, 22, 19)

Thanks in advance!

Upvotes: 2

Views: 682

Answers (1)

mabreitling
mabreitling

Reputation: 606

Quite sure, the ggtext solution is way easier. Just for completeness, you could also do the following. Brings some additional dependencies though:

library(cowplot)
library(ggplot2)
library(magick)
df <- data.frame(countries = c("Norway", "Spain", "Germany", "Canada", "China"),
                 values = c(10, 20, 30, 22, 19))
p <- ggplot(df, aes(x = countries, y = values))+
  geom_bar(stat = "identity")+
  theme_bw()

pimage <- axis_canvas(p, axis = 'x')+
  cowplot::draw_image("https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Flag_of_Canada_%28Pantone%29.svg/320px-Flag_of_Canada_%28Pantone%29.svg.png", x = 0.5, scale = 0.5)+
  cowplot::draw_image("https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Flag_of_the_People%27s_Republic_of_China.svg/640px-Flag_of_the_People%27s_Republic_of_China.svg.png", x = 1.5, scale = 0.5)+
  cowplot::draw_image("https://upload.wikimedia.org/wikipedia/commons/thumb/b/ba/Flag_of_Germany.svg/320px-Flag_of_Germany.svg.png", x = 2.5, scale = 0.5)+
  cowplot::draw_image("https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Flag_of_Norway.svg/320px-Flag_of_Norway.svg.png", x = 3.5, scale = 0.5)+
  cowplot::draw_image("https://upload.wikimedia.org/wikipedia/en/thumb/9/9a/Flag_of_Spain.svg/320px-Flag_of_Spain.svg.png", x = 4.5, scale = 0.5)
  

ggdraw(insert_xaxis_grob(p, pimage, position = "center"))

enter image description here

Upvotes: 6

Related Questions