I have the following 4x4 number matrix containing the numbers 0-4:
0 1 0 3
3 2 1 4
4 1 0 2
3 3 0 1
I would like to understand how to convert number matrices into a color matrices using chosen colors and specific square dimensions (length x width) using R. To be clear, I'm defining color matrix as a figure using colored squares to represent specific values in a matrix orientation. An example 4x4 from another program follows:
I would have to assign color codes to the numbers, for example:
0 = FFFFFF
1 = 99FF66
2 = 66FF33
3 = 33CC00
4 = 009900
But I don't know where to begin putting this together. I imagine I would also have to specify dimensions for color squares as well.
My goal is to be able to import a data frame into R with up to 10 numerical values and create these color charts for matrices as large as 20x20.
numeric() function with the name of the given character matrix as its parameter and this will help the user to convert the character matrix to numeric vector and in the next step user has to call another function matrix() with the numeric vector (which was created by the as.
To convert an array into a matrix in R, we can use apply function. For example, if we have an array called ARRAY that contains 2 array elements then we can convert this array into a single matrix using the command apply(ARRAY,2,c).
A matrix can be converted to a dataframe by using a function called as. data. frame(). It will take each column from the matrix and convert it to each column in the dataframe.
By default, as. list() converts the matrix to a list of lists in column-major order. Therefore, we have to use unlist() function to convert the list of lists to a single list. unlist() function in R Language is used to convert a list of lists to a single list, by preserving all the components.
Here's what I would do:
d<-read.table(text="
0 1 0 3
3 2 1 4
4 1 0 2
3 3 0 1")
cols <- c(
'0' = "#FFFFFF",
'1' = "#99FF66",
'2' = "#66FF33",
'3' = "#33CC00",
'4' = "#009900"
)
# the names aren't necessary here.
image(1:nrow(d), 1:ncol(d), as.matrix(d), col=cols)
If you'd prefer for the orientation to be different, you can rotate the matrix:
image(1:nrow(d), 1:ncol(d), t(apply(d, 2, rev)), col=cols)
To get rid of all the text and borders, you might try:
image(1:nrow(d), 1:ncol(d), as.matrix(d), col=cols,
xaxt="n", yaxt="n", bty="n", xlab="", ylab="")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With