代码之家  ›  专栏  ›  技术社区  ›  Chao Liu

R图形:如何绘制字符序列(纯类别时间序列)

  •  -1
  • Chao Liu  · 技术社区  · 10 年前

    我有一个矩阵,其中每个元素都是一个纯分类变量“a”、“b”、“c”、“d”……矩阵的每一列都是按时间顺序排列的,现在我想按行绘制矩阵,我希望y轴是字符序列。

    Graph with legend

    这就是我想要的情节: Graph with legend

    红色图是矩阵的第一行,蓝色图是第五行。

    我尝试了一些现有的软件包,但大多数都要求我将分类变量转换为数值变量。所以我想知道是否有人能帮我做这件事。非常感谢!

    1 回复  |  直到 10 年前
        1
  •  1
  •   Zheyuan Li    10 年前

    如果没有你的数据,我必须生成一个玩具,名为 mat ,5行10列,填充 letters[1:7] .

    set.seed(0); mat <- matrix(sample(letters[1:7], 5 * 10, TRUE), nrow = 5)
    #     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
    #[1,] "g"  "b"  "a"  "f"  "f"  "b"  "c"  "f"  "c"  "d"  
    #[2,] "b"  "g"  "b"  "d"  "g"  "c"  "d"  "e"  "f"  "f"  
    #[3,] "c"  "g"  "b"  "f"  "b"  "a"  "e"  "f"  "e"  "a"  
    #[4,] "e"  "e"  "e"  "g"  "e"  "c"  "d"  "a"  "f"  "d"  
    #[5,] "g"  "e"  "c"  "c"  "a"  "g"  "b"  "f"  "d"  "f"  
    

    基本上,您需要首先重新表示您的字符矩阵 小地毯 使用整数。

    ## flatten your object into a vector first
    if (is.matrix(mat)) v <- as.character(mat)
    if (is.data.frame(mat)) v <- as.character(unlist(mat, use.names = FALSE))
    lev <- sort(unique(v))    ## sorted unique labels
    
    ## re-representation
    mat_int <- matrix(match(v, lev), nrow = nrow(mat))
    ## or: mat_int <- matrix(as.integer(factor(v, levels = lev)), nrow = nrow(mat))
    
    #     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
    #[1,]    7    2    1    6    6    2    3    6    3     4
    #[2,]    2    7    2    4    7    3    4    5    6     6
    #[3,]    3    7    2    6    2    1    5    6    5     1
    #[4,]    5    5    5    7    5    3    4    1    6     4
    #[5,]    7    5    3    3    1    7    2    6    4     6
    

    然后您只需使用 matplot 。首先禁用y轴,然后使用添加 axis

    ## this plots the whole matrix
    matplot(t(mat_int), yaxt = "n", type = "l", xlab = "time", ylab = "category")
    axis(2, seq_along(lev), labels = lev)
    
    ## this plots 1st and 5th rows
    matplot(t(mat_int)[, c(1,5)], yaxt = "n", type = "l", xlab = "time", ylab = "category")
    axis(2, seq_along(lev), labels = lev)
    

    所选两行的绘图:

    enter image description here