2015-04-17 107 views
2

如何繪製以下矩陣如何使用灰度在R中繪製矩陣?

> a<-matrix(c(-1,0,1,0),nrow=2,ncol=2,byrow=TRUE) 
> a 
    [,1] [,2] 
[1,] -1 0 
[2,] 1 0 

原樣,即在圖2D中,表示在一些調色板值,像灰度?

應該得到這樣的:

enter image description here

而與

image(a,col=grey(seq(0, 1, length = 256))) 

我得到這個:

enter image description here

即矩陣重新定位和重新調整。

+0

http://stackoverflow.com/a/28046116/2994949 – rawr

回答

4

就轉(t)的矩陣

image(t(a),col=grey(seq(0, 1, length = 256))) 

如果你想將標籤從1開始,而不是0開始計數做到以下幾點: (從這裏摘自:r- how to edit elements on x axis in image.plot

image(t(a),col=grey(seq(1, 0, length = 256)), axes = F) 
axis(1, at=seq(1,nrow(a))-1, labels=seq(1,nrow(a))) 
axis(2, at=seq(1,ncol(a))-1, labels=seq(1,ncol(a))) 

結果於:

enter image description here

+0

列和行號仍然丟失。我希望保留它們。 –

+0

剛編輯答案 – Rentrop

0

我會這樣做ggplot2。首先重塑數據。

df <- reshape2::melt(a, varnames = c("y", "x"), value.name = "value") 

然後繪製data.framegeom_raster

ggplot(df, aes_string(x = "x", y = "y", fill = "value")) + 
    geom_raster() +      # same as image in base plot 
    scale_x_continuous(name = "column", breaks = c(1, 2)) + # name axis and choose breaks 
    scale_y_reverse(name = "row", breaks = c(1, 2)) +  # reverse scale 
    scale_fill_continuous(high = "white", low = "black", guide = "none") + # grayscale 
    theme_bw(base_size = 14)    # nicer theme