Home > Enterprise >  How to automatically include labels and data in my scatterplot function in R?
How to automatically include labels and data in my scatterplot function in R?

Time:08-16

I'm going back to practicing making functions at the moment and I came up with this super basic scatterplot that I'm still trying to customize a bit:

#### Quick Scatter ####
library(tidyverse)
quick.scatter <- function(data,
                          x.var,
                          y.var){
  d <- data %>%
    ggplot(aes(x=x.var,
               y=y.var)) 
    geom_point(alpha=.4) 
    geom_smooth(method = "lm",
                color="red") 
    labs(title = "Scatterplot of Data",
         x="Predictor",
         y="Outcome Variable") 
    theme_bw()
  return(d)
}

If you plug in the iris dataset for example, it should give you a quick scatter:

quick.scatter(iris,
              x.var = iris$Sepal.Width,
              y.var = iris$Sepal.Length)

enter image description here

There are a few things I want to refine with this. First, I would like to get rid of the "data" argument here so I can just plug in my values like:

quick.scatter(df$x,df$y)

Second, I want to know if there is an easy way to automatically name the x and y axis based off the variables included. So if I used the code above, I would like it to automatically have the following labels:

enter image description here

CodePudding user response:

Would something like this work for your use-case?

library(tidyverse)

quick.scatter <- function(x, y){
  x_name <- gsub(".*\\$", "", deparse(substitute(x)))
  y_name <- gsub(".*\\$", "", deparse(substitute(y)))
  data <- data.frame(x_name = x,
                     y_name = y)
  d <- data %>%
    ggplot(aes(x=x_name,
               y=y_name)) 
    geom_point(alpha=.4) 
    geom_smooth(method = "lm",
                color="red") 
    labs(title = "Scatterplot of Data",
         x=x_name,
         y=y_name) 
    theme_bw()
  print(d)
}

quick.scatter(iris$Petal.Length, iris$Sepal.Length)
#> `geom_smooth()` using formula 'y ~ x'

Created on 2022-08-16 by the reprex package (v2.0.1)

  • Related