繁体   English   中英

R-将图添加到多面ggplot2对象(使用注解_自定义)

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

我正在尝试使用ggplot2annotation_custom (图实际上是我用来替换图例的地图)来插入图。 但是,我也使用facet_wrap生成多个面板,但是当与annotation_custom facet_wrap一起使用时,这将在每个构面中重现绘图。 有没有一种简单的方法可以只将绘图插入一次,最好在绘图区域外?

这是一个简单的示例:

#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!

这将产生以下图: 情节1 当我想进一步了解以下内容时: 理想的 任何帮助表示赞赏。 谢谢!

annotation_custom()的帮助下,注解"are the same in every panel" ,因此预期结果是在每个构面(面板)中都有您的legend.plot。

一种解决方案是将theme(legend.position="none")到基本图中,然后使用grid.arrange() (库gridExtra )来绘制两个图。

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))

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM