rggplot2ggridges

ggridges - controlling legend


I have a ridge plot where I'm colouring points by a grouping that doesn't affect the ridges. I would like to have a continuous point_colour legend using viridis, but can't figure out how to control it. I have an example below showing how to control a discrete point_colour aesthetic and legend successfully. How do I do the same, but with a continuous point_colour aesthetic?

toy example:

iris %>% 
    mutate(Group = sample(1:4, n(), replace = TRUE)) %>%
    ggplot() +
    geom_density_ridges(aes(x = Sepal.Length, y = Species, point_colour = as.factor(Group), group = Species),
            rel_min_height = 0.005, jittered_points = TRUE) +
    scale_y_discrete(expand = c(0.01, 0)) +
    scale_x_continuous(expand = c(0.01, 0)) +
    theme_ridges() +
    scale_discrete_manual("point_colour",
                        values = viridis::viridis(n = 4,
                                                  begin = 0, end = 1, direction = 1),  name = "Group") +
    guides(point_colour = guide_legend(override.aes = list(fill = "white", colour = "white")))

Solution

  • The issue with the legend when using a continuous color scale for point_colour is that by default a GuideColourbar can only be used for the color or fill aes. But a possible fix would be to extend GuideColourbar by adding point_colour to the available aesthetics:

    library(ggplot2)
    library(ggridges)
    library(dplyr, warn = FALSE)
    
    set.seed(123)
    
    GuideColourbar2 <- ggproto(
      "GuideColourbar2", GuideColourbar,
      available_aes = c(
        GuideColourbar$available_aes,
        "point_colour"
      )
    )
    
    iris %>%
      mutate(Group = sample(1:4, n(), replace = TRUE)) %>%
      ggplot() +
      geom_density_ridges(
        aes(
          x = Sepal.Length, y = Species,
          point_colour = Group, group = Species
        ),
        rel_min_height = 0.005, jittered_points = TRUE
      ) +
      scale_y_discrete(expand = c(0.01, 0)) +
      scale_x_continuous(expand = c(0.01, 0)) +
      theme_ridges() +
      scale_color_viridis_c(
        aesthetics = "point_colour",
        guide = GuideColourbar2
      )
    #> Picking joint bandwidth of 0.181