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 be grateful for assistance.
Currently I have a ggplot legend that looks like this:
There are several things that I do not like about this legend that I would like to change (and that resulted in me thinking it would be easier to resort to base R graphics to do so).
In particular, I wish to eliminate the white space between the boxes in the legend and I wish to add tick marks between the boxes too. I also wish to put "5" beneath the first tick mark separating the first and second boxes; "10" beneath the tick mark separating the second and third boxes; and "20" beneath the tick mark separating the third and forth boxes. I also wish to make the boxes in the legend the same size as one of the "bins" in my plot (I use the stat_bin2d layer).
Relevant code:
ggplot()+
stat_bin2d(restaurants.df,binwidth=c(1500,2500), alpha=0.6,aes(x=X,y=Y,fill=cut(..count.., c(0,5,10,20,Inf))))+
scale_fill_manual("No. of Restaurants",labels=c("<5","5-10","10-20",">20"),values=cols, guide = guide_legend(direction = "horizontal", title.position = "top", ticks=TRUE,label.position="bottom")) +
theme(legend.background = element_rect(colour = "black"),
legend.key = element_rect(color='black'))
@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-inmtcars
data, just to have something to put the legend next to. Then I usegrid.arrange
to create the final plot-plus-legend layout.It might turn out to be easier to define your own custom legend,