如何将图像添加到ggplot

How to add image to a ggplot

我想使用 ggimage 包将从网页(LeBron_James 分配在下面)中提取的图像添加到 ggplot。我怎样才能将它添加到下面的 ggplot rscript 中?

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")

您没有提供任何数据,也没有指定图像的放置位置或方式,因此我无法重现您的情节。但是,您应该能够使用 cowplot 做您想做的事。例如:

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)

您可以将图像放在绘图下方(在这种情况下您需要 select cowplots 主题之一以不覆盖图像)或者您可以将其放在绘图上方,如第二个示例和调整坐标以匹配您想要的结果。根据您的示例,这可能会起作用:

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

这将绘制图像而不是点

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))