2

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 Answer 1

4

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")

2
  • Thank you very much, you made it easy :) Please, can you help me with how to add an arrow on the legend side with mentioning Low and High?
    – user15639265
    Apr 2 at 19:46
  • Not 100% about desired result. But see my edit for an approach to include arrows.
    – stefan
    Apr 2 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy