[英]What determines the 'flipped_aes' occurence in ggplot2 objects?
我目前正在寫漩渦課程,我正在嘗試測試用戶創建的 ggplot2 object 是否與我在 AnswerTest 中創建的 object 有點相等( all.equal()
)。 however the plot object which i receive from swirl api by accessing e$val often inherits an flipped_aes = FALSE attribute which i cannot create in my own plots and hence all.equal(e$val, someplot)
fails allthough they look equal.
我真的很感激一些想法如何解決它或控制它的發生!
如果發生 all.equal() 失敗並顯示以下消息:
"Component “layers”: Component 1: Component 4: Length mismatch: comparison on first 2 components"
我當前的測試如下所示:
calculates_same_graph <- function(expression){ #If ggplot expression must be written in curly brackets in Yaml file
e <- get("e", parent.frame())
eSnap <- cleanEnv(e$snapshot)
val <- expression
passed <- isTRUE(all.equal(val[-8], e$val[-8]))
assign("e", e$val, envir = globalenv()) #only for diagnostics, changes
#when new answer is put in
return(passed)
}
好的,我同意這有點奇怪,但我發現flipped_aes
參數僅在打印 plot 后才存在。 奇怪的是,這似乎是打印 plot 的對象修改副作用。 這僅在參數以某種方式被緩存時才有意義。
假設我們有兩個具有相反審美翻轉的地塊:
library(ggplot2)
# Should have flipped_aes = FALSE
plot1 <- ggplot(iris, aes(Species, Sepal.Width)) +
geom_col()
# Should have flipped_aes = TRUE
plot2 <- ggplot(iris, aes(Sepal.Width, Species)) +
geom_col()
我們可以看到這些未打印的對象在其幾何參數中沒有flipped.aes
。
# Before printing plot
plot1$layers[[1]]$geom_params
#> $width
#> NULL
#>
#> $na.rm
#> [1] FALSE
plot2$layers[[1]]$geom_params
#> $width
#> NULL
#>
#> $na.rm
#> [1] FALSE
現在我們可以將這些圖打印到一個臨時文件中。 只是在控制台中打印它也應該可以工作,我只是無法在 reprex 中復制它。
# Printing as tempfile
tmp <- tempfile(fileext = ".png")
png(tmp)
plot1
plot2
dev.off()
#> png
#> 2
unlink(tmp)
現在,在我們打印了 plot 之后,突然 plot 對象具有flipped_aes
參數。
# After printing plot
plot1$layers[[1]]$geom_params
#> $width
#> NULL
#>
#> $na.rm
#> [1] FALSE
#>
#> $flipped_aes
#> [1] FALSE
plot2$layers[[1]]$geom_params
#> $width
#> NULL
#>
#> $na.rm
#> [1] FALSE
#>
#> $flipped_aes
#> [1] TRUE
由代表 package (v1.0.0) 於 2021 年 3 月 10 日創建
我不知道在您的漩渦測試中處理這種怪異的最佳方法是什么,但似乎 plot 的打印會影響該參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.