Rentrop
Rentrop

Reputation: 21497

ggplot2 is plotting a line strangely

i am trying to plot the time series x_t = A + (-1)^t B

To do this i am using the following code. The problem is, that the ggplot is wrong.

require (ggplot2)
set.seed(42)
N<-2
A<-sample(1:20,N)
B<-rnorm(N)
X<-c(A+B,A-B)
dat<-sapply(1:N,function(n) X[rep(c(n,N+n),20)],simplify=FALSE)
dat<-data.frame(t=rep(1:20,N),w=rep(A,each=20),val=do.call(c,dat))

ggplot(data=dat,aes(x=t, y=val, color=factor(w)))+
  geom_line()+facet_grid(w~.,scale = "free")

enter image description here

looking at the head of dat everything looks right:

> head(dat)
  t  w     val
1 1 12 10.5533
2 2 12 13.4467
3 3 12 10.5533
4 4 12 13.4467
5 5 12 10.5533
6 6 12 13.4467

So the lower (blue) line should only have values 10.5533 and 13.4467. But it also takes different values. What is wrong in my code?

Thanks in advance for any help

Upvotes: 0

Views: 103

Answers (1)

jlhoward
jlhoward

Reputation: 59335

You really should be more careful before asserting that something is "wrong". The way you are creating dat the rows are not ordered by dat$t, so head(...) is not displaying the extra values:

head(dat[order(dat$w,dat$t),],10)
#    t  w      val
# 21 1 18 18.43530
# 61 1 18 18.36313
# 22 2 18 19.56470
# 62 2 18 17.63687
# 23 3 18 18.43530
# 63 3 18 18.36313
# 24 4 18 19.56470
# 64 4 18 17.63687
# 25 5 18 18.43530
# 65 5 18 18.36313

Note the row numbers.

Upvotes: 3

Related Questions