Search code examples
rggplot2ggtext

Adding images below x-axis labels in ggplot2


I have this plot:

my plot

Which has been produced with this code chunk based on an old TidyTuesday dataset, Astronaut.

library(tidyverse)
library(ggplot2)
library(ggtext)

astro_Q2_final %>%
  ggplot(aes(x = reorder(nationality, proportion), y = proportion)) +
  geom_col() +
  theme_minimal() +
  geom_text(aes(label = round(proportion, 3)), position = position_dodge(width = 0.9), 
            vjust = -0.25) +
  labs(title = "Proportion of Space Travellers who are Female, by Nationality",
       x = "Nationality",
       y = "Proportion of Female Astronauts")

The data itself is quite simple - character variable of nationality on the x-axis, and an integer variable corresponding to a worked-out proportion on the y. All I want to do is add images of the flags of the nationalities on the x-axis above the country names. I have tried this photo alignment with graph in r but with no luck; I think it's something to do with the fact that Claus Wilke creates the data object with the expand.grid function - I can't seem to translate what he's doing to what I need to do with my plot/data. Any help would be much appreciated.

The data can be found here https://raw.githubusercontent.com/gjpstrain/astro/main/data.csv

So I've had another look at the ggtext documentation and have included this:

labels <- c(
  U.S.S.R/Russia = "<img src = 'Russia.png' width = 100' /><br>USSR/Russia",
  China = "<img src = 'China.jpg' width = '100' /><br>China",
  Italy = "<img src = 'Italy.png' width = '100' /><br>Italy",
  France = "<img src = 'France.jpg' width = '100' /><br>France",
  U.S = "<img src = 'US.png' width = '100' /><br>US",
  Japan = "<img src = 'Japan.png' width = '100' /><br>Japan",
  Canada = "<img src = 'Canada.png' width = '100' /><br>Canada",
  U.K = "<img src = 'UK.png' width = 100' /><br>UK",
  Korea = "<img src = 'South-Korea.jpg' width = '100' /><br>Korea")

However when I try this:

astro_Q2_final %>%
  ggplot(aes(x = reorder(nationality, proportion), y = proportion)) +
  geom_col() +
  scale_x_discrete(name = NULL,
                   labels = labels)

I get this


Solution

  • Load library ggtext and add this line in the last

    
    astro_Q2_final %>%
      ggplot(aes(x = reorder(nationality, proportion), y = proportion)) +
      geom_col() +
      scale_x_discrete(name = NULL,
                       labels = labels) +
      theme(axis.text.x = ggtext::element_markdown())
    

    You should get the desired visual, if the image-links are correct.