我想在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)
我想要一张图,
是否有任何包或方法来完成这项工作?我怎样才能做到这一点?
要绘制这个,你需要三个数据点:
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)
