我无法弄清楚如何将.gif图形用作x-y绘图中的点,以及如何根据数据集中的数据旋转每个点。
演示数据集:
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
那么,有什么好主意吗? 在此先感谢:-)
答案 0 :(得分: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)