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

geo*_*ory 8 r ggplot2

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

在此输入图像描述

使用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)
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

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

bap*_*ste 13

用笛卡尔坐标,我会用 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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Ana*_*nta 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"))
Run Code Online (Sandbox Code Playgroud)

作品