[英]How to plot matrix as-is in R using grayscale?
如何繪制以下矩陣
> a<-matrix(c(-1,0,1,0),nrow=2,ncol=2,byrow=TRUE)
> a
[,1] [,2]
[1,] -1 0
[2,] 1 0
原樣,即以2D形式表示某些調色板中的值,例如灰度?
應該得到這樣的東西:
與
image(a,col=grey(seq(0, 1, length = 256)))
我得到這個:
即矩陣被重新定向和縮放。
只需轉置( t
)您的矩陣
image(t(a),col=grey(seq(0, 1, length = 256)))
如果您希望標簽從1開始而不是從0開始計數,請執行以下操作:(從此處取: r-如何在image.plot中的x軸上編輯元素 )
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)))
結果是:
我會用ggplot2
做到這ggplot2
。 首先重塑數據。
df <- reshape2::melt(a, varnames = c("y", "x"), value.name = "value")
然后繪制該data.frame
與geom_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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.