2016-03-21 4 views
2

В настоящее время я создаю графики в ggplot2, импортируя пользовательские изображения и используя их как geom_points, похожие на this post, за исключением того, что я просматриваю разные изображения для уникальных уровней фактора.Пользовательская легенда с импортированными изображениями

Есть ли простой способ добавить эти изображения в легенду? Я видел несколько сообщений в пользовательских легендах в ggplot2, но ничего, что касается импортированных изображений.

+3

_ "Есть простой способ добавить эти изображения в легенде? «Я так не думаю, я думаю, вам придется пробивать себе путь, отключив отсечение/включение графика вне области построения графика, а затем создаст собственную легенду. Но мне тоже было бы интересно узнать. – lukeA

+0

этот ответ может быть полезен: http://stackoverflow.com/a/36172385/471093 (также в доказательстве принципа [пакет ggflags] (https://github.com/baptiste/ggflags)) – baptiste

ответ

7

Я не уверен, как вы собираетесь генерировать свой сюжет, но это показывает один метод замены ключа легенды изображением. Он использует grid функции, чтобы найти видовые, содержащие легенды ключевых grobs, и заменяет один с 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) 

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) 
    } 
} 
+0

Отлично! Я пытаюсь автоматизировать это, но не могу написать вывод formatVPTree (current.vpTree()) в список; он просто печатает на консоли. Есть идеи, как это сделать? – RH2015

+0

Nevermind, я уверен, что есть лучший способ, но я нашел capture.output (formatVPTree (current.vpTree())), и мне просто нужно обрезать пробелы – RH2015

+2

Я добавил код, который будет искать требуемый имена видов просмотра с использованием регулярных выражений. –

Смежные вопросы