Search code examples
rggplot2legend

legend ticks outside of the key box in ggplot2


I'm trying to generate a "satisfactory" legend using ggplot2, but what frustrates me is the position of ticks (they are inside the legend key). Here is some code to show what I mean.

library(ggplot2)

ggplot(mtcars, aes(x = cyl, y = gear, fill = mpg)) +
  geom_tile() +
  coord_equal() +
  theme(legend.position = 'top')

What I get is below. The ticks are inside the legend key box. Ticks inside the legend key (I hate this)

Is there a way to put the ticks outside of the legend key box? Just like this legend (it look like they did this with ggplot2):

enter image description here

Any suggestion would be appreciated!!!


Solution

  • Just for anyone who stumbles across this – I found an easy solution to put the ticks outside the colorbar (as shown by @Serigne Mbacké Coly) and remove them on one side completely:

    ggplot(mtcars, aes(x = cyl, y = gear, fill = mpg)) +
      geom_tile() +
      coord_equal() +
      theme(
        legend.position = 'top', 
        legend.ticks.length = unit(c(-.15, 0), 'cm'), # different lengths for ticks on both sides
        legend.ticks = element_line(color='black') # just to show the ticks on a white background
      )
    

    enter image description here