How can I customize certain labels, but keep default values, in ggplot guide_colorsteps?

Viewed 39

I am trying to selectively label a subset of a color bar using geom_contour_filled, while continuing to use the default ggplot colour palette. I've figured out how to do the first part by adapting the function from this post: How can I customize labels in ggplot guide_colorsteps? However, I cannot figure out how to replace the labels without also needing to supply a set of values that will change the color palette; I want to keep the ggplot pallet. What is the best way to approach this?

require(ggplot2)
require(RColorBrewer)

fun_lab <- function(x) {
  x[!(x %in% c(1, 2, 3))]<- "" # selected values to label
  return(x)
}

ggplot(data=faithfuld, aes(x=waiting, y=eruptions)) +
  geom_contour_filled(aes(z=100*density),show.legend=T) +
  scale_fill_manual(values=brewer.pal(11,"Spectral"), # would like to omit this
                    labels = fun_lab,
                    guide = guide_colorsteps(direction="horizontal",
                                             title.position="top")) +
  theme(legend.position="top")

This produces the following plot, which formats the label the way I want, but changes the colors from the defaults:

desired label format

However, my goal is to produce a plot with the default color palette used by geom_contour_filled, like the one below.

ggplot(data=faithfuld, aes(x=waiting, y=eruptions)) +
  geom_contour_filled(aes(z=100*density),show.legend=T) +
  theme(legend.position="top")

desired color palette

1 Answers

Thanks for commenting and clarifying your question; the default palette used for geom_contour_filled() is the viridis palette. One potential solution to your problem is to use the scale_fill_viridis_d() function, e.g.

library(tidyverse)

fun_lab <- function(x) {
  x[!(x %in% c(1, 2, 3))]<- "" # selected values to label
  return(x)
}

ggplot(data=faithfuld, aes(x=waiting, y=eruptions)) +
  geom_contour_filled(aes(z=100*density),show.legend=T) +
  scale_fill_viridis_d(labels = fun_lab,
                       guide = guide_colorsteps(direction="horizontal",
                                               title.position="top")) +
  theme(legend.position="top")

Created on 2022-07-18 by the reprex package (v2.0.1)

Related