Skip to content

scale_colour_manual: Colour for legend key when data is not visible in the plot #6666

@klausbraun

Description

@klausbraun

In one of the examples of

https://ggplot2.tidyverse.org/reference/scale_manual.html

with the help of scale_colour_manual a legend with four keys is created where the dataset mtcars itself only lists cars with three different numbers of cylinders:

cols <- c("8" = "red", "4" = "blue", "6" = "darkgreen", "10" = "orange")
p <- ggplot(mtcars, aes(mpg, wt)) +
  geom_point(aes(colour = factor(cyl)))

p + scale_colour_manual(values = cols, limits = c("4", "6", "8", "10"))

It is clear that in the plot itself there is no point for a car with 10 cylinders, but "10" shows up in the legend. It therefor might be understandable that there is no colour associated with key "10".

But there are also scenarios where it might be useful to draw the colour defined for "10" before which would be "orange". One scenario could be the combination of different plots where different subsets of the data are shown, but only one legend should be used including keys for all data entries occurring at least in one of the plots. An example would be a geographical map with an enlarged inset of a specific region showing more details and including additional features than the "ground map" where the legend keys for this additional features should turn up in the legend.

I know there are solutions with a shared legend and so on, but especially in the case of map-making it would be nice to honour the manually defined colour for a specific legend key. If then there should be no colour shown for this key the colour could be defined as "transparent" which would lead to the actual behaviour.

The expected behaviour would be to show an orange dot in the legend for key "10" in the following illustration:

https://ggplot2.tidyverse.org/reference/scale_manual-7.png

Best

Klaus

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