Inconsistent color scheme in ggplot

Hi there!

I have a problem with inconsistent color/fill scale in ggplot:
In my data.frame, I have a logical variable that states where the specific value should be highlighted. Everything works fine as long as I have both TRUE and FALSE in my data. However, if only one value is present in the data the scale is "broken" and returns only one color indifferent to the actual value. Is there any chance to fix it in the scale_*_discrete or the only way is to switch to scale_*_manual?

suppressMessages({
  library(tibble)
  library(ggplot2)
  library(viridisLite)
})

df <- tibble(x = 1:20,
             y = sample(x = LETTERS, size = 20, replace = TRUE),
             fill = sample(x = c(TRUE, FALSE), size = 20, replace = TRUE))

ggplot(df) +
  geom_tile(aes(x = x,
                y = 1,
                fill = !fill)) +
  geom_text(aes(x = x,
                y = 1,
                label = y,
                color = fill)) +
  scale_fill_viridis_d() +
  scale_color_viridis_d()



df2 <- tibble(x = 1:20,
             y = sample(x = LETTERS, size = 20, replace = TRUE),
             fill = sample(x = c(FALSE), size = 20, replace = TRUE))

ggplot(df2) +
  geom_tile(aes(x = x,
                y = 1,
                fill = !fill)) +
  geom_text(aes(x = x,
                y = 1,
                label = y,
                color = fill)) +
  scale_fill_viridis_d() +
  scale_color_viridis_d()

Created on 2023-09-17 with reprex v2.0.2

use factors to preserve unused levels

df2 <- tibble(x = 1:20,
              y = sample(x = LETTERS, size = 20, replace = TRUE),
              fill = sample(x = factor(c(TRUE, FALSE)), size = 20, replace = TRUE,prob = c(0,1)),
              `! fill` = factor(!as.logical(fill),
                                levels = c(TRUE,FALSE)))

ggplot(df2) +
  geom_tile(aes(x = x,
                y = 1,
                fill = `! fill`)) +
  geom_text(aes(x = x,
                y = 1,
                label = y,
                color = fill)) +
  scale_fill_viridis_d(drop=FALSE) +
  scale_color_viridis_d(drop=FALSE,direction = -1)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.