htmlrggplot2ggtext

How to middle-align text and image in ggplot labels using ggtext and element_markdown?


I'm working on a plot in R, and for each value on the y-axis, I want to display an image alongside the corresponding text. I would like the image and text to be vertically aligned in the center. I'm using ggplot2 along with the element_markdown() function from the ggtext package to include the images.

Here is a simplified version of my code with the output I'm getting (text and image are not aligned):

library(tidyverse)
library(ggtext)

df <- data.frame(logo_html = c("Augsburg<img src='https://raw.githubusercontent.com/luukhopman/football-logos/master/logos/L1/FC%20Augsburg.png' width='20'>", 
                               "Bayern Munich<img src='https://raw.githubusercontent.com/luukhopman/football-logos/master/logos/L1/Bayern%20Munich.png' width='20'>", 
                               "Bochum<img src='https://raw.githubusercontent.com/luukhopman/football-logos/master/logos/L1/VfL%20Bochum.png' width='20'>"), 
                 mean_age = c(24.75, 25.27, 28.08))

df %>% 
  ggplot(aes(x = logo_html, y = mean_age)) +
  geom_bar(stat = "identity", fill = "steelblue") +
  coord_flip() +
  theme_void() +
  theme(
    axis.text.y = ggtext::element_markdown(hjust = 1)
  )

Output

The following is the desired output (text and image are aligned):

enter image description here

Does anyone have suggestions on how I can achieve it? Thank you in advance!


Solution

  • As I already mentioned in my answer on this related post I don't know of any option to center align both the text and the image when using ggtext::element_markdown. Instead, as in the referenced post I would suggest to add the logos using ggtext::geom_richtext:

    library(ggplot2)
    library(ggtext)
    
    df <- data.frame(
      label = c("Augsburg", "Bayern Munich", "Bochum"),
      logo_html = c(
        "<img src='https://raw.githubusercontent.com/luukhopman/football-logos/master/logos/L1/FC%20Augsburg.png' width='20'>",
        "<img src='https://raw.githubusercontent.com/luukhopman/football-logos/master/logos/L1/Bayern%20Munich.png' width='20'>",
        "<img src='https://raw.githubusercontent.com/luukhopman/football-logos/master/logos/L1/VfL%20Bochum.png' width='20'>"
      ),
      mean_age = c(24.75, 25.27, 28.08)
    )
    
    df  |> 
      ggplot(aes(y = label, x = mean_age)) +
      geom_col(fill = "steelblue", width = .75) +
      ggtext::geom_richtext(
        aes(y = label, label = logo_html),
        x = -Inf,
        fill = NA, label.color = NA, hjust = 1
      ) +
      theme_void() +
      theme(
        axis.text.y.left = ggtext::element_markdown(
          size = 10, valign = 1, margin = margin(r = 30, l = 5.5),
          hjust = 1
        )
      ) +
      coord_cartesian(clip = "off")