Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plot lines using qplot

Tags:

r

ggplot2

I want to plot multiple lines on the sample plot using qplot in the ggplot2 package. But I'm having some problem with it.

Using the old plot, and lines function I would do something like

m<-cbind(1:4,5:8,-(5:8))
colnames(m)<-c("time","y1","y2")
m<-as.data.frame(m)
> m
  time y1 y2
1    1  5 -5
2    2  6 -6
3    3  7 -7
4    4  8 -8
plot(x=m$time,y=m$y1,type='l',ylim=range(m[,-1]))
lines(x=m$time,y=m$y2)

Thanks

like image 474
monkeyking Avatar asked Mar 03 '26 14:03

monkeyking


1 Answers

Using the reshape package to melt m:

library(reshape)
library(ggplot2)

m2 <- melt(m, id = "time")
p <- ggplot(m2, aes(x = time, y = value, color = variable))
p + geom_line() + ylab("y")

You could rename the columns in the new data.frame to your liking. The trick here is to have a factor that denotes each of the lines you want to plot.

like image 141
kmm Avatar answered Mar 06 '26 05:03

kmm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!