0

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?

OTStats
  • 1,820
  • 1
  • 13
  • 22
CK7
  • 229
  • 1
  • 11
  • Could you make your problem reproducible by sharing a sample of your data so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Apr 06 '19 at 18:53

1 Answers1

0

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

Gregory Demin
  • 4,596
  • 2
  • 20
  • 20
  • Okay thanks that makes more sense than manually adding each title, as it utilizes the meta data already added when creating variable label. – CK7 Apr 09 '19 at 21:12