Search code examples
rmatrixplotggplot2ggvis

GGVIS plot for logical matrix


I'm trying to plot a logical matrix similar to the question here, the difference is that I'm trying to do it using ggvis so that I can use the hover tool (the data has several thousand rows so I'd like to see row/column names when I hover over it). The following code worked for me with ggplot2.

library(reshape2)
library(ggplot2)

melted = melt(matrix)
ggplot(melted, aes(x = Var2, y = Var1)) +
    geom_tile(aes(fill = value)) +
    scale_file_manual(values = c("black", "red")) +
    theme(axis.text.x = element_blank(), axis.text.y = element_blank()) +
    coord_fixed(ratio = 1/10)

Solution

  • You can find an example for layer_rects here, I just made some adjustments. Using the example for the linked question:

    Load data

    mm <- structure(c(TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, 
                      FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, 
                      FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, 
                      FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, 
                      FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, 
                      FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, 
                      TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, 
                      TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, 
                      TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, 
                      TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, 
                      TRUE, TRUE, TRUE), .Dim = c(10L, 10L), .Dimnames = list(NULL, 
                                                                              c("n1", "n2", "n3", "n4", "n5", "n1.1", "n2.1", "n3.1", "n4.1", 
                                                                                "n5.1")))
    

    Melt and change types

    library(reshape2)
    melted <- melt(mm)
    
    melted$value <- as.numeric(melted$value)
    melted$Var1 <- as.factor(melted$Var1)
    

    Plot

    melted %>%
      ggvis(~Var2, ~Var1, fill = ~value) %>%
      layer_rects(width = band(), height = band()) %>%
      scale_nominal("x", padding = 0, points = FALSE) %>%
      scale_nominal("y", padding = 0, points = FALSE)
    

    enter image description here