gpt4 book ai didi

r - 在 R 中添加要绘制的图片

转载 作者:行者123 更新时间:2023-12-04 03:11:21 25 4
gpt4 key购买 nike

我正在尝试将图片(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)*

我想添加图像而不是位置 1 的直方图 (就我而言,它是一张 map )

我不知道如何处理jpeg包,也许你可以帮助我!

最佳答案

关于 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)
}

使用示例:
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()

enter image description here

关于r - 在 R 中添加要绘制的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27800307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com