Skip to content

Hash for guide_train should take colours into account #4280

Closed
@eliocamp

Description

@eliocamp

When using ggnewscale, legends can disappear if they have the same title and breaks:

library(ggplot2)
library(ggnewscale)

data <- expand.grid(y = 1:4, x = 1:4)
data$z <- c("a", "b")

ggplot(data, aes(x, y)) +
  geom_tile(data = ~.x[.x$x == 1, ], aes(fill = z)) +
  scale_fill_brewer(palette = 1) +
  new_scale_fill() +
  geom_tile(data = ~.x[.x$x == 2, ], aes(fill = z)) +
  scale_fill_brewer(palette = 2) 

What's going on is that ggplot2 is merging both guides because they have the same title and labels. Changing the name of each scale makes them distinct.

ggplot(data, aes(x, y)) +
  geom_tile(data = ~.x[.x$x == 1, ], aes(fill = z)) +
  scale_fill_brewer(name = "1", palette = 1) +
  new_scale_fill() +
  geom_tile(data = ~.x[.x$x == 2, ], aes(fill = z)) +
  scale_fill_brewer(name = "2", palette = 2) 

The problem is that guide_train.legend computes the hash using the title, labels, direction and name:

digest::digest(list(title, key$.label, direction, name))

In the first example, all of those characteristics are the same, and the guides are merged. Ideally, the hash should include information on the colours included in key[[aes_column_name]]

This small hack is a small proof of concept of how it would work:

my_guide <- function(...) {
  guide <- guide_legend(...)
  class(guide) <- c("my_guide", class(guide))
  guide
}

guide_train.my_guide <- function (guide, scale, aesthetic = NULL) {
  guide <- NextMethod("guide_train")
  
  guide$hash <-  with(guide, 
                      digest::digest(list(title, 
                        key$.label, direction, name, key[, 1]  # should be `key[[aes_column_name]]`
                                                 )))
  guide
}

ggplot(data, aes(x, y)) +
  geom_tile(data = ~.x[.x$x == 1, ], aes(fill = z)) +
  scale_fill_brewer(palette = 1, guide = my_guide()) +
  new_scale_fill() +
  geom_tile(data = ~.x[.x$x == 2, ], aes(fill = z)) +
  scale_fill_brewer(palette = 2, guide = my_guide()) 

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions