Home > Software engineering >  Change axis label automatically when y parameter is changed in ggplot2
Change axis label automatically when y parameter is changed in ggplot2

Time:03-26

I have the following dataframe:

df <- data.frame(year = c(2020, 2021, 2022),
                 height = c(21, 25, 29),
                 weight = c(10, 12, 15))

I want to plot year vs. height/ weight using ggplot2. To that end, I wrote a function like so:

plot <- function(dataframe,  xvalue, yvalue) {
  ggplot(dataframe) 
    geom_line(aes(x = xvalue, y = yvalue)) 
    #ylab = some code that automatically changes this label based on yvalue
}

For example:

plot(df, df$date, df$height), the y-axis is automatically labeled as "height"

enter image description here

plot(df, df$date, df$weight), the y-axis is automatically labeled as "weight"

enter image description here

I hope I was able to explain the problem.

CodePudding user response:

Your function could be:

my_plot <- function(dataframe,  xvalue, yvalue) {
  ggplot(dataframe, aes(x = {{xvalue}}, y = {{yvalue}}))  
    geom_line() 
}

Which allows:

plot(df, year, height)

enter image description here

Or, based on your comments,

plot <- function(dataframe,  xvalue, yvalue, xlab, ylab) {
  ggplot(dataframe, aes(x = {{xvalue}}, y = {{yvalue}}))  
    geom_line()  
    xlab(xlab)  
    ylab(ylab)
}

Which allows:

plot(df, year, height, 'Year', 'Height (in inches)')

enter image description here

CodePudding user response:

This is what I would do: create two lists (1) variable names, (2) variable labels then loop through them

library(tidyverse)

df <- data.frame(year = c(2020, 2021, 2022),
                 height = c(21, 25, 29),
                 weight = c(10, 12, 15))
# var name
y_var <- colnames(df[colnames(df) != "year"])
# var label
y_label <- c("Height (feet)", "Weight (lbs)")

# plot function
time_plot <- function(DF,  x_var, y_var, x_lab, y_lab) {
  plt <- ggplot(DF, aes(x = .data[[x_var]], y = .data[[y_var]]))  
    geom_line()  
    labs(x = x_lab,
         y = y_lab)  
    theme_classic(base_size = 14)
  
  return(plt)
}

# loop using `map2`
plt_list <- map2(y_var, y_label, 
                 ~ time_plot(df,  "year", .x, "Year", .y))
plt_list[[1]]

plt_list[[2]]

# combine all plots
library(egg)
ggarrange(plots = plt_list,
          ncol = 2,
          labels = c('A)', 'B)'))

Created on 2022-03-25 by the reprex package (v2.0.1)

  • Related