I defined the two classes
setClass("myDF", contains = "data.frame")
setClass("myCol", contains = "factor")
I then create two test 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)))
When plotting a barplot using ggplot2
, there are no bars when I use the data.frame
containing the column of class myCol
.
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
It also works on an object of class myDF
, which contains common factors as a column.
I struggle to figure out what I missed. Do I need to define a method for some generic (an accessor like [
)?
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
CodePudding user response:
A workaround is to make an explicit call to factor
:
ggplot(my_df, aes(x = factor(A))) geom_bar(stat = "count", width = 1, fill = "steelblue")
When udpated to R 4.2
, it is working without it.