简体   繁体   中英

R plot 2D surface of a matrix of numbers

I am currently trying, given an*p matrix of numbers, to plot a graph with n*p squares, each square having a colour depending of the number in the matrix.

The matrix is defined as follow:

ll <- list(c(1,3,4,3,6,5,8),c(1,1,4,5,7,6,8),c(1,3,1,1,3,4,8),c(2,1,1,2,1,3,5))
mm <- do.call(rbind,ll)

In a very general way, I would like to define colors for group of numbers. For example:

  • Yellow for the group {1,2}
  • Orange for the group {3,4,5}
  • Red for the gorup of numbers {6,7,8}

And then "plot" the matrix. Like the colorfull matplotlib picture on this link: http://activeintelligence.org/blog/archive/matplotlib-sparse-matrix-plot/

I really have no clue how to do it, and any point of view would be greatly appreciated!

 cc <- mm  # make copy to modify
 cc[] <- findInterval(cc, c(0, 2.5, 5.5, 8.5 ) )  # values 1:3
 cc
image(seq(dim(cc)[1]), seq(dim(cc)[2]), cc, col=c("yellow","orange","red"))

The values in the cc -matrix will pull from the color vector.

I suppose that the position of the points are defined by the n and p ranks. You could handle this with ggplot2 and reshape2.

ll <- list(c(1,3,4,3,6,5,8),c(1,1,4,5,7,6,8),c(1,3,1,1,3,4,8),c(2,1,1,2,1,3,5))
mm <- do.call(rbind,ll)
rownames(mm) = 1:nrow(mm)
colnames(mm) = 1:ncol(mm)

library(reshape2)
library(ggplot2)
mm_long = melt(mm)
colnames(mm_long) = c("x", "y", "group")
mm_long$colour_group = NA
mm_long$colour_group[mm_long$group %in% c(1,2)] = 1
mm_long$colour_group[mm_long$group %in% c(3,4,5)] = 2
mm_long$colour_group[mm_long$group %in% c(6,7,8)] = 3

mm_long$group = factor(mm_long$group)
mm_long$colour_group = factor(mm_long$colour_group)

ggplot(mm_long, aes(x=x, y=y)) +
  geom_point(aes(colour=colour_group), shape=15, size=10) +
  scale_colour_manual(values = c("yellow","orange", "red"))

Basically following suggestions from @MrFlick & @BondedDust:

cols=c(rep("yellow", 2), rep("orange", 3), rep("red", 3))

image(1:ncol(mm), 1:nrow(mm), t(mm), col=cols, breaks=c(0:length(cols))+0.5, xlab="", ylab="")

or

heatmap(mm, col=cols, breaks=c(0:length(cols))+0.5, Colv=NA, Rowv=NA, scale="none")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM