0

Could-you help me please in solving this issue. In fact, i would like to plot multiple curves on the same graph on R with a x-axis which is time labeled.

I tried this :

dayTime = strptime(sapply(c(0:110)+480, function(x){paste(floor(x/60),":",x%%60, sep="")}), "%H:%M") 
n = 10  
pdf("myGraph.pdf")
plot(x=dayTime, y=rep(0, length(dayTime)), main="myGraph", xlab="Time", ylab="Level", type="n", ylim=c(0, 0.05), xaxt = "n")
for(i in 1:n) 
{
    lines(myData[, i]), col=i)
}
r = as.POSIXct(round(range(dayTime), "hours"))
axis.POSIXct(1, at=seq(r[1], r[2], by="hour"), format="%H")
legend("topleft", legend=stockspool, col=c(1:n), lwd=rep(1, n), cex=0.8)
dev.off()

but the problem is that i can not add a curve with lines in this context, but if i plot only one curve using plot, it works fine.

Thank you very much.

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
user1646105
  • 103
  • 3
  • 2
    You need to pass x and y values to `lines`. I suggest to use `matplot` instead of your approach. Package ggplot2 would be another option. – Roland Jun 17 '13 at 11:33
  • Please check your code before posting it, there was an error in it. And, please help us help you by providing us with a reproducible example (i.e. code and example data), see http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example for details. – Paul Hiemstra Jun 17 '13 at 11:56
  • @Roland : Actually, i have already tried to passe x and y to _italic_ **bold** `lines` as you suggested but it does not work! But using the package _italic_ **bold** `ggplot2` as suggested by Paul Hiemstra(bellow) provies me with the solution i was looking for. – user1646105 Jun 19 '13 at 06:53

2 Answers2

1

The following solution uses ggplot2:

First create some sample data:

df = data.frame(id = rep(letters[1:5], each = 100),
                time = rep(Sys.time() + 1:100, 5),
                value = runif(500) + rep(1:5, each = 100))
> head(df)
  id                time    value
1  a 2013-06-17 14:02:37 1.368671
2  a 2013-06-17 14:02:38 1.302188
3  a 2013-06-17 14:02:39 1.817873
4  a 2013-06-17 14:02:40 1.283439
5  a 2013-06-17 14:02:41 1.022949
6  a 2013-06-17 14:02:42 1.232590

And create a plot.

library(ggplot2)
ggplot(df, aes(x = time, y = value, color = id)) + geom_line()

enter image description here

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
0

A solution using base graphics:

df = data.frame(id = rep(letters[1:5], each = 100),
                time = rep(Sys.time() + 1:100, 5),
                value = runif(500) + rep(1:5, each = 100))

library(reshape2)
df <- dcast(df,time~id)
matplot(df[,1],df[,-1],type="l")

You can fix the axis in the usual way.

enter image description here

Roland
  • 127,288
  • 10
  • 191
  • 288