我正在嘗試將一組圖 (ggplot) 保存到串列中,并且在最后一個圖覆寫所有串列索引的情況下表現得很奇怪。
這是我的代碼:
library(ggplot2)
mtcars <- mtcars[, c('cyl', 'am', 'gear', 'mpg')]
plots <- list()
for (i in 1:3) {
plots[[i]] <- ggplot(
mtcars,
aes(x = factor(mtcars[, i]), y = mtcars[, 'mpg'])
) geom_point()
}
plots
當我嘗試通常將某些內容保存到串列時,它作業正常,如下例所示:
plots <- list()
for (i in 1:3) {
plots[[i]] <- sample(mtcars$mpg, 1)
}
plots
使用將 ggplot 物件保存到串列lapply也可以正常作業,如下所示:
library(ggplot2)
mtcars <- mtcars[, c('cyl', 'am', 'gear', 'mpg')]
lapply(
1:3, function(i)
ggplot(
mtcars,
aes(x = factor(mtcars[, i]), y = mtcars[, 'mpg'])
) geom_point()
)
知道發生了什么嗎?
順便說一句 - 這個資訊可能是相關的:
> packageVersion('ggplot2')
[1] ‘3.3.3’
> version
_
platform x86_64-apple-darwin17.0
arch x86_64
os darwin17.0
system x86_64, darwin17.0
status
major 4
minor 0.3
year 2020
month 10
day 10
svn rev 79318
language R
version.string R version 4.0.3 (2020-10-10)
nickname Bunny-Wunnies Freak Out
uj5u.com熱心網友回復:
問題是該串列包含ggplotx 美學取決于i變數的位置。更準確地說,在您運行后,您的代碼i設定為3. 特別是,x 美學總是顯示 factor(mtcars[, 3])。
您可以通過嘗試以下操作來驗證這一點:
print(plots[[1]]) # prints the third plot
i <- 1
print(plots([[1]]) # prints the first plot because now i = 1
這是您可以嘗試的替代作業流程:
plot_cars <- mtcars %>%
gather(type, val, -mpg) %>%
nest(data = c(val, mpg)) %>%
mutate(plot = map(data, ~ggplot(.x,
aes(x = val, y = mpg)) geom_point()))
plot_cars$plot[[1]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/366448.html
上一篇:漸變色ggplot2R中的一條線
下一篇:對齊多行“膠水”運算式
