How to plot a sparse matrix in R?

Viewed 1660

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:

enter image description here

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.

2 Answers

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

enter image description here

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

Related