Writing Plotting Functions in R

For the final part of this week, we are going to take what we’ve learned about data frame functions and create functions that produce visualizations.

📖 Required Reading: R4DS – Functions

Read only Section 4 (Plot functions)!

Check-in 7.3: Writing Plotting Functions

Question 1: Fill in the code below to build a rich plotting function which:

  • draws a scatterplot given dataset and x and y variables,
  • adds a line of best fit (i.e. a linear model with no standard errors)
  • add a title.
labeled_scatterplot <- function(df, x_var, y_var) {
  
  label <- rlang::englue("A scatterplot of _____ and _____, including a line of best fit.")
  
  df |> 
    ggplot(mapping = aes(x = _____, 
                         y = _____
                         )
           ) + 
    geom_point() + 
    geom_smooth(method = "lm", _____) +
    labs(title = _____)
}

Question 1: Fill in the code below to build a rich plotting function which:

  • creates a barplot of the counts of each level of a categorical variable
  • sorts the bars in ascending order (smallest to largest)
  • capitalizes the names of the levels of the variable
ascending_bars <- function(df, cat_var) {
  
  # To make the y-axis label of the 
  y_title <- as_label(enquo(cat_var))
  
  df |> 
    mutate(
      ## Order the levels based on the number of observations
      {{ cat_var }} := ____({{ cat_var }}),
      
      ## Relabel the levels to be capitalized 
      {{ cat_var }} := ____({{ cat_var }}, 
                            .fun = ~ str_to_title(.x)
                            )
           )  |>
    ggplot(aes(y = {{ cat_var }})) +
    geom_bar() +
    labs(x = "Number of Observations",
         y = str_to_title(y_title)
         )
}
Tip

You’ll notice that I can’t use y = str_to_title({{ cat_var }}). That is because the str_to_title() function expects string inputs. So, I needed to transform the input variable (cat_var) into a string (e.g., “species”).

Here is how this process works:

Step Code Action
1 ensym(cat_var) Turns the argument you passed into the function (e.g., cat_var = species) into the symbol species.
2 as_label(ensym(cat_var)) Turns the symbol species into the string "species"
3 str_to_title(as_label(ensym(cat_var))) Capitalizes the string ("species" becomes "Species")