【问题标题】:R graphics: How to plot a sequence of characters (pure categorical time series)R图形:如何绘制字符序列(纯分类时间序列)
【发布时间】:2016-12-24 03:28:12
【问题描述】:

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

这是原始矩阵:

这是我想要的情节:

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

我尝试了一些现有的软件包,但大多数情况下它们需要我将分类变量转换为数值变量。所以我想知道是否有人可以帮助我解决这个问题。非常感谢!

【问题讨论】:

  • 如果您能给我们一张我们可以使用的表格,这样会更容易提供帮助。比如dput(your_data).
  • 您好,非常感谢您的及时回复,我不知道如何添加图片或表格,请问是否可以将表格发送到您的邮箱?非常感谢!
  • 顺便问一下,你能看到图片吗(通过我帖子中的链接)?
  • 我编辑了您的帖子(在显示之前必须经过验证),因此图像将被显示,但目前我们可以通过单击链接查看它们。我们不需要完整的数据库,只需写 dput(head(data,n=20))(如果 data 是您的数据库的名称)并复制显示在您的 R 控制台上的结果。
  • 太棒了!非常感谢。

标签: r plot time-series categorical-data


【解决方案1】:

没有你的数据,我必须生成一些玩具,称为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"  

基本上你需要首先用整数重新表示你的字符矩阵mat。

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

选中的两行的绘图:

【讨论】:

  • 你好哲元,你的代码简直太棒了!非常感谢你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 2020-08-29
  • 2020-07-12
相关资源
最近更新 更多