我在R中有一个表示两个变量的联合probability mass function(pmf)的矩阵,例如:
> matrix(c(.13, .00004, 0, 0, 0, .04, .13, .008, 0, 0, .01, .007, .16, .02, .0004, .004, .025, .070, .14, .01, .001, .007, .028, .028, .12), nrow=5)
[,1] [,2] [,3] [,4] [,5]
[1,] 0.13000 0.040 0.0100 0.004 0.001
[2,] 0.00004 0.130 0.0070 0.025 0.007
[3,] 0.00000 0.008 0.1600 0.070 0.028
[4,] 0.00000 0.000 0.0200 0.140 0.028
[5,] 0.00000 0.000 0.0004 0.010 0.120
我想创建这个数据的2D可视化,将其划分为5x5个较小的正方形,其中单个正方形的颜色与矩阵中的条目成比例。 (在上面的情况下,它沿着对角线是最暗的)。有没有一种简单的方法来生成这种类型的图像?
答案 0 :(得分:4)
试试这个:
library(lattice)
#Build the data
x <- matrix(c(.13, .00004, 0, 0, 0, .04, .13, .008, 0, 0, .01, .007, .16, .02, .0004, .004, .025, .070, .14, .01, .001, .007, .028, .028, .12), nrow=5)
xmin <- min(x)
xmax <- max(x)
#Build the plot
pal <- colorRampPalette(c("lightblue", "blue"), space = "rgb")
levelplot(x, main="5 X 5 Levelplot", xlab="", ylab="", col.regions=pal(120), cuts=100, at=seq(xmin, xmax, (xmax-xmin)/20))
答案 1 :(得分:3)
ggplot可以很容易地处理这个问题。我知道有两种简单的方法可以做到这一点:
library(ggplot2)
dat <- matrix(c(.13, .00004, 0, 0, 0, .04, .13, .008, 0, 0, .01, .007, .16, .02, .0004, .004, .025, .070, .14, .01, .001, .007, .028, .028, .12), nrow=5)
ggfluctuation(as.table(dat), type = "colour") +
scale_fill_gradient(low = "white", high = "blue")
#Or with geom_tile
dat.m <- melt(dat)
ggplot(dat.m, aes(X1, X2, fill = value)) +
geom_tile(colour = "grey") + scale_fill_gradient(low = "white", high = "blue")
为了完整性,这里是格子解决方案(也很简单):
library(lattice)
levelplot(dat)
答案 2 :(得分:3)
可以使用image()
函数:
mat <- matrix(c(.13, .00004, 0, 0, 0,
.04, .13, .008, 0, 0,
.01, .007, .16, .02, .0004,
.004, .025, .070, .14, .01,
.001, .007, .028, .028, .12), nrow=5)
image(mat, col = rev(heat.colors(12)))
但你需要提出正确的配色方案来填充每个类/ bin。在这里,我只是反转默认值以获得较高值的较暗颜色。但还有更好的方法。