I found this R tutorial that I would like to modify : https://stephens999.github.io/fiveMinuteStats/simulating_discrete_chains_1.html
In this tutorial, the author is showing how to plot the state transitions of a Markov Chain – and the Markov Chain is being simulated several times.
# simulate discrete Markov chains according to transition matrix P
run.mc.sim <- function( P, num.iters = 50 ) {
# number of possible states
num.states <- nrow(P)
# stores the states X_t through time
states <- numeric(num.iters)
# initialize variable for first state
states[1] <- 1
for(t in 2:num.iters) {
# probability vector to simulate next state X_{t+1}
p <- P[states[t-1], ]
## draw from multinomial and determine state
states[t] <- which(rmultinom(1, 1, p) == 1)
}
return(states)
}
P <- t(matrix(c( 1/3, 2/3, 0, 0, 0, 0, 0, 0,
1/3, 1/3, 1/3, 0, 0, 0, 0, 0,
0, 1/3, 1/3, 1/3, 0, 0, 0, 0,
0, 0, 1/3, 1/3, 1/3, 0, 0, 0,
0, 0, 0, 1/3, 1/3, 1/3, 0, 0,
0, 0, 0, 0, 1/3, 1/3, 1/3, 0,
0, 0, 0, 0, 0, 1/3, 1/3, 1/3,
0, 0, 0, 0, 0, 0, 2/3, 1/3), nrow=8, ncol=8))
# I am changing these numbers compared to the initial distirbution
num.chains <- 100
num.iterations <- 100
chain.states <- matrix(NA, ncol=num.chains, nrow=num.iterations)
for(c in seq_len(num.chains)){
chain.states[,c] <- run.mc.sim(P)
}
matplot(chain.states, type='l', lty=1, col=1:5, ylim=c(0,9), ylab='state', xlab='time')
abline(h=1, lty=3)
abline(h=8, lty=3)
- Is it possible to assign each of these lines a unique color?
- Is it possible to add a legend to this graph such that the legend does not interfere with the graph itself?
I tried to add a legend, but it ended up blocking the graph:
#I only showed for 8 chains...I don't think it's possible to show for all 100 chains without interfering with the graph, regardless of how the legend is placed
legend('topright', c('chain.1', 'chain.2', 'chain.3', 'chain.4', 'chain.5', 'chain.6','chain.7','chain.8'), lty=1, col=1:8)
- Is it possible to assign each line a different color?
- Is there some way to show a legend (even for 10-15 lines) in such a way that the legend does not interfere with the graph?
Thank you!
>Solution :
You could use a palette, e.g. builtin rainbow. However 100 colors may not be very distinguishable.
clr <- rainbow(num.chains) ## create `num.chains` colors
matplot(chain.states, type='l', lty=1, col=clr, ylim=c(0, 9),
ylab='state', xlab='time')
abline(h=1, lty=3)
abline(h=8, lty=3)


