使用ggimage将图像添加到R中的标签

holgip5t  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(157)

有没有一种方法可以使用geom_image将文本标签替换为饼图中的图像?
我试着使用下面的代码。
但是,图像与标签的位置不同。(我包括标签,以显示图像应该去的地方,但我想删除文本标签,并替换为图像)

library(tidyverse)
library(ggplot2)
library(ggimage)

# Sample data
labels <- c("Category 1", "Category 2")
values <- c(20, 80)
# Create a data frame
df <- data.frame(labels, values)

df$image <- 'https://www.r-project.org/logo/Rlogo.png'

# Create the pie chart
ggplot(df, aes(x = "", y = values, fill = labels)) +
  geom_bar(stat = "identity", width = 1) +
  coord_polar("y", start = 0) +
  theme_void() +
  geom_text(aes(y = values, label = labels), color = "white", size=5, 
            position = position_stack(vjust = 0.5)) +
  theme(legend.position = "none") +
  geom_image(aes(image=image)) +
    scale_fill_brewer(palette="Set1")

image我看到其他人使用ggtext和其他包做类似的事情,但我想知道ggimage是否有能力做到这一点。

kq0g1dla

kq0g1dla1#

这总是一个位置(或分组)的问题。(;要将图像放置在与标签相同的位置,必须对geom_image使用与geom_text相同的position=

library(tidyverse)
library(ggplot2)
library(ggimage)

# Sample data
labels <- c("Category 1", "Category 2")
values <- c(20, 80)
# Create a data frame
df <- data.frame(labels, values)

df$image <- "https://www.r-project.org/logo/Rlogo.png"

# Create the pie chart
ggplot(df, aes(x = "", y = values, fill = labels)) +
  geom_bar(stat = "identity", width = 1) +
  coord_polar("y", start = 0) +
  theme_void() +
  geom_text(aes(y = values, label = labels),
    color = "white", size = 5,
    position = position_stack(vjust = 0.5)
  ) +
  theme(legend.position = "none") +
  geom_image(aes(image = image), position = position_stack(vjust = 0.5)) +
  scale_fill_brewer(palette = "Set1")

相关问题