Search code examples
rggplot2graphicslabelaxis-labels

ggplot2: Axis labels taken from variable names instead of labs()


I am trying to create a series of similar functions to create bar graphs of mean income within quantile ranges: quartiles, quintiles, deciles and percentiles. In the example below, the quart_iles function gathers the arguments and includes all the information specific to the "quart" part. The isles function does the drawing with ggplot2, and the intermediate bar_isles function hands the arguments from quart_isles to isles via do.call, in a mainly-successful effort to get around non-standard evaluation problems with calls to ggplot within a function.

The one exception is the axis labels, which are ignored in favor of the names of the variables they represent. I'm puzzled by this, particularly as the code seems identical to that of the title and subtitle, which are working fine.

I think part of my difficulty in figuring this out is that I don't really understand what the "+" notation does. It seems to be more like f(g()) than f(); g();, but I don't think it is exactly either one. But I would still happily accept an answer to the former question without the latter

quart_args <- list(.tit = "U.S. Personal Income Distribution by Quartile xxx",
                   .sub = "Persons by adjusted household income ($2016)",
                   .nms = as.factor(c("1st", "2nd", "3rd", "4th")),
                   .yl  = "Mean Income",
                   .xl  = "Income Quartiles")

#############################################################################

quart_iles <- function(.data){
  names(.data)[1]<- "Quartiles"
  out <- bar_iles(.data, .args = quart_args)
  }

bar_iles <- function(.data, .args){
  force(.data)                              
  out <- do.call(iles, args = c(list(.dt = .data), .args))
}

iles<- function(.dt, .tit, .sub, .nms, .xl, .yl, ...){
  out <- ggplot(data = .dt) + 
    geom_col(mapping = aes(x=.nms, y=Quartiles)) +
    labs(title = .tit, subtitle = .sub, xlab = .xl, ylab = .yl) + 
    theme_light()
}

gg1 <- quart_iles(.data = tibble(10:13))
gg1

Solution

  • There is an incorrect specification of the arguments in the call to labs.

    iles<- function(.dt, .tit, .sub, .nms, .xl, .yl, ...){
    out <- ggplot(data = .dt) + 
    geom_col(mapping = aes(x=.nms, y=Quartiles)) +
    labs(title = .tit, subtitle = .sub, x = .xl, y = .yl) + 
    theme_light()
    

    Changing the function iles in this way should do the trick

    enter image description here