2016-03-21 40 views
2

我目前通過導入自定義圖像並使用它們作爲geom_points,類似於this post在ggplot2中創建圖,除了我通過不同的圖像遍歷一個因子的獨特級別。自定義圖例與導入的圖像

有沒有簡單的方法將這些圖像添加到圖例?我在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

沒關係,我敢肯定有更好的方法,但我發現capture.output(formatVPTree(current.vpTree()))的作品,我只需要修剪空白 – RH2015

+2

我已經添加了一些代碼,將搜索所需使用正則表達式的視口名稱。 –