R 图表嵌套 (inset plots)
2020-01-11 本文已影响0人
生信编程日常
有时候看到paper中有的图,大图中嵌套小图:

这种图在基础作图plot和ggplot2中都可以实现:
- plot实现
#构造两组数
x <- rnorm(100)
y <- rbinom(100, 1, 0.5)
# 画主图
par(fig = c(0,1,0,1))
hist(x, breaks = seq(-2, 3, 0.1), col = 'lightblue')
# 画小图
par(fig = c(0.55, 1, 0.5, 1), new = T)
boxplot(x ~ y, col = 'yellowgreen')
可以得到:

或者也可以用TeachingDemos包中subplot函数这样实现:
library(TeachingDemos)
hist(x, col = 'lightblue')
subplot(
boxplot(x~y, col='yellowgreen', mgp=c(1,0.8,0),
xlab='', ylab='', cex.axis=0.5),
x=grconvertX(c(0.75,1), from='npc'),
y=grconvertY(c(0,0.25), from='npc'),
type='fig', pars=list( mar=c(1.5,1.5,0,0)))
- ggplot实现
需要导入grid包的viewport来调整小图的位置和大小。
library(ggplot2)
library(grid)
data(iris)
chart1 <- ggplot(data = iris, aes(x = Sepal.Length, y = Petal.Length, color = Species, shape = Species)) + geom_point() + theme_bw()
chart1
chart2 <- ggplot(data = iris, aes(x = Species, y = Sepal.Length, color = Species)) + geom_boxplot() + guides(color = FALSE ) + xlab('') + ylab('') + theme_bw()
print(chart2, vp = viewport(x = 0.65, y = 0.25, width = 0.3, height = 0.25))

欢迎关注微信公众号:生信编程日常
每天进步一点点~
