【发布时间】:2018-10-20 07:35:49
【问题描述】:
我想绘制不同时间 t 内状态的概率分布图。我有转换矩阵
P1 <- matrix(c(0, 1, 0, 0, 0, 0, 2/3, 1/3, 0, 1, 0, 0, 0, 0, 0, 1), 4, 4, byrow=TRUE)
要绘制从 p1 到 p50 的图形,我使用以下代码。
library(ggplot2)
initState <- c(1,0,0,0) # The initial state will be state 1
# Initiate probability vectors
one <- c()
two <- c()
three <- c()
four <- c()
# Calculate probabilities for 50 steps.
for(k in 1:50){
nsteps <- initState*P1^k
one[k] <- nsteps[1,1]
two[k] <- nsteps[1,2]
three[k] <- nsteps[1,3]
four[k] <- nsteps[1,4]
}
# Make dataframes and merge them
one <- as.data.frame(one)
one$Group <- 'one'
one$Iter <- 1:50
names(one)[1] <- 'Value'
two <- as.data.frame(two)
two$Group <- 'two'
two$Iter <- 1:50
names(two)[1] <- 'Value'
three <- as.data.frame(three)
three$Group <- 'three'
three$Iter <- 1:50
names(three)[1] <- 'Value'
four <- as.data.frame(four)
four$Group <- 'four'
four$Iter <- 1:50
names(four)[1] <- 'Value'
steps <- rbind(one,two,three,four)
# Plot the probabilities using ggplot
ggplot(steps, aes(x = Iter, y = Value, col = Group))+
geom_line() +
xlab('Chain Step') +
ylab('Probability') +
ggtitle('50 Step Chain Probability Prediction')+
theme(plot.title = element_text(hjust = 0.5))
但是结果很奇怪,谁能找出我的代码哪里出错了?
【问题讨论】:
标签: r ggplot2 markov-chains