0

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?

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.