How to plot a multicolumn CSV file?

前端 未结 2 1470
攒了一身酷
攒了一身酷 2021-02-04 09:23

I am very new to R, so excuse me for a question probably stupid.

I\'ve got a multicolumn CSV (plain comma-separated, no quotes) file where the first row is the header, t

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-04 09:55

    You can use read.csv to input the data as a data.frame. Then you have plenty of choices for plotting. I prefer lattice for most investigative work.

    Two in lattice. Here I am creating random data to chart.

    library(lattice)
    d <- data.frame(index=1:20, x=rnorm(20), y=rnorm(20))
    
    > head(d, n=3)
      index         x          y
    1     1 -1.065591  0.2422635
    2     2 -1.563782 -1.4250984
    3     3  1.156537  0.3659411
    
    xyplot(x+y~index, data=d, type='l', auto.key=list(space='right'))
    

    You can generate the formula from the names of the columns. I don't usually do this from the prompt, but use such constructs in code:

    f <- paste(paste(names(d[,-1,drop=FALSE]), collapse="+"),
               names(d[,1,drop=FALSE]),
               sep=" ~ ")
    
    xyplot(as.formula(f), data=d, type='l', auto.key=list(space='right'))
    

    As in Ben's answer, type='l' specifies lines. The default is type='p' for points. I added the auto.key parameter here, to label the series.

    enter image description here

提交回复
热议问题