1

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

Bryan
  • 1,771
  • 4
  • 17
  • 30

1 Answers1

1

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)

jared_mamrot
  • 22,354
  • 4
  • 21
  • 46
  • Thanks for both of these ideas, but it seems `geom_contour_filled` is using a different color palette than `scale_fill_discrete`, and I haven't yet figured out how to emulate it. I've updated the original post with some images which hopefully make it clearer. – Bryan Jul 18 '22 at 07:27
  • Ahh! Yep, thanks for clarifying - that makes a lot more sense - I've edited my answer to offer a potential solution @Bryan – jared_mamrot Jul 18 '22 at 10:02