Matrix with ggplot

Published by onesixx on

https://rpubs.com/lgadar/matrix-visualizations
# https://rpubs.com/lgadar/matrix-visualizations
A <- matrix(c(2,5,2,1,0,0,0,0,1,0,
\t\t\t\t\t\t\t0,0,0,1,3,5,6,0,0,1,
\t\t\t\t\t\t\t0,0,0,2,0,0,1,2,7,2,
\t\t\t\t\t\t\t4,6,2,5,1,0,0,1,0,0,
\t\t\t\t\t\t\t0,1,0,0,3,5,4,0,0,1,
\t\t\t\t\t\t\t0,0,1,0,0,2,0,3,5,7,
\t\t\t\t\t\t\t3,1,4,0,1,0,0,0,0,2,
\t\t\t\t\t\t\t0,0,0,1,3,4,6,0,0,1), byrow=T, nrow=8, ncol=10)
rownames(A) <- str_c("r", seq_len(nrow(A)))
colnames(A) <- str_c("c", seq_len(ncol(A)))
# Melt Matirx to data.table
dtA <- data.table(row=str_c("r", rep(seq_len(nrow(A)), times=ncol(A))),
\t\t\t\t\t\t\t\t\tcol=str_c("c", rep(seq_len(ncol(A)),  each=nrow(A))),
\t\t\t\t\t\t\t\t\tvalue=c(A))
dtA[, row:=factor(row, levels=str_c("r", rep(seq_len(nrow(A)))) %>% rev())]
dtA[, col:=factor(col, levels=str_c("c", rep(seq_len(ncol(A)))) )]
longDat <- dtA[value!=0,]   # white

p <- longDat %>% ggplot(aes(x=col, y=row)) + geom_raster(aes(fill=value)) +
\tscale_fill_gradient(low="grey90", high="red") +
  labs(x="sample", y="variable", title="Matrix ggplot")
p

theme_set(
  hrbrthemes::theme_ipsum(base_size=9) +
  theme(
     panel.background = element_rect(fill="white"),
     plot.title=element_text(size=11)
  )
)

change order

pacman::p_load(seriation)
o <- seriate(x=A, method="BEA_TSP")  
rowOrder <- o[[1]][]
colOrder <- o[[2]][]

dtA[, row:=factor(row, levels=names(rowOrder))]
dtA[, col:=factor(col, levels=names(colOrder))]
dtA %>% str()

Categories: R ggplot2

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x