Boo
Boo

Reputation: 155

Line instead of Dot (R) Not so easy

If you could help me it would be great : So i'm doing a double curve (SDT) graph, and i have a bit of a problem : here my graph : Dot type = "l"

First time I have this problem ... Really have no clue how to solve it, well I just think my data is not ordered but how can I order it easily ?

Here's me code (but really nothing special) :

x = TDSindice2$Hit
mean = mean(x)
sd = sd(x)

y = dnorm(x,mean,sd)

plot(x,y, col = "red")


x = TDSindice2$Fa
mean = mean(x)
sd = sd(x)

y = dnorm(x,mean,sd)
par(new=TRUE)

plot(x,y ,type = "l", col ="blue")

Thanks for all :)

Upvotes: 0

Views: 916

Answers (1)

Gavin Simpson
Gavin Simpson

Reputation: 174898

You need to order your data in terms of increasing values of x before plotting. For example:

set.seed(1)
x <- runif(50)
y <- 1.2 + (1.4 * x) + (-2.5 * x^2)

plot(x, y)
lines(x, y)

enter image description here

The order() function can be used to generate an index that when applied to a variable/object places the values of that object in the required order (increasing by default):

ord <- order(x)
plot(x[ord], [ord], type = "o")

enter image description here

But you'd be better off have x and y in the same object, a data frame, and just sort the rows of that:

dat <- data.frame(x = x, y = y)
ord <- with(dat, order(x))
plot(y ~ x, data = dat[ord, ], type = "o") ## or
## lines(y ~ x, data = dat[ord, ])

Note that order() is used to index the data hence we don't change the original ordering, we just permute the rows as we supply the object to the plot() function.

Upvotes: 5

Related Questions