2

I would like to have a function that i could apply to any object that meets a criteria, and have a nice ggplot scatter plot with regression line print.

However, i cannot generalise what i can do at the REPL with code.

so i have this working:

require(ggplot2)    
require(xts)
set.seed(1)
dd = xts(cbind(rnorm(10), runif(10)), order.by = Sys.Date() + 1:10)
names(dd) <- c('d1', 'd2')

gp <- ggplot(data = dd, 
             aes(x = d1, y = d2)) + 
        geom_point(shape=1) + 
        geom_smooth(method = lm)

But this fails

PointReg <- function(Xts, a=1, b=2) {
    stopifnot(is.xts(Xts), 
              ncol(Xts) >1)
    tempData <- Xts[, c(a,b)]
    gPlot <- ggplot(data = tempData, 
                aes(x = colnames(tempData)[1],
                   y = colnames(tempData)[2])) +
            geom_point(shape=1) +
            geom_smooth(method = lm)
    gPlot
}

What am i doing wrong?

0

3 Answers 3

2

Your function throws an error since aes() tries to evaluate the argument in the column names of your data. To be more specific, aes() tries to evaluate colnames(tempData)[1] as a column name and this column doesn't exist.

To fix this, you somehow have to tell ggplot that you are not passing a column name, but an expression (a string) that will resolve to a column name.

Use aes_string() for this. Concretely, simply replace aes() with aes_string(). Try this:

PointReg <- function(Xts, a=1, b=2) {
  stopifnot(is.xts(Xts), 
            ncol(Xts) >1)
  tempData <- Xts[, c(a,b)]
  gPlot <- ggplot(data = tempData, 
                  aes_string(x = colnames(tempData)[1],
                      y = colnames(tempData)[2])) +
    geom_point(shape=1) +
    geom_smooth(method = lm)
  gPlot
}

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

2

You can specify the columns using indexes.

> library(ggplot2)
> df <- data.frame(a = 1:10, b = 1:10, c=c("x"))
> ggplot(data = df, aes(x = df[,1], y = df[,2])) + geom_line()

Comments

1

Since aes_string is now deprecated, the way to use strings within ggplot is to use !!ensym():

d1 <- "d1"
d2 <- "d2"
ggplot(data, aes(x= !!ensym(d1), y= !!ensym(d2))) + geom_line()

Source: How does enquote/quote/!! works in ggplot

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.