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

  • Still looking to remove the ticks from one of the both side, but to put the ticks outside you can use :

    p + theme(legend.ticks.length = unit(-0.15, 'cm')) # Can adjust the length.
    

    The trick is the minus sign (-).