Skip to content

geom_tile ignores drop=FALSE for factor aesthetics #5459

@s-andrews

Description

@s-andrews

When trying to plot a geom_tile plot using a factor as an aesthetic where some of the levels are not present in the data. If you use scale_x_discrete(drop=FALSE) to force the addition of the missing levels on the axis then the missing levels are included in the axis but the tiles are still drawn as if the new levels didn't exist.

For example:

library(tidyverse)

tibble(
  from=factor(c("d0","d3","d3","d3"), levels=c("d0","d1","d2","d3")),
  to=factor(c("A","A","B","C"), levels=c("A","B","C")),
  value=c(1,2,3,4)
) %>%
  ggplot(aes(x=from,y=to,fill=value)) +
  geom_tile() +
  scale_x_discrete(drop=FALSE)

Produces:

image

Where you can see only two tiles on the x-axis, despite the axis correctly showing all 4 categories on the tick marks.

> sessionInfo()
R version 4.3.1 (2023-06-16 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19045)

Matrix products: default


locale:
[1] LC_COLLATE=English_United Kingdom.utf8  LC_CTYPE=English_United Kingdom.utf8    LC_MONETARY=English_United Kingdom.utf8
[4] LC_NUMERIC=C                            LC_TIME=English_United Kingdom.utf8    

time zone: Europe/London
tzcode source: internal

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] lubridate_1.9.3 forcats_1.0.0   stringr_1.5.0   dplyr_1.1.3     purrr_1.0.2     readr_2.1.4     tidyr_1.3.0     tibble_3.2.1    ggplot2_3.4.3  
[10] tidyverse_2.0.0

loaded via a namespace (and not attached):
 [1] gtable_0.3.4      compiler_4.3.1    tidyselect_1.2.0  scales_1.2.1      yaml_2.3.7        fastmap_1.1.1     R6_2.5.1          labeling_0.4.3   
 [9] generics_0.1.3    knitr_1.44        munsell_0.5.0     pillar_1.9.0      tzdb_0.4.0        rlang_1.1.1       utf8_1.2.3        stringi_1.7.12   
[17] xfun_0.40         timechange_0.2.0  cli_3.6.1         withr_2.5.1       magrittr_2.0.3    digest_0.6.33     grid_4.3.1        rstudioapi_0.15.0
[25] hms_1.1.3         lifecycle_1.0.3   vctrs_0.6.3       evaluate_0.22     glue_1.6.2        farver_2.1.1      fansi_1.0.4       colorspace_2.1-0 
[33] rmarkdown_2.25    tools_4.3.1       pkgconfig_2.0.3   htmltools_0.5.6 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions