Home > front end >  ggplot plotting a grid
ggplot plotting a grid

Time:12-03

I need to plot this matrix using ggplot

one two two one one two
one two one two two one
two one two two one two 

So that one is a red square and two is a blue square. Essentially a grid with red and blue squares. How can I do this in R?

CodePudding user response:

Given your matrix:

mat <- matrix(c("one", "two", "two", "one", "one", "two", "one", "two", "one", "two", "two", "one",
"two", "one", "two", "two", "one", "two"), nrow = 3, byrow = TRUE)
> mat
     [,1]  [,2]  [,3]  [,4]  [,5]  [,6] 
[1,] "one" "two" "two" "one" "one" "two"
[2,] "one" "two" "one" "two" "two" "one"
[3,] "two" "one" "two" "two" "one" "two"

you can build a dataframe

mat_df <- reshape2::melt(mat)

and then use ggplot2

ggplot(data = mat_df, aes(x = Var1, y = Var2, fill = value))   
  geom_tile()
  • Related