为图形上的多条线分配唯一颜色

Assigning Unique Colors To Multiple Lines on a Graph

我找到了我想要修改的 R 教程:https://stephens999.github.io/fiveMinuteStats/simulating_discrete_chains_1.html

在本教程中,作者展示了如何绘制马尔可夫链的状态转换 - 并且对马尔可夫链进行了多次模拟。

# 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)

我尝试添加图例,但它最终阻止了图表:

#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)

谢谢!

您可以使用调色板,例如内置 rainbow。不过100种颜色可能不太好区分。

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)