Multiple curves with same Time x-axis in R

五迷三道 提交于 2019-12-12 01:07:20

问题


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.


回答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()




回答2:


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.



来源:https://stackoverflow.com/questions/17146442/multiple-curves-with-same-time-x-axis-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!