I'm plotting a species prediction map in ggplot using a spatial pixels data frame. I have the plot pretty much how I want it, the only problem is that my raster scale goes from white to red and so it's hard to see where it begins in the legend see the plot. I want to draw a box to outline to the legend key- just the bar going from white to red not the rest of it. I've being searching for over an hour but I can't find any way to do this, only ways to give the legend a background or draw a box around the legend text and bar, which I don't want to do. Does anyone know if this is possible to do in ggplot or do I need to change my colour gradient?
Thanks!
My plotting code:
ggplot() +
geom_raster(data=habs_pop_clip1, aes(x = easting.x, y = northing.x, fill = pred)) +
scale_fill_gradient("Probability of occurrence", low="white", high="red",limits = c(0,1)) +
coord_fixed(ratio=1, xlim=c(545000, 654000), ylim=c(278000,347000))+
geom_polygon(data=Norfolk1, aes(x=long, y=lat, Group=group), color="grey",fill=NA)+
theme(text = element_text(family = "serif")) +
geom_segment(aes(x = 550000, y = 278500, xend = 560000, yend = 278500), lineend = "round") +
annotate("text", x = 555000, xend = 555000, y = 282000, yend = 282000, label = "10 km", family = "serif", size = 4) +
ggtitle(colnames(bat_occ[i+7])) +
theme(plot.margin=unit(c(0.5, 0.5, 0.5, 0.5), "cm")) +
theme_bw() +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.line=element_blank(),
axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
axis.text =element_blank())
I don't know if there's a built-in parameter. If not, you could add a rectangle manually,
df <- reshape2::melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))+ scale_fill_continuous(guide = "colorbar")
g <- ggplotGrob(p)
g$grobs[[8]][[1]][[1]] <- gtable::gtable_add_grob(g$grobs[[8]][[1]][[1]],
rectGrob(gp=gpar(fill=NA, lwd=5)), 4, 2)
grid.newpage()
grid.draw(g)