R: How to build a sequence of characters (pure categorical time series)

I have a matrix in which each element is a pure categorical variable "a", "b", "c", "d", ... Each column of the matrix is ​​a chronological record, and now I want to build the matrix in a row, and I hope the y axis is a sequence of characters.

Here is the source matrix:

Legend Chart

Here is what I wanted this plot to be: Graph with legend

The red graph is the first row of the matrix, and the blue graph is the fifth.

I tried some existing packages, but basically they require me to pass categorical variables to numeric variables. So I wonder if anyone can help me with this. Thank you very much!

-1
source share
1 answer

Without your data, I have to create a toy, called mat , with 5 rows and 10 columns filled with 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" 

Basically you need to first represent the character matrix mat as integers.

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

Then you simply draw (whole or multiple rows) of this matrix using matplot . Disable the y axis first, and then add it later using the axis so you can adjust the labels of the axes.

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

Graph of the selected two lines:

enter image description here

+1
source

All Articles