user2274151
user2274151

Reputation: 41

How to plotting binary matrix only 1(one) elements in R

I have a sparse matrix .csv file and save the Matrix like:

v1 v2 v3 v4 v5 v6 ... vn
1 0  1  0  1  0  0
2 0  0  0  1  0  0
3 0  0  0  0  1  0
4 1  0  0  0  0  1
5 1  0  1  0  1  0
...
m

I want make plot's x value = v1~vn , y value = 1~m and marking only non-zero elements(only 1)

in Matlab I use spy(), but I don't know how do this in R.

Upvotes: 3

Views: 2785

Answers (2)

Adiel Loinger
Adiel Loinger

Reputation: 199

You can use the SparseM package:

m <- matrix(as.numeric(runif(100) > 0.9), ncol = 10) # create random sparse matrix library(SparseM) image(as.matrix.csr(m)) # plot it :)

enter image description here

Upvotes: 3

Maurits Evers
Maurits Evers

Reputation: 50718

Here is a solution using ggplot2::ggplot.

# Sample data
set.seed(2017);
df <- matrix(sample(c(0, 1), 100, replace = TRUE), nrow = 10);
df;

# Convert wide to long
library(reshape2);
df.long <- melt(df);

# Var1 = row
# Var2 = column
library(ggplot2);
gg <- ggplot(subset(df.long, value == 1), aes(x = Var2, y = Var1));
gg <- gg + geom_point(size = 2, fill = "blue", shape = 21);
gg <- gg + theme_bw();
gg <- gg + labs(y = "Row", x = "Column");
gg <- gg + scale_y_reverse();

enter image description here

Upvotes: 2

Related Questions