I have a data that looks like this:
> print(dat)
cutoff tp fp
1 0.6 414 45701
2 0.7 172 16820
3 0.8 51 4326
4 0.9 49 3727
5 1.0 0 0
I want to plot them in reverse-order from smallest dat$tp
to largest. However this code plot them in order like above (ie largest to smallest) instead.
> fp_max <- max(dat$fp);
> tp_max <- max(dat$tp);
> op <- par(xaxs = "i", yaxs = "i")
> plot(tp ~ fp, data = dat, xlim = c(0,fp_max),ylim = c(0,tp_max), type = "n")
> with(dat, lines(c(0, fp, fp_max), c(0, tp, tp_max), lty=1, type = "l", col = "black"))
> lines( par()$usr[1:2], par()$usr[3:4], col="red" )
How can I modify the code above to address the problem?
Of course, the x-axis & y-axis coordinates should be from smallest to largest value
The following shows the result of my current code.
Notice that the line started at 0,0 and it 'goes back' to 0 again. we want to avoid it going back to 0.
Ahh, I understand.
It's because lines
draws lines between the points in the order they are given.
There are a few ways you could get around this:
do type='l'
in your plot
command and then with(dat,lines(...))
is not necessary:
# can also do the col='black',lty=1 in here. plot(tp ~ fp, data = dat, xlim = c(0,fp_max),ylim = c(0,tp_max), type = "l")
Note that by definition of your fp_max
and tp_max
, you will include the point (fp_max,tp_max)
already. And as long as you have a row with (0,0)
for tp
and fp
in dat
, you'll also get the (0,0)
point.
Sort dat$tp
and use that to sort dat$fp
too:
plot(tp ~ fp, ..., type='n') # sort dat$tp obj <- sort(dat$fp,index.return=T) # use obj$x as tp and obj$ix to sort dat$fp prior to plotting with(dat, lines(c(0, obj$x, fp_max), c(0, tp[obj$ix], tp_max), lty=1, type = "l", col = "black"))
#Get order of rows
idx <- order(dat$tp)
#Select data in sorted order
sorted <- dat[idx,]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.