如何在不一直使用annotation_custom的情況下在 ggplot 繪圖圖中包含多個 grobs 物件?
這是我的代碼:
df <- data.frame(x = 1:10, y = 1:10)
df2 <- data.frame(x = 1 , y = 1)
g <- ggplotGrob(ggplot(df2, aes(x, y))
geom_point()
theme(plot.background = element_rect(colour = "black")))
base <- ggplot(df, aes(x, y))
geom_blank()
theme_bw()
base
annotation_custom(grob = g, xmin = 3, xmax = 2, ymin = 8, ymax = 10)
annotation_custom(grob = g, xmin = 1.5, xmax = 2.5, ymin = 2.8, ymax = 3)
annotation_custom(grob = g, xmin = 1.7, xmax = 2.7, ymin = 3.8, ymax = 5)
annotation_custom(grob = g, xmin = 5, xmax = 6, ymin = 7, ymax = 8.5)
我真正的問題更大,這只是一個例子。
例如,有沒有辦法將所有這些 grobs 放在一個串列中,然后選擇我想要定位它們的坐標。還是我需要一直使用annotation_custom?
任何幫助
uj5u.com熱心網友回復:
一種選擇是將坐標和 grobs 放在 a 中,tibble并用于遍歷 tibblepurrr::pmap的行以將 grobs 添加到您的繪圖中:
library(ggplot2)
library(tibble)
library(purrr)
d_grob <- tibble(
xmin = c(3, 1.5, 1.7, 5),
xmax = c(2, 2.5, 2.7, 6),
ymin = c(8, 2.8, 3.8, 7),
ymax = c(10, 3, 5, 8.5),
grob = list(g, g, g, g)
)
base
purrr::pmap(d_grob, function(grob, xmin, xmax, ymin, ymax) annotation_custom(grob = grob, xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax))

uj5u.com熱心網友回復:
您可以ggplot使用串列將圖層添加到繪圖中。解決此問題的一種方法是創建一個函式,該函式接受您創建的總的 x 和 y 坐標串列ggplotGrob(),然后創建annotation_custom物件并將其添加到您最后回傳的串列中。
df <- data.frame(x = 1:10, y = 1:10)
df2 <- data.frame(x = 1 , y = 1)
g <- ggplotGrob(ggplot(df2, aes(x, y))
geom_point()
theme(plot.background = element_rect(colour = "black")))
add_rects <- function(x_coords, y_coords) {
# First test that the x and y lists are the same length.
# If they are not throw an error.
if (length(x_coords) != length(y_coords)) {
stop("The x and y coordinates must be the same length")
}
grob_list <- list()
for (i in 1:length(x_coords)) {
# Check to see that each element in the list has exactly 2 coordinates
if (length(x_coords[[i]]) != length(y_coords[[i]] & length(x_coords[[i]]) != 2)) {
stop("Each x and y coordinate must be a vector of length 2 specifying
the min and max positioning.")
}
# Get the min and max values for x and y coordinates
xmin <- x_coords[[i]][1]
ymin <- y_coords[[i]][1]
xmax <- x_coords[[i]][2]
ymax <- y_coords[[i]][2]
# Create the annotation
grob <- annotation_custom(grob = g,
xmin = xmin,
xmax = xmax,
ymin = ymin,
ymax = ymax)
# Append it to the list that you will return after the loop
grob_list[[i]] <- grob
}
return(grob_list)
}
base <- ggplot(df, aes(x, y))
geom_blank()
theme_bw()
x_coords <- list(
c(3, 2),
c(1.5, 2.5),
c(1.7, 2.7),
c(5, 6)
)
y_coords <- list(
c(8, 10),
c(2.8, 3),
c(3.8, 5),
c(7, 8.5)
)
base
add_rects(x_coords = x_coords, y_coords = y_coords)
這給出了一個與我從你的代碼中得到的相同的圖(下圖)。

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/371931.html
下一篇:用黑線分隔散點圖點
