Mobeus Zoom
Mobeus Zoom

Reputation: 608

Scatterplot function for different attributes with ggplot2

Let's say I have a dataframe df. (Below I use the example of mtcars.) Can I write a function that will take in any two attributes of the df and produce a ggplot2 scatterplot?

So far I have the following code:

scatterplotter <- function(att1, att2){
  plot <- ggplot(data=mtcars, aes(x=att1, y=att2)) +
    geom_point(aes(color=as.factor(vs))) +
    xlab(paste(att1)) + ylab(paste(att2)) +
    ggtitle(paste("plot of",att1,"and ",att2))
return(plot)
}

Now I have the problem that, while x=att1 and y=att2 are as they should be, this is not going to work with the pastes, and I get an error saying Error in parse(text = disp) : object 'disp' not found. Can anyone help with this?

I wouldn't mind how the names are to be fed into the function, whether scatterplotter("disp","gear") or scatterplotter(disp,gear) for instance.

(No packages besides base-R + ggplot2 please)

Upvotes: 1

Views: 62

Answers (1)

Chase
Chase

Reputation: 69151

use aes_string()

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.6.3
scatterplotter <- function(att1, att2){
  plot <- ggplot(data=mtcars, aes_string(x=att1, y=att2)) +
    geom_point(aes(color=as.factor(vs))) +
    xlab(paste(att1)) + ylab(paste(att2)) +
    ggtitle(paste("plot of",att1,"and ",att2))
  return(plot)
}

scatterplotter("mpg", "disp")

Created on 2020-05-15 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions