xiuxiu
xiuxiu

Reputation: 47

How to add image to a ggplot

I wanted to add an image extracted from a webpage (LeBron_James assigned below) to the ggplot using ggimage package. How can i add it to the ggplot rscript below?

GGplot_mean_performance <- FirstPick_Wage_Performance %>% 
  ggplot(aes(x=Player, y=mean_performance, label=mean_performance))+ 
  geom_point(stat="identity", size=3)  +
  geom_hline(aes(yintercept = mean(mean_performance)), color = "blue", size = 3) + 
  geom_segment(aes(y = mean(mean_performance),             
                   x = Player, 
                   yend = mean_performance, 
                   xend = Player,)) +
  geom_text(color="red", size=4) +
  labs(title="Lollipop Chart of Player's mean performance for the first two years as draft pick \ncompared to mean performance of the population", 
       subtitle="Blake Griffin is the best performing 1st Pick and Anthony Bennett is the worst performing 1st Pick",
       caption="Source: https://www.basketball-reference.com & https://basketball.realgm.com") + 
  ylim(20, 80) +
  coord_flip() +
  theme(legend.position = "none")

Lebron_James <- image_read2("https://nba-players.herokuapp.com/players/james/lebron")

Upvotes: 2

Views: 1729

Answers (2)

Tony Ladson
Tony Ladson

Reputation: 3649

This will plot the image instead of a point

library("ggplot2")
library("ggimage")


d <- data.frame(x = 1:2,
                y = 1:2,
                image = c("https://nba-players.herokuapp.com/players/james/lebron",
                          "https://nba-players.herokuapp.com/players/james/lebron"))

ggplot(d, aes(x, y)) + 
  geom_image(aes(image=image), size=.2) +
  scale_x_continuous(limits = c(0, 3)) +
  scale_y_continuous(limits = c(0,3))

Upvotes: 1

at80
at80

Reputation: 790

You didn't provide any of your data nor did you specify where or how you want the image to be placed so I can't reproduce your plot. However, you should be able to do what you want to do with cowplot. For example:

library(ggimage)
library(cowplot)
Lebron_James <- image_read2("https://nba-players.herokuapp.com/players/james/lebron")


df <- data.frame(a=seq(1,10), b=seq(1,10))

p <- ggplot(df)+
  geom_line(aes(a, b)) +
  theme_cowplot(12)

# place image under plot
a <- ggdraw() + 
  draw_image(Lebron_James, scale = 0.5) +
  draw_plot(p) 

# place image above plot
b <- ggdraw(p) + 
  draw_image(Lebron_James, x = 1, y = 1, hjust = 1, vjust = 1, width = 0.13, height = 0.2)

plot_grid(a,b)

You can either place the image below the plot (in which case you need to select one of cowplots themes to not cover the image) or you can place it above the plot as in the second example and adjust the coordinates to match your desired outcome. From your example this would likely work:

ggdraw(GGplot_mean_performance) +
   draw_image(Lebron_James, x=1, y=1, hjust = 1, vjust = 1)

Upvotes: 1

Related Questions