rggplot2tidyversepie-chartggimage

Using ggimage to add images to labels in R


Is there a way to use geom_image to replace text labels to images in a pie chart?

I tried using the code below.

However, the images aren't in the same position as the labels. (I included the labels to show where the images should go but I want to remove the text labels and replace them with the images)

library(tidyverse)
library(ggplot2)
library(ggimage)

# Sample data
labels <- c("Category 1", "Category 2")
values <- c(20, 80)
# Create a data frame
df <- data.frame(labels, values)

df$image <- 'https://www.r-project.org/logo/Rlogo.png'


# Create the pie chart
ggplot(df, aes(x = "", y = values, fill = labels)) +
  geom_bar(stat = "identity", width = 1) +
  coord_polar("y", start = 0) +
  theme_void() +
  geom_text(aes(y = values, label = labels), color = "white", size=5, 
            position = position_stack(vjust = 0.5)) +
  theme(legend.position = "none") +
  geom_image(aes(image=image)) +
    scale_fill_brewer(palette="Set1") 

image I have seen others do something similar using ggtext and other packages but was wondering if ggimage has the capacity to do this.


Solution

  • It always a matter of the position (or the grouping). (; To place the images at the same position as the labels you have to use the same position= for geom_image as for geom_text:

    library(tidyverse)
    library(ggplot2)
    library(ggimage)
    
    # Sample data
    labels <- c("Category 1", "Category 2")
    values <- c(20, 80)
    # Create a data frame
    df <- data.frame(labels, values)
    
    df$image <- "https://www.r-project.org/logo/Rlogo.png"
    
    
    # Create the pie chart
    ggplot(df, aes(x = "", y = values, fill = labels)) +
      geom_bar(stat = "identity", width = 1) +
      coord_polar("y", start = 0) +
      theme_void() +
      geom_text(aes(y = values, label = labels),
        color = "white", size = 5,
        position = position_stack(vjust = 0.5)
      ) +
      theme(legend.position = "none") +
      geom_image(aes(image = image), position = position_stack(vjust = 0.5)) +
      scale_fill_brewer(palette = "Set1")