从MarkovChain对象的绘图中替换x轴标签

时间:2019-04-09 14:56:07

标签: r plot clickstream

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

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)

clickstream plot with wrong x-axis labels

2 个答案:

答案 0 :(得分:0)

使用plot.default而不是plot会显示图形plot函数,该函数允许使用xaxt函数参数删除现有的x轴标签。由于plot.default不接受MarkovChain对象,因此需要从该对象中提取图的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
)

enter image description here

答案 1 :(得分:0)

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

此外,这使我们可以使用已实现的S4 plot方法来签名'MarkovChain'包的clickstream

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)

结果

enter image description here

数据

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