如何在R中的绘图上放置多个png?
我正在尝试绘制热图。但然后在热图的每个图块上,我想放置一个 png。到目前为止,这是我的代码:
library(ggplot2)
library(png)
library(grid)
# get png
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
g <- rasterGrob(img, interpolate=TRUE)
# create heatmap
x <- LETTERS[1:5]
y <- paste0("var", seq(1,5))
data <- expand.grid(X=x, Y=y)
data$Z <- runif(25, 0, 5)
# Heatmap
p <- ggplot(data, aes(X, Y, fill= Z)) +
geom_tile() +
theme(aspect.ratio = 1)
# place png
p +
annotation_custom(g, xmin = 0.5, xmax = 1.5, ymin = 0.5, ymax = 1.5)
上面的代码绘制了这个:
但我想做的是将 png 放在热图的每个图块上。现在,我可以像这样检索每个图块的坐标:
b <- ggplot_build(p)
b$data[[1]]$xmin
b$data[[1]]$xmax
b$data[[1]]$ymin
b$data[[1]]$ymax
但我不知道如何将 png 放置在每个图块上。我希望不必为每个图块都有一个 annotation_custom
参数。我正在尝试使该过程稍微自动化。
有什么办法可以做到这一点吗?
Similar questions have been asked here and here. However, they don't exactly solve my issue.
I'm trying to plot a heatmap. But then on every tile of the heatmap, I want to place a png. Here's my code so far:
library(ggplot2)
library(png)
library(grid)
# get png
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
g <- rasterGrob(img, interpolate=TRUE)
# create heatmap
x <- LETTERS[1:5]
y <- paste0("var", seq(1,5))
data <- expand.grid(X=x, Y=y)
data$Z <- runif(25, 0, 5)
# Heatmap
p <- ggplot(data, aes(X, Y, fill= Z)) +
geom_tile() +
theme(aspect.ratio = 1)
# place png
p +
annotation_custom(g, xmin = 0.5, xmax = 1.5, ymin = 0.5, ymax = 1.5)
The above code plots this:
But what Im trying to do is place the png on every single tile go the heatmap. Now, I can retrieve the coordinates for each tile like so:
b <- ggplot_build(p)
b$data[[1]]$xmin
b$data[[1]]$xmax
b$data[[1]]$ymin
b$data[[1]]$ymax
But I don't know how to place the png on every tile. I was hoping to not have to have an annotation_custom
argument for every single tile. I'm trying to somewhat automate the process.
Is there any way that this can be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以循环添加注释
You can add the annotations in a loop