在ggplot中嵌入一个子图(ggsubplot)

时间:2013-12-20 16:33:32

标签: r ggplot2

我正在尝试使用ggplot重新创建这个基本生成的绘图,但我想使用比demonstrated here更优雅的工作流程,它直接依赖于grid::viewport()

enter image description here

使用 ggsubplot ,我尝试了:

require(ggplot2)
require(ggsubplot)
d = data.frame(x = sort(rlnorm(300)), y = sort(rlnorm(300)), grp = 1)
ggplot(d, aes(x, y)) + geom_point() + theme_bw() +
  scale_x_continuous(limits=c(0, 10)) + scale_y_continuous(limits=c(0, 10)) +
  geom_subplot(data=d, aes(x=5, y=1, group = grp, subplot = geom_point(aes(x, y))), width=4, height=4)

产生了以下令人失望的结果:

enter image description here

显然需要一些工作,但如果将轴,标签和网格添加到子图中,它就不远了。知道怎么做吗?我找不到任何这方面的例子,ggsubplot默认删除这些元素。提前谢谢。

3 个答案:

答案 0 :(得分:12)

使用笛卡尔坐标,我会使用annotation_custom

require(ggplot2)
d = data.frame(x = sort(rlnorm(300)), y = sort(rlnorm(300)), grp = 1)

main <- ggplot(d, aes(x, y)) + geom_point() + theme_bw() 

sub <- main + geom_rect(data=d[1,],xmin=0, ymin=0, xmax=5, ymax=5, 
                        fill="blue", alpha=0.5)
sub$layers <- rev(sub$layers) # draw rect below

main + annotation_custom(ggplotGrob(sub), xmin=2.5, xmax=5, ymin=0, ymax=2.5) +
  scale_x_continuous(limits=c(0, 5)) + scale_y_continuous(limits=c(0,4))

enter image description here

答案 1 :(得分:2)

您可能需要使用位置和颜色等,但似乎添加reference作品

ggplot(d, aes(x, y)) + geom_point() + theme_bw() +
  scale_x_continuous(limits=c(0, 10)) + scale_y_continuous(limits=c(0, 10)) +
  geom_subplot(data=d, aes(x=5, y=1, group = grp, subplot = geom_point(aes(x, y))), width=4, height=4,reference=ref_box(fill = "grey90", color = "black"))

作品

答案 2 :(得分:2)

这是你的想法吗?

编辑:添加了@ geotheory的编辑,仅绘制了1 geom_rect(...)

您可以使用viewports包中的grid执行此操作。

require(ggplot2)
set.seed(123)
d   <- data.frame(x = sort(rlnorm(300)), y = sort(rlnorm(300)), grp = 1)
ggp <- ggplot(d, aes(x, y)) + 
  geom_point() + theme_bw() +
  scale_x_continuous(limits=c(0, 5)) + 
  scale_y_continuous(limits=c(0, 5)) 

sub <- ggplot(d)+geom_point(aes(x,y))+
  theme_bw()+
# assign single row data object so only one rectangle is drawn  
  geom_rect(data=d[1,],xmin=0,ymin=0,xmax=5,ymax=5,fill="blue",alpha=0.5)

library(grid)
grid.newpage()
print(ggp)
vp <- viewport(width = .6, height = .6, x=.37, y=.06,just=c("left","bottom"))
pushViewport(vp)
print(sub,vp=vp)