Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding a subplot in ggplot (ggsubplot)

Tags:

r

ggplot2

I'm trying to recreate this base-produced plot with ggplot, but I want to use a workflow more elegant than the the one demonstrated here, which relies directly on grid::viewport().

enter image description here

Using ggsubplot, I tried:

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)

which produced the following disappointing result:

enter image description here

Obviously needs some work, but if axes, labels and grid are added to the subplot its not far off. Any idea how to do these? I can't find any examples of this, and ggsubplot defaults to removing these elements. Thanks in advance.

like image 656
geotheory Avatar asked Dec 20 '13 16:12

geotheory


2 Answers

With cartesian coordinates, I would use 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

like image 196
baptiste Avatar answered Sep 19 '22 19:09

baptiste


you might have to play with position and color, etc, but it seems like adding reference works

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"))

works

like image 22
Ananta Avatar answered Sep 19 '22 19:09

Ananta