Add label names on the color bar manually using ggplot2 package

Viewed 140

I want to change my continuous color legend by adding manual label names (Low and High) for values at the bottom and top of the scale bar. How can I do this?

x <- 1:100
y <- runif(100) * 100
tib <- tibble(x, y)

ggplot(tib, aes(x = x, y = y, color = y)) +
  geom_point() +
  binned_scale(aesthetics = "color",
               scale_name = "stepsn", 
               palette = function(x) c("red", "yellow", "green", "yellow", "red"),
               breaks = c(5, 10, 25, 60),
               limits = c(0, 100),
               show.limits = TRUE, 
               guide = "colorsteps")

Intended output:

enter image description here

I tried to adding labels = c("Low", 5, 10, 25, 60, "High") in the script but it showed this error:

Error in f():
! Breaks and labels are different lengths
Run rlang::last_error() to see where the error occurred.
1 Answers

An easy option to achieve this (and which I just figured out) would be to pass a named vector to the limits argument where the names are your desired labels:

set.seed(123)

library(ggplot2)

ggplot(tib, aes(x = x, y = y, color = y)) +
  geom_point() +
  binned_scale(aesthetics = "color",
               scale_name = "stepsn", 
               palette = function(x) c("red", "yellow", "green", "yellow", "red"),
               breaks = c(5, 10, 25, 60),
               limits = c(low = 0, high = 100),
               show.limits = TRUE, 
               guide = "colorsteps")

EDIT Not 100% sure about the arrows but an easy option to add some arrows would be to include the UTF-8 symbol for a left arrow to the labels:

set.seed(123)
x <- 1:100
y <- runif(100) * 100
tib <- data.frame(x, y)

library(ggplot2)

ggplot(tib, aes(x = x, y = y, color = y)) +
  geom_point() +
  binned_scale(aesthetics = "color",
               scale_name = "stepsn", 
               palette = function(x) c("red", "yellow", "green", "yellow", "red"),
               breaks = c(5, 10, 25, 60),
               limits = c("\u2190 low" = 0, "\u2190 high" = 100),
               show.limits = TRUE, 
               guide = "colorsteps")

Related