R - 像素矩阵的图像?

Ada*_* SO 32 r image matrix

你怎么用R中的矩阵制作图像?

矩阵值将对应于图像上的像素强度(虽然我只对此时的0,1值白色或黑色感兴趣.),而列和行编号对应于图像上的垂直和水平位置.

通过制作图像我的意思是在屏幕上显示它并将其保存为jpg.

Spa*_*man 34

您可以使用"图片"在屏幕上最简单地显示它:

m = matrix(runif(100),10,10)
par(mar=c(0, 0, 0, 0))
image(m, useRaster=TRUE, axes=FALSE)
Run Code Online (Sandbox Code Playgroud)

您还可以查看光栅包...


mds*_*ner 26

设置没有边距的图:

par(mar = rep(0, 4))
Run Code Online (Sandbox Code Playgroud)

使用灰度图像矩阵,就像间隔人的答案,但完全填充设备:

m = matrix(runif(100),10,10)
image(m, axes = FALSE, col = grey(seq(0, 1, length = 256)))
Run Code Online (Sandbox Code Playgroud)

在调用png()中包装它来创建文件:

png("simpleIm.png")
par(mar = rep(0, 4))
image(m, axes = FALSE, col = grey(seq(0, 1, length = 256)))
dev.off()
Run Code Online (Sandbox Code Playgroud)

如果需要使用空间轴(X和Y的默认值为[0,1]),请使用image.default(x, y, z, ...)x和y给出z中像素中心位置的形式.x并且y可以是长度为dim(z)+ 1,以给出该约定的角坐标.

像素中心(这是图像的默认值):

x <- seq(0, 1, length = nrow(m))
y <- seq(0, 1, length = ncol(m))
image(x, y, m, col = grey(seq(0, 1, length = 256)))
Run Code Online (Sandbox Code Playgroud)

像素角(需要1个额外的x和y,0现在是左下角):

x <- seq(0, 1, length = nrow(m) + 1)
y <- seq(0, 1, length = ncol(m) + 1)
image(x, y, m, col = grey(seq(0, 1, length = 256)))
Run Code Online (Sandbox Code Playgroud)

请注意,从R 2.13中,image.default获得了一个参数useRaster,该参数使用非常有效的新图形函数,rasterImage而不是旧的image,它实际上是多次调用rect引擎盖下来将每个像素绘制为多边形.


bil*_*080 12

我做了一个矩阵(垂直轴向下增加)两种方式之一.下面是使用heatmap.2()的第一种方法.它可以更好地控制图中数值的格式化(参见下面的formatC语句),但在更改布局时要稍微处理一下.

 library(gplots)

 #Build the matrix data to look like a correlation matrix
 x <- matrix(rnorm(64), nrow=8)
 x <- (x - min(x))/(max(x) - min(x)) #Scale the data to be between 0 and 1
 for (i in 1:8) x[i, i] <- 1.0 #Make the diagonal all 1's

 #Format the data for the plot
 xval <- formatC(x, format="f", digits=2)
 pal <- colorRampPalette(c(rgb(0.96,0.96,1), rgb(0.1,0.1,0.9)), space = "rgb")

 #Plot the matrix
 x_hm <- heatmap.2(x, Rowv=FALSE, Colv=FALSE, dendrogram="none", main="8 X 8 Matrix Using Heatmap.2", xlab="Columns", ylab="Rows", col=pal, tracecol="#303030", trace="none", cellnote=xval, notecol="black", notecex=0.8, keysize = 1.5, margins=c(5, 5))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述