0

I am new to R and I am trying to generate a plot, from a data.frame. My first column contains the x-values, while the other 15 columns contain the y values.

I would appreciate if someone could help me please? I managed to write the code, but it is quite lengthy. Would someone be able to suggest something more succinct, as I need to run the code for various data-sets and would like to keep editing the code to a minimum.

data.frame is called rdata

That is how the data looks like

rdata
library(ggplot2)


x<-rdata[,1]
y1<-rdata[,2]
y2<-rdata[,3]
y3<-rdata[,4]
y4<-rdata[,5]
y5<-rdata[,6]
y6<-rdata[,7]
y7<-rdata[,8]
y8<-rdata[,9]
y9<-rdata[,10]
y10<-rdata[,11]
y11<-rdata[,12]
y12<-rdata[,13]
y13<-rdata[,14]
y14<-rdata[,15]
y15<-rdata[,16]

plotdata <- data.frame(x=rep(x,15), y=c(y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11,y12,y13,y14,y15), class=c(rep("y1",226), rep("y2", 226),  
      rep("y3", 226), rep("y4", 226),rep("y5", 226),  rep("y6", 226), rep("y7", 226),  rep("y8", 226), rep("y9", 226),
      rep("y10", 226), rep("y11", 226),rep("y12", 226),  rep("y13", 226), rep("y14", 226),  rep("y15", 226)))

#Then use ggplot2 to plot it

library(ggplot2)
ggplot(data=plotdata, aes(x=x, y=y,color=class)) + geom_line()  +
  xlab('Wavelength (nm)') +
  ylab('second derivative of OD')enter code here`

Thanks!

aosmith
  • 34,856
  • 9
  • 84
  • 118
Orbis
  • 15
  • 1
  • 5
  • Possible duplicate of [plot multiple columns on the same graph in R](https://stackoverflow.com/questions/9531904/plot-multiple-columns-on-the-same-graph-in-r) – aosmith Jun 19 '17 at 19:14

1 Answers1

0

This should reproduce the plotdata data set

ss<-do.call(rbind, replicate(length(2:ncol(rdata)), coredata(melt(rdata, id.var=c("v1"), 
                             variable.name="class")), simplify = FALSE))
ss[,"class"]<-rep(paste("y",1:ncol(rdata[,-1])), each=nrow(rdata[,-1])*ncol(rdata[,-1]), sep="")
colnames(ss)[colnames(ss)=="value"] <- "y"
colnames(ss)[colnames(ss)=="v1"]    <- "x"
Al14
  • 1,734
  • 6
  • 32
  • 55