R 带有导入图像的自定义图例

R 带有导入图像的自定义图例,r,ggplot2,legend,R,Ggplot2,Legend,我目前正在ggplot2中创建绘图,方法是导入自定义图像并将其用作几何图形点,类似于,只是我在不同的图像中循环以获得唯一的因子级别 有没有简单的方法将这些图像添加到图例中?我在ggplot2中看到过多篇关于自定义图例的帖子,但没有涉及导入图像的帖子 我不确定您将如何生成绘图,但这显示了一种用图像替换图例键的方法。它使用grid函数来定位包含图例键槽的视口,并将其中一个替换为R徽标 library(png) library(ggplot2) library(grid) # Get image i

我目前正在ggplot2中创建绘图,方法是导入自定义图像并将其用作几何图形点,类似于,只是我在不同的图像中循环以获得唯一的因子级别


有没有简单的方法将这些图像添加到图例中?我在ggplot2中看到过多篇关于自定义图例的帖子,但没有涉及导入图像的帖子

我不确定您将如何生成绘图,但这显示了一种用图像替换图例键的方法。它使用
grid
函数来定位包含图例键槽的视口,并将其中一个替换为R徽标

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)
库(png)
图书馆(GG2)
图书馆(网格)
#获取图像

img“有没有一种简单的方法可以将这些图像添加到图例中?”我不这么认为,我想你必须通过禁用剪切/启用绘图区域外的绘图,然后构建自己的图例来破解它。但我也很想知道。这个答案可能有用:(也是在原则证明中)太好了!我正在尝试将其自动化,但似乎无法将formatVPTree(current.vpTree())的输出写入列表;它只是打印到控制台。你知道怎么做吗?没关系,我肯定有更好的方法,但我发现capture.output(formatVPTree(current.vpTree())可以工作,我只需要修剪空格。我添加了一些代码,可以使用正则表达式搜索所需的视口名称。
# 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)
    }
}