Aesthetics Error When Calling ggplot() Using Two Methods

Viewed 48

My end goal is to create a function to easily build a series of ggplot objects. However in running some tests on the a piece of the code I plan to use within my function I'm receiving a geom_point aesthetics error whose cause doesn't seem to match other instances of this error for which I've found SO questions.

Reproducible code below

library(ggpubr)
library(ggplot2)

redData <- read.csv("http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"
                    ,header = TRUE, sep = ";")

datatest <- redData
x <- "alcohol"
y <- "quality"

#PlotTest fails with Error: geom_point requires the following missing aesthetics: x, y
PlotTest<-ggplot(datatest, aes(datatest$x,datatest$y)) +
  geom_point()+xlim(0,15)+ylim(0,10)

#PlotTest2 works just fine, they should be functionally equivalent
PlotTest2 <- ggplot(redData, aes(redData$"alcohol", redData$"quality")) +
  geom_point()+xlim(0,15)+ylim(0,10)

PlotTest

PlotTest2

PlotTest and PlotTest2 should be functionally equivalent, but they clearly are not but I can't see what causes one to work and not the other.

EDIT

I realize now that datatest$x,datatest$y dont actually resolve to datatest$"alcohol" and datatest$"quality". That was silly.

Is there some way to access data via a variable name that stores the column name? That would be what I need.

2 Answers
library(ggpubr)
library(ggplot2)

redData <- read.csv("http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv" ,header = TRUE, sep = ";")
datatest <- redData
x <- "alcohol"
y <- "quality"

ggplot(datatest,aes(x=datatest[,x],y=datatest[,y]))+geom_point()+xlim(0,15)+ylim(0,10)+labs(x=x,y=y)
ggplot(redData,aes(x=alcohol,y=quality))+geom_point()+xlim(0,15)+ylim(0,10)

You can use aes_string() which takes character variables as argument names:

library(dplyr)
library(ggplot2)

plot_cars <- function(data = mtcars, x, y) {

data %>% 
  ggplot(aes_string(x, y)) +
  geom_point()

  }


plot_cars(x = "mpg", y = "cyl")

In your example above you'd call ggplot(redData, aes_string(x, y))..., though don't have your data to test that.

Related