2

I have a dataframe that consists of 5 vectors:

name <- c("a", "a", "b", "b", "b")
game <- c(1, 2, 1, 2, 3)
pts <- c(3, 6, 1, 6, 7) 
cum_pts <- c(3, 9, 1, 7, 14)
image <- (image1, image1, image2, image2, image2)

df <- data.frame(name, game, pts, cum_pts, image)

I want to make a line plot of the two different values of "name", with the image associated with each name at the very end of the respective lines.

I can do that with this code, where I use geom_image for each associated image:

df %>%
  ggplot(aes(x = game, y = cum_pts, group = name)) +
  geom_line() +
  geom_image(data = filter(df, name == "a"), aes(x = max(game), y = max(cum_pts), image = pics), size = 0.08) +
  geom_image(data = filter(df, name == "b"), aes(x = max(game), y = max(cum_pts), image = pics), size = 0.08)

and it gives me this, which is what I want for this df:

line plot with images at end

Ultimately my dataframe will consist of many more names than just 2, and having to use a separate geom_image line for each name seems inefficient. Is there any way I can just use one line of code for all the images that will be placed at the end of their respective lines?

stefan
  • 90,330
  • 6
  • 25
  • 51

1 Answers1

4

There is no need to filter your df for each name and add the images one by one. Instead you could use a dataframe with one row per name and add the images with one call to geom_image. In my code below I create the df for the images using dplyr::slice_max to pick the row with the max(game) for each name:

library(ggplot2)
library(ggimage)
library(dplyr)

image1 <- "https://www.r-project.org/logo/Rlogo.png"
image2 <- "https://ggplot2.tidyverse.org/logo.png"

df_image <- df |> 
  group_by(name) |> 
  slice_max(order_by = game, n = 1)

ggplot(df, aes(x = game, y = cum_pts, group = name)) + 
  geom_line() +
  geom_image(data = df_image, aes(x = game, y = cum_pts, image = image), size = 0.08)

stefan
  • 90,330
  • 6
  • 25
  • 51