我们如何在R中给定坐标绘制图像?

4
给定'n'个png/jpeg格式的图片和对应的二维坐标(x,y):我想在一个图中将这些图片绘制在给定的坐标上。如果我发现图片太大,我希望在给定的坐标上绘制一个更小/缩放版本的图片。如何在R中实现这样的图形?
下面给出了这种图形的示例: enter image description here

@baptiste 我需要在2D坐标系中绘制它们。rasterImage的参数有4个:(xleft,ybottom,xright,ytop)。xleft是左侧x位置的向量(或标量),ybottom是底部y位置的向量(或标量),xright是右侧x位置的向量(或标量),ytop是顶部y位置的向量(或标量)。我该如何理解并将其作为解决方案适用于我的问题? - hearse
3个回答

8
xy <- data.frame(x=runif(10, 0, 100), y=runif(10, 0, 100))

require(png)
img <- readPNG(system.file("img", "Rlogo.png", package="png"))

thumbnails <- function(x, y, images, width = 0.1*diff(range(x)), 
                       height = 0.1*diff(range(y))){

  images <- replicate(length(x), images, simplify=FALSE)
  stopifnot(length(x) == length(y))

  for (ii in seq_along(x)){
    rasterImage(images[[ii]], xleft=x[ii] - 0.5*width,
                ybottom= y[ii] - 0.5*height,
                xright=x[ii] + 0.5*width, 
                ytop= y[ii] + 0.5*height, interpolate=FALSE)
  }
}

plot(xy, t="n")
thumbnails(xy[,1], xy[,2], img)

enter image description here


请注意,如果img是不同图像的列表,则需要将此行注释掉:images <- replicate(length(x), images, simplify=FALSE) 以使其工作。 - val
如何在指定位置指定10个不同的图像,这些图像对应着10个坐标? - user2964644

4
TeachingDemos包中的my.symbols函数和ms.image函数可用于使用图像绘制图形。

以下是一个示例:

library(png)

flag.list <- lapply( list.files('flags/',pattern='png$', full=TRUE), 
    function(x) readPNG(x) )

library(TeachingDemos)

ms.flags <- function(ind,...) {

    tmp <- array(0, dim=c(150,150,4) )
    tmp[ 26:125, , 1:3] <- flag.list[[ind]]
    tmp[ 26:125, , 4 ] <- 1

    ms.image(tmp,...)
}

x <- rnorm(50)
y <- rnorm(50)

my.symbols(x,y, symb = ms.flags, ind=1:50, symb.plots=TRUE,
  add=FALSE, xlim=c(-3,3), ylim=c(-3,3), inches=0.75)

enter image description here


我正在尝试这个,但是我得到了“Error in flag.list[[ind]] : subscript out of bounds”的错误,并且我发现flag.list是“List of 0”……看起来我没有得到图像? - val
@val,你是怎么读取这些图片的?你下载了一些图片吗?它们相对于你的工作目录在哪个文件夹里? - Greg Snow
我使用了这行代码:imgfiles <- list.files(getwd(),pattern="*-scaled.png") 来获取我的图像。最终,我在这里发布我的答案,并使用了上面接受的答案中的代码-请参见http://stackoverflow.com/questions/37150889/r-plotting-thumbnails-that-are-in-a-list-on-a-scatterplot - val

2
ggflags包提供了一个原理验证的示例。
library(ggflags)
set.seed(1234)
d <- data.frame(x=rnorm(50), y=rnorm(50), 
                country=sample(c("ar","fr", "nz", "gb", "es", "ca"), 50, TRUE), 
                stringsAsFactors = FALSE)
ggplot(d, aes(x=x, y=y, country=country, size=x)) + 
  geom_flag() + 
  scale_country()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接