R图形:如何绘制字符序列(纯分类时间序列) [英] R graphics: How to plot a sequence of characters (pure categorical time series)
问题描述
我有一个矩阵,其中每个元素都是纯类别变量 a, b, c, d,...。矩阵的每一列都是按时间顺序排列的条目,现在我想绘制
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 entry and now I want to plot the matrix by row and I hope the y-axis is the sequence of characters.
这是原始矩阵:
这里是我想要的图:
Here is what I wanted the plot to be:
红色图是矩阵的第一行,蓝色图是矩阵的第五行。
The red plot is first row of the matrix and the blue plot is the fifth.
我已经尝试了一些现有的软件包,但是大多数情况下它们需要我将分类变量转换为数值变量。所以我想知道是否有人可以帮助我。非常感谢!
I have tried some existing packages but mostly they require me to transfer the categorical variables to numerical variables. So I wonder if anyone could help me with this. Many thanks!
推荐答案
没有您的数据,我必须生成一个玩具,称为 mat
,有5行和10列,用字母[1:7]
填充。
Without your data, I have to generate some toy one, 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"
基本上,您需要先-用整数表示字符矩阵 mat
。
Basically you need first re-represent you character matrix mat
with 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
然后,您可以使用 matplot $ c $绘制该矩阵的(全部或部分行) c>。首先禁用y轴,然后再使用
axis
添加它,以便您可以自定义轴标签。
Then you just plot (the whole or some rows of) this matrix using matplot
. Disable the y-axis first then add it later using axis
so that you can customize axis labels.
## 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)
所选两行的图:
这篇关于R图形:如何绘制字符序列(纯分类时间序列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!