导入图像的自定义图例

时间:2016-03-21 14:14:05

标签: r ggplot2 legend

我目前正在ggplot2中创建绘图,方法是导入自定义图像并将它们用作geom_points,类似于this post,除了我循环遍历不同图像以获得唯一级别的因子。

是否有一种简单的方法可以将这些图像添加到图例中?我在ggplot2中看过多个关于自定义图例的帖子,但没有任何处理导入图像的帖子。

1 个答案:

答案 0 :(得分:7)

我不确定如何生成绘图,但这显示了一种用图像替换图例键的方法。它使用display:inline-block函数来定位包含图例键grobs的视口,并用R徽标替换一个

grid

enter image description here

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)