2017-05-19 17 views
2

我需要繪製圖像。我的問題是,我的PNG圖像不會調整到網格:如果您希望rasterGrob無需擴展將圖像大小調整爲ggplot2網格

library(webshot) 
library(png) 
webshot("http://www.doctormetrics.com/","doctor.png") 
img <- readPNG("doctor.png") 
dim(img) 
x11() 
g <- rasterGrob(img, interpolate=TRUE) 
qplot(1:2, 1:2, geom="blank") + 
    annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) + 
    geom_point() 

enter image description here

+0

寬高比限制,你需要指定寬度和高度爲'unit(1,「npc」)' – baptiste

+0

謝謝@baptiste,我把它寫下來! –

回答

1

你可以做

library(webshot) 
library(png) 
library(ggplot2) 
library(grid) 
webshot("http://www.doctormetrics.com/",tf<-tempfile(fileext = ".png")) 
img <- readPNG(tf) 
g <- rasterGrob(img, interpolate=TRUE, height = 1, width = 1) 
ggplot() + 
    annotation_custom(g, xmin=1, xmax=2, ymin=1, ymax=2) + 
    geom_point(aes(x,y), data.frame(x=1:2, y=1:2)) + 
    coord_fixed(ratio = nrow(img)/ncol(img)) 

enter image description here

+0

它的工作原理,謝謝@lukeA –