Search code examples
rggplot2plotaxis-labels

How to label axes on a plot when making a custom function?


I need to make a custom function that would be draw several separate boxplot graphs. My function has two arguments: one for the x-axis, another for the y-axis. I want to label them with the names of the columns from my data frame that I'm using as arguments. The problem is when I use colnames() to extract column names it doesn't show anything on the graph, not even the letters a and b that are used as arguments (it used to show them when I didn't have the labs() layer). Can you help me fix this? My code is below.

forestfires <- 
 read.csv(url(
  "https://archive.ics.uci.edu/ml/machine-learning-databases/forest-fires/forestfires.csv"))

require(ggplot2)

boxplot_months <- function(a,b) {
  ggplot(data = forestfires) +
    aes_string(x=a, y=b) +
    geom_boxplot() +
    theme(panel.background = element_rect(fill="white")) +
    labs(x=colnames(a), y=colnames(b))
 }

boxplot_months(forestfires$month, forestfires$FFMC)

Solution

  • aes_string takes characters as input.

    That being said, by passing the arguments as strings, you can use a and b in labs() as well. However, I should mention that colnames(forestfires$month) is simply none since after extracting a column you simply have a vector not that column anymore.

    forestfires <- 
      read.csv(url(
        "https://archive.ics.uci.edu/ml/machine-learning-databases/forest-fires/forestfires.csv"))
    
    boxplot_months <- function(a,b, mydataset) {
     require(ggplot2)
      ggplot(mydataset) +
        geom_boxplot(aes_string(a,b)) +
        theme(panel.background = element_rect(fill="white"))+
        labs(x=a, y=b)
    }
    
    boxplot_months("month", "FFMC", forestfires)
    

    Created on 2019-06-26 by the reprex package (v0.3.0)