我定義了兩個類
setClass("myDF", contains = "data.frame")
setClass("myCol", contains = "factor")
然后我創建兩個測驗data.frame
orig_df <- data.frame(A = factor(sample(c("1", "2"), size = 100, replace = T), levels = c("1", "2"), labels = c("Apple", "Banana")))
my_df <- new("myDF", data.frame(A = new("myCol", orig_df$A)))
使用 繪制條形圖時,當我使用包含 class 的列ggplot2時沒有條形圖。data.framemyCol
ggplot(orig_df, aes(x = A)) geom_bar(stat = "count") # works fine

ggplot(my_df, aes(x = A)) geom_bar(stat = "count") # no bars visible

它也適用于 class 的物件myDF,其中包含作為列的公因子。
我很難弄清楚我錯過了什么。我是否需要為一些泛型(訪問器,如[)定義一個方法?
R version 4.1.3 (2022-03-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)
Matrix products: default
locale:
[1] LC_COLLATE=German_Germany.1252 LC_CTYPE=German_Germany.1252 LC_MONETARY=German_Germany.1252
[4] LC_NUMERIC=C LC_TIME=German_Germany.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] ggplot2_3.3.6
loaded via a namespace (and not attached):
[1] magrittr_2.0.3 tidyselect_1.1.2 munsell_0.5.0 colorspace_2.0-3 R6_2.5.1 rlang_1.0.2
[7] fansi_1.0.3 dplyr_1.0.9 tools_4.1.3 grid_4.1.3 gtable_0.3.0 utf8_1.2.2
[13] cli_3.3.0 DBI_1.1.2 withr_2.5.0 ellipsis_0.3.2 digest_0.6.29 assertthat_0.2.1
[19] tibble_3.1.7 lifecycle_1.0.1 crayon_1.5.1 farver_2.1.0 purrr_0.3.4 vctrs_0.4.1
[25] glue_1.6.2 labeling_0.4.2 compiler_4.1.3 pillar_1.7.0 generics_0.1.2 scales_1.2.0
[31] pkgconfig_2.0.3
uj5u.com熱心網友回復:
一種解決方法是顯式呼叫factor:
ggplot(my_df, aes(x = factor(A))) geom_bar(stat = "count", width = 1, fill = "steelblue")
當更新到 時R 4.2,它在沒有它的情況下作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/477212.html
