簡體   English   中英

繪制二進制矩陣 - R

[英]Plotting a binary matrix - R

我有一個二進制矩陣,行名是用戶名,列名是日期。 如示例中所述,我如何 plot 數據。

例子:

  2011-1-6  2011-1-9  2011-1-15  2011-2-19  Labels
A    1         0         0          1         1
B    0         1         1          1         2
C    1         1         0          0         3

在這種情況下,所需的圖形將如下所示:

在此處輸入圖像描述

有幾種方法,但我想鼓勵使用整潔的數據和ggplot2 因此,假設您的矩陣名為mat

library(tidyr)
library(dplyr)
library(ggplot2)
# or simply just use: library(tidyverse)

mat %>% 
  as.data.frame() %>%
  mutate(id=rownames(.),
         Labels = as.factor(Labels)) %>%
  pivot_longer(cols=starts_with("2011")) %>%
  filter(value==1) %>%
  ggplot(aes(x=name, y=id, color=Labels)) + 
    geom_point() + 
    theme(axis.text.x = element_text(angle = 90))

返回與您所需的 output 類似的 plot。

那么我們做了什么?

  1. 將矩陣轉換為 data.frame。
  2. 將行名稱添加到新列。
  3. 將數據重塑為“長”格式。 這是ggplot處理數據所必需的。
  4. 刪除( filter )所有value == 0行,因為只有value == 1行應該被繪制。
  5. 最后使用ggplot將 plot 數據作為散點圖 plot ( geom_points ) 與 colors 通過標簽和 x 軸旋轉標簽。

數據

structure(c(1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 2, 3), 
          .Dim = c(3L, 5L), 
          .Dimnames = list(c("A", "B", "C"), 
                           c("2011-1-6", "2011-1-9", "2011-1-15", "2011-2-19", "Labels")))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM