我正在尝试将图片(jpeg,png不关心)添加到由布局函数定义的绘图中.例如:
a<-c(1,2,3,4,5)
b<-c(2,4,8,16,32)
m <- matrix(c(1,1,1,1,2,3,2,3), nrow = 2, ncol = 4)
layout(m); hist(a);boxplot(a~b);plot(b~a)*
Run Code Online (Sandbox Code Playgroud)
而不是位置1上的直方图我想添加一个图像(在我的情况下,它是一个地图)
我不知道如何处理jpeg包,也许你可以帮助我!
nic*_*ola 10
您需要通过和包读取您的png或jpeg文件.然后,使用该功能,您可以在绘图上绘制图像.说你的文件是,你可以试试这个:pngjpegrasterImagemyfile.jpeg
require(jpeg)
img<-readJPEG("myfile.jpeg")
#now open a plot window with coordinates
plot(1:10,ty="n")
#specify the position of the image through bottom-left and top-right coords
rasterImage(img,2,2,4,4)
Run Code Online (Sandbox Code Playgroud)
上面的代码将在(2,2)和(4,4)点之间绘制图像.
只是想从名为grid.raster的内置“网格”包中提供一个替代解决方案
据我所知,它的行为与 rasterImage 非常相似,但采用标准化单位,“npc”——在我看来是一个奖励,并且除非您同时设置宽度和高度,否则会保留纵横比。出于我的目的,我只是设置了其中之一/或图像似乎完美地缩放。
library(png)
library(grid)
x11()
mypng = readPNG('homer.png')
image(volcano)
grid.raster(mypng, x=.3, y=.3, width=.25) # print homer in ll conrner
grid.raster(mypng, x=.9, y=.7, width=.5) # print bigger homer in ur corner
while(!is.null(dev.list())) Sys.sleep(1)
Run Code Online (Sandbox Code Playgroud)

关于Rodrigo的评论,我创建了一个函数,该函数应保留图像的像素长宽比(addImg)。
addImg <- function(
obj, # an image file imported as an array (e.g. png::readPNG, jpeg::readJPEG)
x = NULL, # mid x coordinate for image
y = NULL, # mid y coordinate for image
width = NULL, # width of image (in x coordinate units)
interpolate = TRUE # (passed to graphics::rasterImage) A logical vector (or scalar) indicating whether to apply linear interpolation to the image when drawing.
){
if(is.null(x) | is.null(y) | is.null(width)){stop("Must provide args 'x', 'y', and 'width'")}
USR <- par()$usr # A vector of the form c(x1, x2, y1, y2) giving the extremes of the user coordinates of the plotting region
PIN <- par()$pin # The current plot dimensions, (width, height), in inches
DIM <- dim(obj) # number of x-y pixels for the image
ARp <- DIM[1]/DIM[2] # pixel aspect ratio (y/x)
WIDi <- width/(USR[2]-USR[1])*PIN[1] # convert width units to inches
HEIi <- WIDi * ARp # height in inches
HEIu <- HEIi/PIN[2]*(USR[4]-USR[3]) # height in units
rasterImage(image = obj,
xleft = x-(width/2), xright = x+(width/2),
ybottom = y-(HEIu/2), ytop = y+(HEIu/2),
interpolate = interpolate)
}
Run Code Online (Sandbox Code Playgroud)
library(png)
myurl <- "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/Jupiter_%28transparent%29.png/242px-Jupiter_%28transparent%29.png"
z <- tempfile()
download.file(myurl,z,mode="wb")
pic <- readPNG(z)
file.remove(z) # cleanup
dim(pic)
png("plot.png", width = 5, height = 4, units = "in", res = 400)
par(mar = c(3,3,0.5,0.5))
image(volcano)
addImg(pic, x = 0.3, y = 0.5, width = 0.2)
dev.off()
Run Code Online (Sandbox Code Playgroud)