英文:
Using ggimage to add images to labels in R
问题
以下是您要翻译的内容:
有没有办法在饼图中使用geom_image来替换文本标签为图像?
我尝试使用下面的代码。
但是,图像的位置与标签不同。 (我包括了标签以显示图像应放置的位置,但我想要删除文本标签并将其替换为图像)
library(tidyverse)
library(ggplot2)
library(ggimage)
# 示例数据
labels <- c("Category 1", "Category 2")
values <- c(20, 80)
# 创建数据框
df <- data.frame(labels, values)
df$image <- 'https://www.r-project.org/logo/Rlogo.png'
# 创建饼图
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是否具备这个功能。
英文:
Is there a way to use geom_image to replace text labels to images in a pie chart?
I tried using the code below.
However, the images aren't in the same position as the labels. (I included the labels to show where the images should go but I want to remove the text labels and replace them with the images)
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
I have seen others do something similar using ggtext and other packages but was wondering if ggimage has the capacity to do this.
答案1
得分: 0
这是代码部分,不需要翻译。
英文:
It always a matter of the position (or the grouping). (; To place the images at the same position as the labels you have to use the same position=
for geom_image
as for geom_text
:
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")
<!-- -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论