Skip to content

Instantly share code, notes, and snippets.

@baptiste
Created April 24, 2024 20:19
Show Gist options
  • Save baptiste/10cc7f576e0c5450b66bf0762ea5ef7c to your computer and use it in GitHub Desktop.
Save baptiste/10cc7f576e0c5450b66bf0762ea5ef7c to your computer and use it in GitHub Desktop.
library(ggplot2)
my_axis = function() {
structure("test",
class = c("element_custom","element_blank", "element") # inheritance test workaround
)
}
library(grid)
# returns a gTree with desired text
element_grob.element_custom <- function(element, x,...) {
g1 <- textGrob("Low", y=0,hjust=0, rot = 90)
g2 <- textGrob("High", y=1,hjust=1, rot = 90)
w1 <- grobHeight(g1)
w2 <- grobHeight(g2)
gap <- unit(1,"npc") - w1 - w2
g3 <- rectGrob(y = w1, vjust = 0, width = unit(1,"line"), height=gap)
gTree(children=gList(g1, g2, g3), cl="custom_axis")
}
# gTrees don't know their size and ggplot would squash it, so give it room
grobWidth.custom_axis = heightDetails.custom_axis = function(x, ...)
unit(1, "line")
p <- ggplot(data.frame(x=1:10), aes(x,x)) +
geom_blank() + theme(axis.title.y = my_axis(), plot.background = element_blank())
library(egg)
expose_layout(p)
print(p, newpage = F)
@baptiste
Copy link
Author

Screenshot 2024-04-25 at 08 19 31

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