I have a plot in ggplot and I wish to overlay a map legend that I have created with base R code. I do not know how to overlay base R graphics on top of a ggplot and would b
@baptiste's comment got me interested in trying to create a plot that would become the legend. Here's my attempt. I use geom_tile to create a plot that will become the legend. The OP didn't provide sample data so I've created a plot using the built-in mtcars data, just to have something to put the legend next to. Then I use grid.arrange to create the final plot-plus-legend layout.
library(ggplot2)
library(grid)
library(gridExtra)
## Create legend
# Fake data
dat = data.frame(x=1:4, y="Group", col=factor(1:4))
# Create a plot that will become the legend
legend = ggplot(dat, aes(x,y, fill=col)) +
geom_tile(show.legend=FALSE) +
scale_x_continuous(breaks=c(1.5,2.5,3.5), labels=c(5,10,20)) +
scale_fill_manual(values=c("yellow","orange","red","darkred")) +
labs(y="", x="") +
ggtitle("No. of Restaurants") +
theme_bw() +
theme(panel.border=element_blank(),
axis.ticks.y=element_blank(),
axis.text.y=element_blank())
## Create a plot to put next to the legend
p1 = ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
theme(plot.margin=unit(c(0,0,0,0)))
# Arrange plot and legend
grid.arrange(p1, arrangeGrob(rectGrob(gp=gpar(col=NA)),
legend,
rectGrob(gp=gpar(col=NA)),
heights=c(0.42,0.16,0.42)),
widths=c(0.8,0.2))