jslefche
jslefche

Reputation: 4609

R - add plot to facetted ggplot2 object (using annotation_custom)

I'm trying to inset a plot using ggplot2 and annotation_custom (the plot is actually a map that I'm using to replace the legend). However, I'm also using facet_wrap to generate multiple panels, but when used with annotation_custom, this reproduces the plot in each facet. Is there an easy way to insert the plot only once, preferably outside the plotting area?

Here is a brief example:

#Generate fake data
set.seed(9)
df=data.frame(x=rnorm(100),y=rnorm(100),facets=rep(letters[1:2]),
              colors=rep(c("red","blue"),each=50))
#Create base plot
p=ggplot(df,aes(x,y,col=colors))+geom_point()+facet_wrap(~facets)
#Create plot to replace legend
legend.plot=ggplotGrob(
  ggplot(data=data.frame(colors=c("red","blue"),x=c(1,1),y=c(1,2)),
         aes(x,y,shape=colors,col=colors))+geom_point(size=16)+
         theme(legend.position="none") )
#Insert plot using annotation_custom
p+annotation_custom(legend.plot)+theme(legend.position="none") 
#this puts plot on each facet!

This produces the following plot: plot1 When I would like something more along the lines of: plotideal Any help is appreciated. Thanks!

Upvotes: 0

Views: 1462

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98529

In the help of annotation_custom() it is said that annotations "are the same in every panel", so it is expected result to have your legend.plot in each facet (panel).

One solution is to add theme(legend.position="none") to your base plot and then use grid.arrange() (library gridExtra) to plot both plots.

library(gridExtra)
p=ggplot(df,aes(x,y,col=colors))+geom_point()+facet_wrap(~facets)+
         theme(legend.position="none") 

grid.arrange(p,legend.plot,ncol=2,widths=c(3/4,1/4))

enter image description here

Upvotes: 2

Related Questions