Skip to content

Nothing plotted with manual_scale when a named vector is used as the input. #4087

Closed
@ds-jim

Description

@ds-jim

When building a manual_scale ggplot shows no data when the number of colours <= the number in the scale when a named vector is used. Strangely the colours work when the number of colours > the number in the scale. This seems to be fixed by using an unnamed vector.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(scales)
library(ggplot2)
library(tibble)


named_vec <- c("teracota" = "#d18975", 
                 "green" = "#8fd175",
                 "purple" = "#3f2d54")

scale_colour_named <- function(...)
{ discrete_scale("colour", "test_pal",
                 manual_pal(named_vec)) }

scale_colour_unnamed <- function(...)
{ discrete_scale("colour", "test_pal",
                 manual_pal(unname(named_vec))) }


  #Works when n > than pallet
USArrests %>%
  rownames_to_column("State") %>%
  slice(1:4) %>%
  ggplot(aes(x = State, y = Murder, col = State)) +
  geom_point(size = 10, show.legend = FALSE) +
  scale_colour_named()
#> Warning: This manual palette can handle a maximum of 3 values. You have supplied
#> 4.
#> Warning: Removed 1 rows containing missing values (geom_point).

  #No points plotted
USArrests %>%
  rownames_to_column("State") %>%
  slice(1:3) %>%
  ggplot(aes(x = State, y = Murder, col = State)) +
  geom_point(size = 10, show.legend = FALSE) +
  scale_colour_named()
#> Warning: Removed 3 rows containing missing values (geom_point).

  #However, it works without using a named vector
USArrests %>%
  rownames_to_column("State") %>%
  slice(1:3) %>%
  ggplot(aes(x = State, y = Murder, col = State)) +
  geom_point(size = 10, show.legend = FALSE) +
  scale_colour_unnamed()

Created on 2020-06-24 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