前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ggplot2:在一幅图中插入另外一幅图

ggplot2:在一幅图中插入另外一幅图

作者头像
用户7010445
发布2020-03-02 16:38:07
1.1K0
发布2020-03-02 16:38:07
举报

需求

我用ggplot2做了两幅图:

  • 柱形图
代码语言:javascript
复制
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")

image.png

  • 饼图
代码语言:javascript
复制
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")

image.png

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

如何实现? 找到了函数

  • ggplotGrob()
  • annotation_custom() 完整代码
代码语言:javascript
复制
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)

image.png

另外的小知识点

ggplot2去掉边框和底纹

代码语言:javascript
复制
theme(panel.border = element_blank(),
        panel.grid = element_blank())
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-09-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 小明的数据分析笔记本 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 需求
  • 我现在想要把饼图放到柱形图的右上角
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档