Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert pictures into each individual bar in a ggplot graph

Tags:

r

image

ggplot2

I'm trying to compare different NBA rookies across different stats, and I thought the graph would look great if I could add the player's face at the end of the graph like in the r/dataisbeautiful graphs. My code is currently this:

a3 %>%
  ggplot(aes(x = reorder(Player,
                         PPM),
             y = PPM)) +
  geom_bar(stat = "identity",
           aes(fill = Player)) +
  geom_text(aes(label = PPM), size = 3, position = position_dodge(width = 1),
            hjust = -0.1) +
  coord_flip() +
  theme_minimal() +
  xlab("Player") +
  ylab("Points Per Minute") +
  theme(legend.position = "none")

This is what my graph currently looks likelike

like image 344
Pedro Guizar Avatar asked Nov 03 '19 03:11

Pedro Guizar


1 Answers

You didn't provide a reprex, so I need to make something up. I would probably do it like this.

library(tidyverse)
library(ggtextures)
library(magick)
#> Linking to ImageMagick 6.9.9.39
#> Enabled features: cairo, fontconfig, freetype, lcms, pango, rsvg, webp
#> Disabled features: fftw, ghostscript, x11

data <- tibble(
  count = c(5, 6, 6, 4, 2, 3),
  animal = c("giraffe", "elephant", "horse", "bird", "turtle", "dog"),
  image = list(
    image_read_svg("http://steveharoz.com/research/isotype/icons/giraffe.svg"),
    image_read_svg("http://steveharoz.com/research/isotype/icons/elephant.svg"),
    image_read_svg("http://steveharoz.com/research/isotype/icons/horse.svg"),
    image_read_svg("http://steveharoz.com/research/isotype/icons/bird.svg"),
    image_read_svg("http://steveharoz.com/research/isotype/icons/turtle.svg"),
    image_read_svg("http://steveharoz.com/research/isotype/icons/dog.svg")
  )
)

ggplot(data, aes(animal, count, fill = animal, image = image)) +
  geom_isotype_col(
    img_height = grid::unit(1, "null"), img_width = NULL,
    ncol = 1, nrow = 1, hjust = 1, vjust = 0.5
  ) +
  coord_flip() +
  guides(fill = "none") +
  theme_minimal()

Created on 2019-11-03 by the reprex package (v0.3.0)

like image 144
Claus Wilke Avatar answered Sep 28 '22 07:09

Claus Wilke