需求

我用ggplot2做了两幅图:

  • 柱形图
library(ggplot2)
df<-data.frame(x=LETTERS[1:10],y=10:1)
df
ggplot()+
geom_bar(data=df,aes(x=x,y=y,fill=x),
stat="identity")+theme_bw()+
theme(legend.position = "none")

ggplot2:在一幅图中插入另外一幅图_公众号 image.png

  • 饼图
ggplot()+
geom_bar(data=df[1:5,],aes(x="",y=y,fill=x),
stat="identity")+theme_bw()+
coord_polar("y",start=0)+
theme_bw()+
theme(axis.title = element_blank(),
axis.text = element_blank(),
legend.position = "none",
panel.border = element_blank(),
panel.grid = element_blank())+
scale_fill_brewer(palette="Set1")

ggplot2:在一幅图中插入另外一幅图_ide_02 image.png

我现在想要把饼图放到柱形图的右上角

如何实现?

找到了函数

  • ​ggplotGrob()​
  • ​annotation_custom()​​ 完整代码
library(ggplot2)
df<-data.frame(x=LETTERS[1:10],y=10:1)
df
p1<-ggplot()+
geom_bar(data=df,aes(x=x,y=y,fill=x),
stat="identity")+theme_bw()+
theme(legend.position = "none")

p2<-ggplot()+
geom_bar(data=df[1:5,],aes(x="",y=y,fill=x),
stat="identity")+theme_bw()+
coord_polar("y",start=0)+
theme_bw()+
theme(axis.title = element_blank(),
axis.text = element_blank(),
legend.position = "none",
panel.border = element_blank(),
panel.grid = element_blank())+
scale_fill_brewer(palette="Set1")
g<-ggplotGrob(p2)
p1+annotation_custom(g,xmin=5,xmax=12,ymin=5,ymax=10)

ggplot2:在一幅图中插入另外一幅图_饼图_03 image.png

另外的小知识点

ggplot2去掉边框和底纹

theme(panel.border = element_blank(),
panel.grid = element_blank())

欢迎大家关注我的公众号

小明的数据分析笔记本


ggplot2:在一幅图中插入另外一幅图_公众号_04 公众号二维码.jpg