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()
.
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:
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.
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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With