Ggplot, drawing multiple lines along the edges

I drew two panels in a column using the ggplot2 face, and would like to add two vertical lines across the panels at x = 4 and 8. Below is the code:

library(ggplot2) library(gtable) library(grid) dat <- data.frame(x=rep(1:10,2),y=1:20+rnorm(20),z=c(rep("A",10),rep("B",10))) P <- ggplot(dat,aes(x,y)) + geom_point() + facet_grid(z~.) + xlim(0,10) Pb <- ggplot_build(P);Pg <- ggplot_gtable(Pb) for (i in c(4,8)){ Pg <- gtable_add_grob(Pg, moveToGrob(i/10,0),t=8,l=4) Pg <- gtable_add_grob(Pg, lineToGrob(i/10,1),t=6,l=4) } Pg$layout$clip <- "off" grid.newpage() grid.draw(Pg) 

The above code is modified using ggplot, a line of drawing between points along the edges . AND this is the output figure .

There are two problems in this figure. At first, only one vertical line was shown. It seems that moveToGrob only worked once. Secondly, the line shown is not accurate at x = 4. I did not find the variable Pb$panel$ranges , so is there a way I can also correct the range? Thank you very much.

+3
source share
2 answers

In a simple scenario, when the panels have common axes, and the lines extend over the entire y range, you can draw lines along all gtable elements, finding the correct coordinate transformation npc (cf previous post, updated as ggplot2 continues to change)

 library(ggplot2) library(gtable) library(grid) dat <- data.frame(x=rep(1:10,2),y=1:20+rnorm(20),z=c(rep("A",10),rep("B",10))) p <- ggplot(dat,aes(x,y)) + geom_point() + facet_grid(z~.) + xlim(0,10) pb <- ggplot_build(p) pg <- ggplot_gtable(pb) data2npc <- function(x, panel = 1L, axis = "x") { range <- pb$layout$panel_ranges[[panel]][[paste0(axis,".range")]] scales::rescale(c(range, x), c(0,1))[-c(1,2)] } start <- sapply(c(4,8), data2npc, panel=1, axis="x") pg <- gtable_add_grob(pg, segmentsGrob(x0=start, x1=start, y0=0, y1=1, gp=gpar(lty=2)), t=8, b=6, l=4) grid.newpage() grid.draw(pg) 

enter image description here

+5
source

You can just use geom_vline and generally avoid grid clutter:

 ggplot(dat, aes(x, y)) + geom_point() + geom_vline(xintercept = c(4, 8)) + facet_grid(z ~ .) + xlim(0, 10) 

plot with vlines

+3
source

All Articles