Как добавить изображение в ggplot
Я хотел добавить изображение, извлеченное с веб-страницы (LeBron_James, назначенное ниже), в ggplot с помощью пакета ggimage. Как я могу добавить его в rscript ggplot ниже?
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")
2 ответа
Решение
Это построит изображение вместо точки
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))
Вы не предоставили никаких данных и не указали, где и как вы хотите разместить изображение, поэтому я не могу воспроизвести ваш сюжет. Однако вы должны уметь делать то, что хотите, с коровьим заговором. Например:
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)
Вы можете поместить изображение под сюжетом (в этом случае вам нужно выбрать одну из тем коровьего сюжета, чтобы не закрывать изображение) или вы можете разместить его над сюжетом, как во втором примере, и настроить координаты в соответствии с желаемым результатом. В вашем примере это, вероятно, сработает:
ggdraw(GGplot_mean_performance) +
draw_image(Lebron_James, x=1, y=1, hjust = 1, vjust = 1)