Skip to content

Instantly share code, notes, and snippets.

@baptiste
Created June 3, 2023 22:13
Show Gist options
  • Save baptiste/0caf0fca177685616bf403c92aafff83 to your computer and use it in GitHub Desktop.
Save baptiste/0caf0fca177685616bf403c92aafff83 to your computer and use it in GitHub Desktop.
library(ggplot2)
library(grid)
element_box_break <- function (fill=NULL, colour = NULL, linewidth = NULL, linetype = NULL, lineend = NULL,
color = NULL, arrow = NULL, inherit.blank = FALSE) {
if (!is.null(color))
colour <- color
if (is.null(arrow))
arrow <- FALSE
structure(list(fill=fill, colour = colour, linewidth = linewidth, linetype = linetype,
lineend = lineend, arrow = arrow, inherit.blank = inherit.blank),
class = c("element_box_break","element_rect", "element"))
}
element_grob.element_box_break <- function(element, label="", ...) {
start <- unit(0,'npc')
end <- unit(1,'npc')
space <- unit(4,'mm')
gap <- unit(3,'mm')
s <- segmentsGrob(x0 = unit.c(start,end,end,start,start),
x1 = unit.c(end,end,start,start,start),
y0 = unit.c(start,start,end,end,start+space),
y1=unit.c(start,end,end,start+space+gap,start),
gp=gpar(col='black')) # c("red","blue",'green','gold')
grobTree(rectGrob(gp=gpar(fill=element$fill, col=NA)), s)
}
element_line_break <- function (colour = NULL, linewidth = NULL, linetype = NULL, lineend = NULL,
color = NULL, arrow = NULL, inherit.blank = FALSE) {
if (!is.null(color))
colour <- color
if (is.null(arrow))
arrow <- FALSE
structure(list(colour = colour, linewidth = linewidth, linetype = linetype,
lineend = lineend, arrow = arrow, inherit.blank = inherit.blank),
class = c("element_line_break","element_line", "element"))
}
element_grob.element_line_break <- function(element, label="", ...) {
start <- unit(0,'npc')
end <- unit(1,'npc')
space <- unit(4,'mm')
gap <- unit(3,'mm')
s <- segmentsGrob(x0 = unit.c(end - gap,end - gap, end, end),
x1 = unit.c(end + gap, end + gap, end, end),
y0 = unit.c(start+space-0.5*gap,start+space+0.5*gap,start,start+space+gap),
y1=unit.c(start+space+0.5*gap,start+space+1.5*gap,space,end),
gp=gpar(col='black')) # c("red","blue",'green','gold')
s
}
set.seed(1234)
d <- data.frame(x=1:10,y=runif(10, 12,13))
theme_set(theme_bw())
ggplot(d,aes(x,y)) +
geom_point() +
# coord_cartesian(ylim=c(11.94,max(d$y))) +
theme(axis.line.y = element_line_break(),
panel.background = element_box_break(fill='grey98'),
panel.border = element_box_break(fill=NA))
@baptiste
Copy link
Author

baptiste commented Jun 3, 2023

Screenshot 2023-06-04 at 10 13 54

@baptiste
Copy link
Author

baptiste commented Jun 3, 2023

Would be tricky to do in ggplot2: first, need to replace element_line in axis.line to draw the broken axis, replace panel.background and panel.border to skip the gap—then the hard part: add absolute space below/left after training scales, axis breaks that avoid clashes, support for secondary axes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment