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.
How
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()
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
}