Search code examples
rexpss

Expss labels are they accessible to ggplot title?


I wish to add titles to ggplot from Expss variable labels. The Expss package creates a new data type with variable labels and value labels (with underlying numbers). Is there some way of accessing the variable label assigned by referencing the variable name and including it as a title in ggplot? Similarly, could the Expss table caption come from the variable label?


Solution

  • Generally speaking you can easily get variable label with var_lab function: var_lab(my_dataframe$my_variable). In example below you can see how it is used with table caption and ggplot:

    library(ggplot2)
    library(expss)
    data(mtcars)
    mtcars = apply_labels(mtcars,
                          mpg = "Miles/(US) gallon",
                          cyl = "Number of cylinders",
                          disp = "Displacement (cu.in.)",
                          hp = "Gross horsepower",
                          drat = "Rear axle ratio",
                          wt = "Weight (1000 lbs)",
                          qsec = "1/4 mile time",
                          vs = "Engine",
                          vs = c("V-engine" = 0,
                                 "Straight engine" = 1),
                          am = "Transmission",
                          am = c("Automatic" = 0,
                                 "Manual"=1),
                          gear = "Number of forward gears",
                          carb = "Number of carburetors"
    )
    
    # table with caption from label
    cro_cpct(mtcars$am, mtcars$vs) %>% set_caption(var_lab(mtcars$am))
    
    # ggplot with title from label
    use_labels(mtcars, {
        # '..data' is shortcut for all 'mtcars' data.frame inside expression 
        ggplot(..data) +
            geom_point(aes(y = mpg, x = wt, color = qsec)) +
            facet_grid(am ~ vs) +
            ggtitle(var_lab(mpg))
    }) 
    

    ggplot with labels and title