R 图表嵌套 (inset plots)

2020-04-01 15:51:58 浏览数 (1)

有时候看到paper中有的图,大图中嵌套小图:

image.png

这种图在基础作图plot和ggplot2中都可以实现:

  1. plot实现
代码语言:javascript复制
#构造两组数
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') 

可以得到:

image.png

或者也可以用TeachingDemos包中subplot函数这样实现:

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

2.ggplot实现

需要导入grid包的viewport来调整小图的位置和大小。

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

image.png

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

0 人点赞