Search code examples
rggplot2gridextragtable

set Text-background to ggplot axis-text


I have a ggplot graphich and it has a long text as Y-axis .

I'm trying to find a way to set background-color for the Y-axis with tow different colors "zebra-theme" like this one

but it seems that there is no ggplot feature in element_text() for this .

Can someone help me please.

thanks

Tlopasha


Solution

  • it's probably possible if you hack the theme system, but it's probably not a good idea.

    enter image description here

    library(grid)
    
    element_custom <- function(...) {
      structure(list(...), class = c("element_custom", "element_blank"))
    }
    
    element_grob.element_custom <- function(element, label, x, y, ...)  {
      tg <- textGrob(label, y=y, gp=gpar(col=element$colour))
      padding <- unit(1,"line")
      rg <- rectGrob(y=y,width=grobWidth(tg)+padding, height=unit(1,"line")+padding, 
                     gp=gpar(fill = element$fill, col=NA, alpha=0.1))
      gTree(children=gList(rg, tg), width=grobWidth(tg) + padding, cl="custom_axis")
    }
    
    widthDetails.custom_axis <- function(x) x$width + unit(2,"mm") # fudge
    
    
    qplot(1:3,1:3) +
      theme(axis.text.y = element_custom(colour = 1:2, fill=1:2))