从马尔可夫链对象的图中替换 x 轴标签

Replace x-axis label from the plot of a MarkovChain object

这里是生成 0 阶马尔可夫链图的一些代码。我想用显示一年前六个月的 45 度旋转标签替换绘图的 x 轴标签(c、d、h、i、o、p)。但是,在 plot 调用中使用 xaxt="n" 似乎不起作用。此代码只是覆盖现有标签,而不是替换它们。如何将标签替换为我想要的标签?

library(clickstream)
clickstreams <- c("User1,h,c,c,p,c,h,c,p,p,c,p,p,o",
                   "User2,i,c,i,c,c,c,d",
                   "User3,h,i,c,i,c,p,c,c,p,c,c,i,d",
                   "User4,c,c,p,c,d",
                   "User5,h,c,c,p,p,c,p,p,p,i,p,o",
                   "User6,i,h,c,c,p,p,c,p,c,d")
csf <- tempfile()
writeLines(clickstreams, csf)
cls <- readClickstreams(csf, header = TRUE)
mc <- fitMarkovChain(cls, order=0)
plot(mc, xaxt="n")
text(x=1:6, y=par()$usr[3], labels = month.name[1:6], srt=45, adj = c(1.1,1.1), xpd = TRUE, cex=.9)

使用 plot.default 而不是 plot 公开了图形 plot 函数,它允许使用 xaxt 函数参数来删除现有的 x 轴标签。由于 plot.default 不接受马尔可夫链对象,因此需要从对象中提取绘图的 xy 值。

plot.default(
   x=mc@transitions[[1]]$states, 
   y=mc@transitions[[1]]$probability,
   xaxt="n", 
   ann=FALSE, 
   pch="-", 
   cex=3
)

text(
    x = 1:6, 
    y = par()$usr[3], 
    labels = month.name[1:6], 
    srt = 45, 
    adj = c(1.1,1.1), 
    xpd = TRUE, 
    cex = .9
)

str(mc)揭示了S4对象的结构。仅将 xy 坐标而不是整个 "MarkovChain" 对象传递给 plot 即可恢复 xaxt 选项功能。使用 with 最方便。

此外,这允许我们使用已实现的 S4 plot 方法对 clickstream 包的签名 'MarkovChain'

library(clickstream)
with(mc@transitions[[1]], plot(states, probability, xaxt="n"))
text(x=1:6, y=par()$usr[3], labels=month.name[1:6], srt=45, adj=rep(1.1, 2), xpd=TRUE, cex=.9)

结果

数据

library(clickstream)
mc <- new("MarkovChain", states = c("h", "c", "p", "o", "i", "d"), 
    order = 0, transitions = list(structure(list(states = structure(1:6, .Label = c("c", 
    "d", "h", "i", "o", "p"), class = "factor"), frequency = c(25L, 
    4L, 5L, 7L, 2L, 17L), probability = c(0.416666666666667, 
    0.0666666666666667, 0.0833333333333333, 0.116666666666667, 
    0.0333333333333333, 0.283333333333333)), class = "data.frame", row.names = c(NA, 
    -6L))), lambda = 0, logLikelihood = -88.4241188515082, observations = 60, 
    start = structure(c(c = 0.166666666666667, h = 0.5, i = 0.333333333333333
    ), class = "table", .Dim = 3L, .Dimnames = structure(list(
        c("c", "h", "i")), .Names = "")), end = structure(c(d = 0.666666666666667, 
    o = 0.333333333333333), class = "table", .Dim = 2L, .Dimnames = structure(list(
        c("d", "o")), .Names = "")), transientStates = c("c", 
    "h", "i", "p"), absorbingStates = c("d", "o"), absorbingProbabilities = structure(list(
        state = structure(1:4, .Label = c("c", "h", "i", "p"), class = "factor"), 
        d = c(0.792201957232916, 0.864224245314581, 0.903842865008182, 
        0.517925028202586), o = c(0.207798042767084, 0.13577575468542, 
        0.0961571349918185, 0.482074971797414)), class = "data.frame", row.names = c(c = 1L, 
    h = 3L, i = 4L, p = 6L)))