Search code examples
rggplot2

xlab in theme in ggplot2


I'm making many graphs which have same xlab. I wonder can we use xlab in theme like this:

theme_mine1 <- opts(
      panel.grid.major = theme_blank()
    , panel.grid.minor = theme_blank()
    , panel.background = theme_blank()
    , axis.line        = theme_blank()
    , xlab             = expression(paste("My (xlab ", m^{-2}, ")"))
    )

When I use this theme it doesn't give any error or warning but it does not change the xlab. What can I try next?


Solution

  • You can use opts(labels=list(x='xlabelhere'),...).

    A note on how I found this out (because I didn't know it before, and think it's very useful):

    There is a fantastic stackoverflow question on finding what can be fed in to opts here.

    In summary it references the ggplot2 wiki for opts. It also says you can use plot_theme(p) to see all options currently applied to plot p.

    In your case the ggplot2 opts link didn't yield any results for the x label, but doing plot_theme(p) on p from your previous questions, one could see:

    > names(plot_theme(p))
     [1] "labels"             "axis.line"          "axis.text.x"       
     [4] "axis.text.y"        "axis.ticks"         "axis.title.x"      
     [7] "axis.title.y"       "axis.ticks.length"  "axis.ticks.margin" 
    [10] "legend.background"  "legend.key"         "legend.key.size"   
    [13] "legend.key.height"  "legend.key.width"   "legend.text"       
    [16] "legend.text.align"  "legend.title"       "legend.title.align"
    [19] "legend.position"    "legend.direction"   "legend.box"        
    [22] "panel.background"   "panel.border"       "panel.grid.major"  
    [25] "panel.grid.minor"   "panel.margin"       "strip.background"  
    [28] "strip.text.x"       "strip.text.y"       "plot.background"   
    [31] "plot.title"         "plot.margin"       
    

    For your purposes, labels looks very promising!

    So then I tried:

    > plot_theme(p)$labels
    $x
    [1] "x"
    
    $y
    [1] "y/n"
    

    Score! This gives me enough to go on:

    theme_mine1 <- opts(
                    ....,
                    labels=list(x='my xlabel! booya!'))
    

    Which works!