我正在嘗試向保存的 ggplot 物件添加多行。線的坐標存盤在資料框串列中,每個單獨的圖都有一個資料框。我使用 lapply 成功創建了多個繪圖,但是,呼叫 geom_segment 時代碼失敗。下面是示例資料和代碼。
library(ggplot2)
library(tidyverse)
data(iris)
#Dataframes
m.slen <- iris[,c(1,5)]
m.swid <- iris[,c(2,5)]
m.plen <- iris[,c(3,5)]
m.pwid <- iris[,c(4,5)]
#List of dataframes
m.list = list(m.slen = m.slen,
m.swid = m.swid,
m.plen = m.plen,
m.pwid = m.pwid)
#Setting col names
m.list <- lapply(m.list, setNames, nm = c("data", "species"))
#Creating list of data frames with coordinates for geom_segment
meanV = lapply(m.list, function(x) mean(x$data, na.rm = TRUE))
coordy1 = lapply(m.list, function(x) x %>%
group_by(species) %>%
summarise(max = max(data, na.rm=TRUE)) %>%
pull(max) 2)
#Table with dynamic values
line.plot <- list()
for(i in 1:4) {
line.plot[[i]] <-
tibble(x1 = meanV[[i]],
x2 = meanV[[i]] 1,
y1 = coordy1[[i]][1],
y2 = coordy1[[i]][1])
}
#Creating first set of plots, using first list of DFs
plots <- lapply(m.list,function(x)
p <- ggplot(x, aes( x= data, fill = species))
geom_histogram(stat = "count")
ggtitle(names(m.list)))
print(plots)
#Adding segments using second list of DFs
final_plots <- lapply(plots,function(x)
plots geom_segment(data = line.plot,
aes(x = x1, y = y1, xend = x2, yend = y2)))
一切正常,直到最后一步,我收到以下錯誤
錯誤
fortify():!data必須是資料框,或其他可強制轉換的物件fortify(),而不是串列
歡迎任何意見或建議。謝謝
uj5u.com熱心網友回復:
問題是這line.plot是一個串列。為了達到您想要的結果,您可以使用purrr::map2回圈遍歷您的繪圖串列和段的資料框串列:
注意:我也添加inherit.aes = FALSE了geom_segment,否則你也會得到一個錯誤。
final_plots <- purrr::map2(plots, line.plot, function(x, y) {
x geom_segment(
data = y,
aes(x = x1, y = y1, xend = x2, yend = y2), inherit.aes = FALSE
)
})
final_plots[[1]]

編輯使用base R,您可以通過以下方式獲得相同的結果mapply:
final_plots <- mapply(function(x, y) {
x geom_segment(
data = y,
aes(x = x1, y = y1, xend = x2, yend = y2), inherit.aes = FALSE
)
}, x = plots, y = line.plot, SIMPLIFY = FALSE)
或感謝@Parfait 的評論,使用Map:
final_plots <- Map(function(x, y) {
x geom_segment(
data = y,
aes(x = x1, y = y1, xend = x2, yend = y2), inherit.aes = FALSE
)
}, x = plots, y = line.plot)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478282.html
