0

I have this function:

plotS<-function(data){
        library(ggplot2)
        p<-ggplot(data,aes(x=date,y=y))+geom_line(aes(y=data[,2],color=colnames(data)[2]))
        p<-p+geom_line(aes(y=data[,3],color=colnames(data)[3]))

        return(p)    
    }

the input, data, is an n by 3 data.frame like this

    date        A       ADI
1   2007-01-03  34.300  32.84
2   2007-01-04  34.410  33.41
3   2007-01-05  34.090  33.03
4   2007-01-08  33.970  33.29
5   2007-01-09  34.010  33.24
...

when I run the function, it always return:

Error in data[, 2] : object of type 'closure' is not subsettable

I think it because in ggplot2, aesthetics can only take column name as parameter. But the problem is the input data set always have different name in column2 and column3. Is there any simple solution?

bdemarest
  • 14,397
  • 3
  • 53
  • 56
HLD25
  • 39
  • 1
  • 2
  • 4
  • 1
    There are a number of issues: (1) `data` is the name of a built-in R function, (2) using `[` inside of `aes` is not recommended, (3) `color=something` should be inside `aes()` and `something` needs to be a column name in your data, (4) You might be running into scoping issues with ggplot called from inside a function. Have a look at http://stackoverflow.com/questions/10659133/local-variables-within-aes – bdemarest Feb 12 '15 at 23:14
  • Thanks. I correct the issues(1) and (3). The problem is that the colnames is the stock price and I want to keep it in the legend, but it is different for each input data set. I can't think of a more generic mean of reference. – HLD25 Feb 15 '15 at 14:53
  • For defining columns of data dynamically (inside a loop or function) you probably want to use `aes_string()`. – bdemarest Feb 17 '15 at 19:48

0 Answers0