We can hack the unexported ggplot2:::guide_gengrob.colorbar
function to simulate such an appearance.
Run
trace(ggplot2:::guide_gengrob.colorbar, edit = TRUE)
and replace the following lines (should be around line 26 or so)
if (guide$raster) {
image <- switch(guide$direction, horizontal = t(guide$bar$colour),
vertical = rev(guide$bar$colour))
grob.bar <- rasterGrob(image = image, width = barwidth,
height = barheight, default.units = "cm", gp = gpar(col = NA),
interpolate = TRUE)
}
with
if (guide$raster) {
image <- switch(guide$direction,
horizontal = with(guide$bar,
rbind(rep("white", length(colour)),
colour,
rep("white", length(colour)))),
vertical = with(guide$bar,
cbind(rep("white", length(colour)),
rev(colour),
rep("white", length(colour)))))
grob.bar <- rasterGrob(image = image, width = barwidth,
height = barheight, default.units = "cm", gp = gpar(col = NA),
interpolate = FALSE)
}
and click 'Save'.
Now the following code
p <- ggplot(mtcars, aes(x = cyl, y = gear, fill = mpg)) +
geom_tile() +
coord_equal() +
scale_fill_continuous(guide = guide_colourbar(ticks.colour = "black"))
# works for both horizontal & vertical legends
p + theme(legend.position = 'top')
p + theme(legend.position = 'right')
produces
To remove the effect at any point during the current R session, run
untrace(ggplot2:::guide_gengrob.colorbar)
(Note: this hack's effect won't persist across R sessions, and needs to be repeated each time this is desired.)
Explanation
The original image
in the code is basically a vector of gradient colours, which is then used to create a raster grob object. In our modified version, we sandwich the vector with two vectors of repeated "white"'s, either horizontally or vertically, so that the visible gradient legend becomes narrower, and the ticks are no longer overlapping it.
We then change interpolate = TRUE
to interpolate = FALSE
in the raster grob's definition, so that we get a sharp transition from white to gradient bar and vice versa.
Lastly, tick colour is set as "black" in the ggplot code, so that the ticks can actually be seen against the white background.