我在ggplot2中使用facet_wrap
创建了一个多面板图,并希望将不同的图像添加到每个面板中。
annotation_custom
将图像插入ggplot2,但所有面板都是相同的。
这是添加R徽标的示例
库(GGPLOT2)
# Create dataset
df <- data.frame(
x = rep(seq(1, 5), times = 2),
y = rep(seq(1, 5), times = 2),
z = rep(seq(1, 2), each = 5)
)
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
g <- rasterGrob(img, interpolate=TRUE)
ggplot(df) +
geom_point(aes(x, y)) +
annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
facet_wrap(~z)
img2
由img
生成。
img2 <- img * 0.5
是否可以在ggplot2中插入不同的图像(例如img
到面板1,img2
到面板2)?
感谢您的任何建议。如果我的问题不明确,请告诉我。
答案 0 :(得分:0)
我就是这样解决这个问题的。我想在 ggplot 的每个面板中都有一个不同的图像(光栅图像)。然而,面板的数量可能会改变。这是在函数内部。注意 Baptistes 的 annotate_custom2() 函数肯定更干净。 https://stackoverflow.com/a/44897816/2403645 我不记得为什么我不能得到那份工作;我想这是因为我不会提前知道轴限制或方面的数量。
library(ggplot2)
library(grid)
library(stringr)
# Set up list of images
N <- 6
img.list <- list()
for(i in 1:N) img.list[[i]] <- as.raster(matrix(runif(15), ncol = 5, nrow = 3))
# Make a panel plot in ggplot
df <- data.frame(name=letters[1:N], val=rep(1:N, each=10))
ggplot(df, aes(val, val)) + geom_point() + facet_wrap(~name)
# Get the current viewport tree
a <- current.vpTree()
# Get the names of the children viewports with name panel
# For me, the viewport name of my plot was "layout"; might be different
# in different situations
b <- names(a$children$layout$children)
# find the names of the panel viewports.
# Change if you want the images somewhere else in the plot (like panel titles)
panel.vp <- b[stringr::str_detect(b, "panel-")]
# NOTE! the panel naming is weird. panel-1-2 is not row 1 column 2.
# it is the next numbers that seem to denote the panel row/column
# set up a viewport for my image; always top left
vp.img <- grid::viewport(x=unit(0.1,"npc"), y=unit(0.8,"npc"), width=unit(0.2, "npc"), just = "left")
# add the images to each facet
for(i in 1:N){
# checkout viewport for panel i
grid::seekViewport(panel.vp[i])
# draw my image
grid::grid.draw(grid::grobTree(grid::rasterGrob(img.list[[i]]), vp=vp.img))
}