Dan Metes
Dan Metes

Reputation: 21

How to draw boxes/borders around x or y axis labels?

Is there a way in R to draw boxes/borders around x or y axis labels, possibly angled labels?

I've been using ggplot to create tile charts and found code that places around labels in the data itself (through geom_label: Set ggplot2 label background color but not around labels in the axes themselves.

Chart Example:

enter image description here

Upvotes: 2

Views: 1651

Answers (1)

baptiste
baptiste

Reputation: 77096

library(grid)

element_custom <- function() {
  structure(list(), class = c("element_custom", "element_text"))
}

element_grob.element_custom <- function(element, label="", ...)  {
  tg <- textGrob(label)
  padding <- unit(1,"line")
  rg <- rectGrob(width=grobWidth(tg)+padding, height=grobHeight(tg)+padding)
  gTree(children=gList(rg, tg), height=grobHeight(tg) + padding, cl="custom_axis")
}

heightDetails.custom_axis <- function(x) x$height + unit(2,"mm") # fudge

ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_line() + 
  labs(x= "Axis title")+
  (theme_grey() %+replace% theme(axis.title.x = element_custom()))

enter image description here

Upvotes: 7

Related Questions