0

我不知道如何使用 .gif 图形作为 xy 绘图中的点,并根据数据集中的数据旋转每个点。

演示数据集:

library("ggplot2")
library("ggimage")
N=5
d <- data.frame(x = rnorm(N),
            y = rnorm(N),
            image = rep("https://www.r-project.org/logo/Rlogo.png", N),
            size = seq(.05, 0.15, length.out = N),
            angle = seq(0, 45, length.out = N) )

下图将绘制所有 Rlogo 旋转 45 度的图:

ggplot(d, aes(x, y)) + 
  geom_image(aes(image=image, size=I(size)), angle = 45)
# Plot with tilted png

但是如何为每个点单独设置旋转角度呢?下面的代码片段根本不起作用,并且在不倾斜任何点的情况下绘制了一个情节..

ggplot(d, aes(x, y)) + 
  geom_image(aes(image=image, size=I(size), angle = I(angle)))
#plotting but without tilting the points

在 aes 之外设置绘图角度无济于事。

ggplot(d, aes(x, y)) + geom_image(aes(image=image, size=I(size)), angle = I(d$angle))
# No plotting: Error in valid.viewport(x, y, width, height, just, gp, clip, xscale, yscale, invalid 'angle' in viewport

那么,有人对此有好主意吗?提前致谢:-)

4

1 回答 1

1

你可以试试这个,虽然真正的解决方案是写一个更好的geom,

library("ggplot2")
library("egg")
library("grid")
N=5
d <- data.frame(x = rnorm(N),
                y = rnorm(N),
                image = replicate(N, system.file("img", "Rlogo.png", package="png")),
                size = seq(.05, 0.15, length.out = N),
                angle = seq(0, 45, length.out = N),
                stringsAsFactors = FALSE)

grobs <- purrr::map2(d$image, runif(N,0,180),
                     function(i,a) list(raster = png::readPNG(i), angle=a) )
d$grob <- I(grobs)

custom_grob <- function(data, x=0.5, y=0.5){
  grob(data=data$raster,angle=data$angle,x=x,y=y, cl="custom")
}
preDrawDetails.custom <- function(x){
  pushViewport(viewport(x=x$x,y=x$y, angle = x$angle))
}
postDrawDetails.custom <- function(x){
  upViewport()
}
drawDetails.custom <- function(x, recording=FALSE, ...){
  grid.raster(x$data, interpolate = FALSE, width=unit(1,"cm"), height=unit(1,"cm"))
}
ggplot(d, aes(x, y)) +
  theme_bw() +
  geom_custom(data = d, aes(data = grob), 
              grob_fun = custom_grob)

在此处输入图像描述

于 2018-06-23T20:20:13.443 回答