Search code examples
rggplot2colorbarlegend-properties

How can I customize labels in ggplot guide_colorsteps?


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.


Solution

  • 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