## A Color-Coded Trajectory Plot

A trajectory is a path of an object through space as a function of time.
Suppose you want to plot a trajectory but it intersects itself, making it hard to follow.
Here is a solution by starting the path in red and changing in color through the spectrum to end the path in violet.

# mylinesr
# An R command for drawing line segments in a rainbow of colors.

# A simple R code example by Nissim Kaufmann

# Arguments:
# x  x-coordinates
# y  y-coordinates
# n    number of colors to use, from red to magenta
# alpha opacity
# ...  other arguments passed to lines()

mylinesr<-function(x,y,alpha=1,...){
n<-max(35,length(x)-1) #how many colors to use
colr<-rainbow(n,start=0,end=5/6,alpha=alpha)
cutsn<-round(seq(1,length(x),len=n+1))
for(i in 1:n) lines(x[cutsn[i]:cutsn[i+1]],y[cutsn[i]:cutsn[i+1]],col=colr[i],...)
}

# example:
dev.off()
par(bg='#405060')
plot(c(0,1),c(0,1),type='n',xlab='',ylab='',main='mylinesr() sample output by Nissim')
mylinesr(tempx<-runif(10),tempy<-runif(10)/2,lty=2,lwd=3); text(tempx,tempy,1:10,pos=3,col='white')
mylinesr(1:100/100,1-runif(100)/2,lwd=2)

# a random walk
tempx<-cumsum(rnorm(n=1000)/50)
tempy<-cumsum(rnorm(n=1000)/100)
plot(tempx,tempy,xlab='',ylab='',main='mylinesr() random walk by Nissim', sub="n=1000")
mylinesr(tempx,tempy)
i<-1; text(tempx[i],tempy[i],'START',font=2,pos=3,col='white')
i<-length(tempx); text(tempx[i],tempy[i],'STOP', font=2,pos=3,col='white')

The image below is a screenshot from the serious video game Sirius: CYCLES, an IARPA project, for training the user about cognitive biases.  This puzzle room from the game is overlaid with the trajectories traced by ~350 players.  For each player, the path changes from red to magenta over time from start to finish, and dots appear where the computer mouse was rested. Semi-transparent colors are used in order to cope with overlapping paths.