gpt4 book ai didi

r - 带有导入图像的自定义图例

转载 作者:行者123 更新时间:2023-12-03 19:55:01 24 4
gpt4 key购买 nike

我目前正在通过导入自定义图像并将它们用作 geom_points 在 ggplot2 中创建绘图,类似于 this post ,除了我循环浏览不同的图像以获得一个因素的独特水平。

有没有一种简单的方法可以将这些图像添加到图例中?我在 ggplot2 中看到了多篇关于自定义图例的帖子,但没有任何内容涉及导入的图像。

最佳答案

我不确定你将如何生成你的情节,但这显示了一种用图像替换图例键的方法。它使用 grid用于定位包含图例键 grobs 的视口(viewport)的函数,并将其中一个替换为 R Logo

library(png)
library(ggplot2)
library(grid)

# Get image
img <- readPNG(system.file("img", "Rlogo.png", package="png"))

# Plot
p = ggplot(mtcars, aes(mpg, disp, colour = factor(vs))) +
geom_point() +
theme(legend.key.size = unit(1, "cm"))

# Get ggplot grob
gt = ggplotGrob(p)
grid.newpage()
grid.draw(gt)

# Find the viewport containing legend keys
current.vpTree() # not well formatted
formatVPTree(current.vpTree()) # Better formatting - see below for the formatVPTree() function

# Find the legend key viewports
# The two viewports are:
# key-4-1-1.5-2-5-2
# key-3-1-1.4-2-4-2

# Or search using regular expressions
Tree = as.character(current.vpTree())
pos = gregexpr("\\[key.*?\\]", Tree)
match = unlist(regmatches(Tree, pos))

match = gsub("^\\[(key.*?)\\]$", "\\1", match) # remove square brackets
match = match[!grepl("bg", match)] # removes matches containing bg

# Change one of the legend keys to the image
downViewport(match[2])
grid.rect(gp=gpar(col = NA, fill = "white"))
grid.raster(img, interpolate=FALSE)
upViewport(0)

enter image description here
# Paul Murrell's function to display the vp tree 
formatVPTree <- function(x, indent=0) {
end <- regexpr("[)]+,?", x)
sibling <- regexpr(", ", x)
child <- regexpr("[(]", x)
if ((end < child || child < 0) && (end < sibling || sibling < 0)) {
lastchar <- end + attr(end, "match.length")
cat(paste0(paste(rep(" ", indent), collapse=""),
substr(x, 1, end - 1), "\n"))
if (lastchar < nchar(x)) {
formatVPTree(substring(x, lastchar + 1),
indent - attr(end, "match.length") + 1)
}
}
if (child > 0 && (sibling < 0 || child < sibling)) {
cat(paste0(paste(rep(" ", indent), collapse=""),
substr(x, 1, child - 3), "\n"))
formatVPTree(substring(x, child + 1), indent + 1)
}
if (sibling > 0 && sibling < end && (child < 0 || sibling < child)) {
cat(paste0(paste(rep(" ", indent), collapse=""),
substr(x, 1, sibling - 1), "\n"))
formatVPTree(substring(x, sibling + 2), indent)
}
}

关于r - 带有导入图像的自定义图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36133374/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com