Skip to content

Change in scale_color_manual behavior in 3.5.x, adds NA to legend #6015

Closed
@jeraldnoble

Description

@jeraldnoble

Per @teunbrand request to open an issue re: #5214 (comment)

NAs are printed in the legend when using scale_color_manual()

> packageVersion("ggplot2")
[1] ‘3.5.1’

df = data.frame(xvar = c(-3,-2,-1,1,2,3), yvar = c(3,2,1,1,2,3), lab_text = c("-3", "-2", NA, NA, "2", "3"), lab_grp = c("down", "down", NA, NA, "up", "up"))

ggplot(df, aes(x = xvar, y = yvar, color = lab_grp)) + geom_point() + scale_color_manual(values = c("down" = "red", "up" = "blue"))

exPlot

Identical plot made without specifying factors

ggplot(df, aes(x = xvar, y = yvar, color = lab_grp)) + geom_point() + scale_color_manual(values = c("red", "blue"))

Likely caused by change ggplot2::manual_scale in line:
x <- intersect(x, c(names(values), NA)) %||% character()

3.4.x code:

> ggplot2:::manual_scale
function (aesthetic, values = NULL, breaks = waiver(), ..., limits = NULL) 
{
   ...
    if (is.null(limits) && !is.null(names(values))) {
        limits <- function(x) intersect(x, names(values)) %||%     
            character()
    }
   ...
    discrete_scale(aesthetic, "manual", pal, breaks = breaks, 
        limits = limits, ...)
}

3.5.x code:

> ggplot2:::manual_scale
function (aesthetic, values = NULL, breaks = waiver(), name = waiver(), 
        ..., limits = NULL, call = caller_call())
    # omitted for brevity
    if (is.null(limits) && !is.null(names(values))) {
        force(aesthetic)
        limits <- function(x) {
            x <- intersect(x, c(names(values), NA)) %||% character()
            if (length(x) < 1) {
                cli::cli_warn(paste0("No shared levels found between {.code names(values)} of the manual ", 
                  "scale and the data's {.field {aesthetic}} values."))
            }
            x
        }
    }
    # omitted for brevity
    discrete_scale(aesthetic, name = name, palette = pal, breaks = breaks, 
        limits = limits, call = call, ...)
}

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