2

This example code gives me everything I want except for the colorbar labels.

require(ggplot2)
require(RColorBrewer)
df    <- faithfuld
pbase <- ggplot(data=df, aes(x=waiting, y=eruptions))
p1    <- pbase + geom_contour_filled(aes(z=100*density),
                  show.legend=T) +
                  scale_fill_manual(values=brewer.pal(11,"Spectral"),
                  guide = guide_colorsteps(direction="horizontal",
                  title.position="top",
                  title="Density*100.")) +
                 theme(legend.position="top")

enter image description here

Rather than the default labels, what I'd like are labels just at the end points of the bar. I have tried using the "draw.ulim" and "draw.llim" parameters in the guide, but they seem to have no effect. I've searched for similar posts, but not found an answer to this question.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Fleetboat
  • 189
  • 7
  • Maybe you want `guide_colorsteps( ... , show.limits = TRUE)`. – stefan Jun 06 '21 at 16:38
  • Thanks. Stefan. I tried that too. No joy, I'm afraid. That does add the end point values, but does not eliminate the intermediate labels. – Fleetboat Jun 06 '21 at 17:17
  • One more thing - I did try including label=F, but then all the labels including the end points disappear. – Fleetboat Jun 06 '21 at 17:25

1 Answers1

4

Not a perfect solution but maybe it fits your needs:

  1. To show the endpoints add show.limits=TRUE as I already suggested in my comment.
  2. To get rid of the intermediate labels I make use of a custom labeller function. This function is called two times by the scale. Once for the default intermediate breaks (which in almost(!!) all cases is a vector of length > 2) and once for the limits (which is a vector of length 2). Hence I check for the length of the passed vector and keep only the labels for the "limits". But keep in mind that this is only a kind of heuristic which may fail in extreme special cases.
require(ggplot2)
#> Loading required package: ggplot2
require(RColorBrewer)
#> Loading required package: RColorBrewer
df    <- faithfuld
pbase <- ggplot(data=df, aes(x=waiting, y=eruptions))

fun_lab <- function(x) {
  if (length(x) == 2) x else ""
}

p1    <- pbase + geom_contour_filled(aes(z=100*density),show.legend=T) +
  scale_fill_manual(values=brewer.pal(11,"Spectral"),
                    labels = fun_lab,
                    guide = guide_colorsteps(direction="horizontal",
                                             title.position="top",
                                             title="Density*100.", show.limits = TRUE)) +
  theme(legend.position="top")
p1

stefan
  • 90,330
  • 6
  • 25
  • 51