【发布时间】:2022-07-04 14:09:26
【问题描述】:
我找到了我想修改的 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)
[![在此处输入图片描述][2]][2]
- 是否可以为每一行分配不同的颜色?
- 是否有某种方法可以显示图例(即使是 10-15 行),并且图例不会干扰图形?
谢谢!
【问题讨论】:
标签: r plot data-visualization legend