rggplot2

How can I add border to legend swatches in ggplot2?


Consider the following graph:

library(ggplot2)

df = expand.grid(
  x=seq(-1,1,length.out=100),
  y=seq(-1,1,length.out=100)
  )

df$in_circle = with(df, x^2 + y^2 < .5)

ggplot(df, aes(x=x,y=y,z=in_circle)) +
  geom_contour_filled(breaks  = c(-.5,.5,1.5)) +
  scale_fill_manual(
    values = c('white','orange')
  ) +
  theme_minimal()

which looks like this:

Plot created by the code listed above

Note that the white color in the legend isn't clear because it is the same color as the background. I would like to put borders around the swatches without changing the plot. It should look something like this:

Desired plot, same as first plot but with borders around the swatches.

How can I achieve this?


Solution

  • Add

     + theme(legend.key=element_rect(colour='black'))
    

    I thought it must be a duplicate which someone finds and suggests.