Meg*_*gan 5 r markov-chains markov
我已经从 r 中的矩阵绘制了一个马尔可夫链。但是,我有许多低于 0.01 的概率,因此我的概率图如下所示:
我已经搜索了几个小时,但似乎找不到可以显示所有四个小数位的东西。有什么办法可以格式化这个还是我应该保持原样?
我的代码如下:
library(markovchain)
newtransition.matrix <- matrix( data = c(
.9366, .0066, .0007, .0003 ,.0003, 0, .0015, 0,
.0583, .9172, .0225, .0026, .0006, .001, 0, 0,
.004, .0694, .9176, .0483, .0044, .0032, .0029, 0,
.0009, .0049, .0518, .8924, .0666, .0046, .0088, 0,
.0002, .0006, .0049, .0444, .8323, .0572, .0191, 0,
0, .0009, .002, .0081, .0746, .8362, .1028, 0,
0, .0002, .0001, .0016, .0105, .0384, .6123, 0,
0, .0002, .0004, .0023, .0107, .0594, .2526, 1),
nrow = 8, ncol = 8,
dimnames = list( c( "AAA", "AA", "A", "BBB", "BB", "B", "CCC", "Default" ), c( "AAA", "AA", "A", "BBB", "BB", "B", "CCC", "Default") ) )
print( newtransition.matrix )
newtransition.matrix <- new( "markovchain", transitionMatrix = newtransition.matrix )
layout <- matrix(c(-3, 1, 2, 2, 2, -2, 4, 1, 0, 6, 0, -6, -3, -4, 3, -4), ncol = 2, byrow = TRUE)
plot(newtransition.matrix, vertex.size = 10, layout = layout, edge.arrow.size=0.25)
Run Code Online (Sandbox Code Playgroud)
非常感谢!
您需要编辑 S4 方法。2 位数字的限制是硬编码在绘图函数中的。我无法仅用代码来编辑函数的主体(如果其他人能弄清楚,请发表评论)。下面的代码需要一些用户输入。
# Digging to find the plotting function for markovchain
showMethods(plot)
# Find the source code
f <- getMethod("plot", signature = c(x="markovchain", y="missing"))
# Ahh it uses plot.igraph, and the labels are being specified with edge.label = edgeLabel
# But edgeLabel is being rounded to 2 digits
# Extract and edit the body of f,
# Change round(E(netMc)$weight/100, 2) to round(E(netMc)$weight/100, 4) or something larger
g <- edit(body(f@.Data))
# Store the edited body again
body(f@.Data) <- g
# Call new plotting function to plot with more digits
f(newtransition.matrix, vertex.size = 10, layout = layout, edge.arrow.size=0.25)
Run Code Online (Sandbox Code Playgroud)
这是使用该包的简单解决方案igraph。如果您查看 的文档markovchain, 的绘图函数markovchain只是调用 的绘图函数igraph,因此您会发现许多(如果不是全部)绘图参数在两种对象之间是交叉兼容的。
igraph在这里,我们只需从转换矩阵创建一个对象,然后将其绘制出来。您可能会发现这比markovchain直接绘制对象更方便。
library(markovchain)
library(igraph)
newtransition.matrix <- new( "markovchain", transitionMatrix = newtransition.matrix )
layout <- matrix(c(-3, 1, 2, 2, 2, -2, 4, 1, 0, 6, 0, -6, -3, -4, 3, -4),
ncol = 2,
byrow = TRUE)
# create an igraph object from your transition matrix
graph <- as(newtransition.matrix, "igraph")
plot(graph, vertex.size = 15,
edge.label = E(graph)$prob, # We add the proper edge labels here
layout = layout,
edge.arrow.size=0.25)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
372 次 |
| 最近记录: |