Skip to content

New ggplot2.discrete.fill option doesn't work with ordered factor columns #4148

Closed
@rlh1994

Description

@rlh1994

I have found what I think is an issue with the new ggplot2.discrete.fill options, although it may be my understanding of what exactly "discrete" means and this may be by design. When using the option it works correctly for character columns, or as in the example factor(char_column)'s, but does not appear to work for already existing factor columns as this uses the default colours instead.

As I said this may be by design in that factors are treated different in plotting and I haven't realised, but this isn't clear in documentation anywhere I looked. I am using ggplot2 version 3.3.2, and R version 3.6.1.

library(ggplot2)
okabe <- c("#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")

cty_by_var <- function(var) {
  ggplot(mpg, aes(cty, colour = {{var}}, fill = {{var}})) +
    geom_density()
}

price_by_var <- function(var) {
  ggplot(diamonds, aes(price, colour = {{var}}, fill = {{var}})) +
    geom_density()
}

price_by_var2 <- function(var) {
  ggplot(diamonds, aes(price, colour = as.character({{var}}), fill = as.character({{var}}))) +
    geom_density()
}

# Works correctly with okabe colours 
withr::with_options(
  list(ggplot2.discrete.fill = okabe),
  print(cty_by_var(class))
)

# Works incorrectly, using the default colours
withr::with_options(
  list(ggplot2.discrete.fill = okabe),
  print(price_by_var(cut))
)

# Works correctly with okabe colours 
withr::with_options(
  list(ggplot2.discrete.fill = okabe),
  print(price_by_var2(cut))
)

Created on 2020-07-27 by the reprex package (v0.3.0)

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