0

The library ggplot2 produces the following well known warning when replacing the scale fill:

Scale for fill is already present.
Adding another scale for fill, which will replace the existing scale.

Which is typically produced as follows:

library("ggplot2")
data <- data.frame(group = LETTERS[1:3], value = 1:9)
figure <- ggplot(data, aes(x = group,  y = value, fill = group)) + 
  geom_boxplot() +
  scale_fill_manual(values = c("#1b98e0", "yellow", "#353436")) +
  scale_fill_discrete(guide = guide_legend(reverse = TRUE))   # Produces scale fill warning
print(figure)

While the typical recommendation is to simply not replace the scale fill, we are using a library call that has a default rendering scheme defined and the code cannot be edited. However, for the purposes of accessibility we allow the user to override the palette, which in turn will produce the warning.

Is there a way to suppress only the scale fill warning from ggplot2?

stefan
  • 90,330
  • 6
  • 25
  • 51
rjzii
  • 14,236
  • 12
  • 79
  • 119

1 Answers1

1

Best practices call for preventing a warning from being generated if possible since warning suppression can hide other possible problems. However, in this case since the intent is the replacement of the originally defined scale fill it is possible to use the same approach as removing the scale from a plot, namely:

# Define a basic plot
library("ggplot2")
data <- data.frame(group = LETTERS[1:3], value = 1:9)
figure <- ggplot(data, aes(x = group,  y = value, fill = group)) + 
  geom_boxplot()

# Remove any scales
figure$scales$scales <- list()

# Now define our own scale
figure <- figure + scale_fill_manual(values = c("#1b98e0", "yellow", "#353436"))
print(figure)
rjzii
  • 14,236
  • 12
  • 79
  • 119