简体   繁体   中英

How to plot a sparse matrix in R?

I have a large sparse matrix (100 rows 8000 columns) and I would like to represent it graphically. I found on internet this representation of a matrix of this kind:

在此输入图像描述

But it didnt specify how the image was obtained. I have tried using plot.matrix package and SparseM package but I still did not find the answer.

You can use the image() function in R:

# Create a matrix with random 0s and 1s
pseudo.data <- rbinom(100 * 8000, 1, 0.5)
pseudo.data <- matrix(pseudo.data, nrow = 100)

# plot the matrix
image(t(pseudo.data), col = c("white", "black"))

在此输入图像描述

You could also do something along these lines:

  library(tidyverse)

generatedMatrix <- matrix(rnorm(900), ncol = 30)>.5

generatedMatrix %>% as.vector %>% 
  tibble(value = ., row = rep(1:nrow(generatedMatrix), times = ncol(generatedMatrix)),
                                         col = rep(1: ncol(generatedMatrix), each = nrow(generatedMatrix))) %>%
  ggplot(aes(x = row, y = col, colour = value)) +
  geom_point(size = 2) +
  scale_color_manual(values = c('black','white'))+
  theme_minimal()

  library(tidyverse)

generatedMatrix <- matrix(rbinom(900,size = 1,prob = .5), ncol = 30)

generatedMatrix %>% as.vector %>% 
  tibble(value = ., row = rep(1:nrow(generatedMatrix), times = ncol(generatedMatrix)),
                                         col = rep(1: ncol(generatedMatrix), each = nrow(generatedMatrix))) %>%
  ggplot(aes(x = row, y = col, fill = value)) +
  geom_tile(size = 2) +
  scale_fill_gradient(low = 'black',high = 'white')+
  theme_minimal() +
  theme(legend.position = 'none')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM