r中的矩阵图

Kaj*_*aja 4 plot r

我想在r中创建这样一个图:

在此输入图像描述

我有一个这样的矩阵

 [1]   [2]   [3]   [4]   [5] .... [30]

[1] 0.5   0.75  1.5   0.25  2.5 .... 0.51

[1] 0.84  0.24  3.5   0.85  0.25.... 1.75

[1] 0.35  4.2   0.52  1.5   0.35.... 0.75
.
. .......................................
.
[30]0.84  1.24  0.55   1.5  0.85.... 2.75
Run Code Online (Sandbox Code Playgroud)

我想要一张图,

  • 如果值小于一个---->绿色圆圈
  • 如果一个和两个之间的值---->黄色圆圈
  • 两个以上---->红圈

是否有任何包或方法来完成这项工作?我怎样才能做到这一点?

Ric*_*rta 6

要绘制这个,你需要三个数据点:

x, y, color
Run Code Online (Sandbox Code Playgroud)

因此,第一步是重塑.
幸运的是,matricies已经是一个向量,只需要一个维度属性,所以我们只需要创建一个x,y坐标的data.frame.我们这样做expand.grid.

# create sample data. 
mat <- matrix(round(runif(900-30, 0, 5),2), 30)
Run Code Online (Sandbox Code Playgroud)

创建(x,y)data.frame.
请注意,y是的SEQ x的以次

dat <- expand.grid(y=seq(nrow(mat)), x=seq(ncol(mat)))

## add in the values from the matrix. 
dat <- data.frame(dat, value=as.vector(mat))

## Create a column with the appropriate colors based on the value.
dat$color <- cut( dat$value, 
                  breaks=c(-Inf, 1, 2, Inf), 
                  labels=c("green", "yellow", "red")
                 )



## Plotting
library(ggplot2)
ggplot(data=dat, aes(x=x, y=y)) + geom_point(color=dat$color, size=7)
Run Code Online (Sandbox Code Playgroud)

样本输出

  • @kaja,没有概率.`cut`语句只是制作三个独立的`ifelse()`语句的简单方法.它对连续向量进行分段,并且中断内的每个值都是一个组.`labels`参数表示将每个组标记为什么 (2认同)