replace x axis labels with images

Hi. The following creates a small column chart. Suppose I have four small images by President, e.g. lincoln.jpg . How could I replace the x axis names with those images? Thank you.

suppressMessages(library(dplyr))
suppressMessages(library(ggplot2))
df <- data.frame(President = c("Lincoln", "Garfield", "McKinley", "Kennedy"),
Days_in_office = c(1503,199,1654,1036) )

df %>%
ggplot() +
geom_col(mapping=aes(President, y=Days_in_office, fill=President)) +
scale_fill_manual(values=c("blue", "yellow", "red", "black")) +
labs(title="Days in Office Before Presidential Assassination")

Have a look at the ggtext package.

Wow, that is what I am looking for.

However, in running there sample code on the boxplot, I get
Error in function (type, msg, asError = TRUE) :
error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version

Any ideas?

ggtext is what I need. I think I want something like

library(ping)
lincoln <- readPNG("lincoln.png")
labels <- c("", )

library(ggtext)
p <- p +
scale_x_discrete(labels = labels) +
theme(axis.text.x = ggtext::element_markdown())

but this is not getting images as axis text.

I'm getting some issues, but they are firewall ones.

Your reproducible example doesn't work. The library should be png I think, and the object p isn't defined.

This works for me - replace test.png with your lincoln.png.

library(png)
library(ggtext)
library(tidyverse)
lincoln <- readPNG("test.png") # replace with whatever
labels <- c(virginica = "<img src='test.png' width='100' /><br>*virginica*") # replace with whatever


df <- iris %>% 
  filter(Species == "virginica")

ggplot(df, aes(Species, Sepal.Length)) +
  geom_col() +
  scale_x_discrete(labels = labels) +
  theme(axis.text.x = ggtext::element_markdown())

image

Excellent, thank you.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.