我有几个10x10矩阵,其中填充了五个值:0、0.5、1、1.5和2。并非所有矩阵都具有所有这些值。
我想用相同的颜色 始终 进行绘制。我想将五种特定颜色链接到特定值,即:
当前,代码如下:
example_mat <- matrix(sample(c(0,0.5,1,1.5,2),100, replace = TRUE), nrow = 10, ncol = 10)
# make rotate function for plot
rotate <- function(x) t(apply(x, 2, rev))
# plot
image(rotate(example_mat), col=c("white","light blue","blue","lightpink1","red"), xaxt= "n", yaxt= "n")
grid(nx = 10, ny = 10, col = "black", lty = "solid")
box(which = "plot", lty = "solid")
这产生了以下情节:
这似乎工作得很好,除了我有很多这样的图,有时矩阵中不是所有5个值(0、0.5、1、1.5和2)都存在,然后他将不同的颜色分配给了价值观。如何使该图始终具有相同的颜色和相同的值?
答案 0 :(得分:2)
一种方法是使用ggplot
并根据其值为每个图块预定义填充颜色。
#Define colors using named vector
mycols = c(white = 0, lightblue = 0.5, blue = 1, pink = 1.5, red = 2)
#DATA
set.seed(42)
example_mat = matrix(sample(c(0,0.5,1,1.5,2),100, replace = TRUE), nrow = 10, ncol = 10)
rotate <- function(x) t(apply(x, 2, rev))
m1 = rotate(example_mat)
library(ggplot2)
#Convert to long format
d = data.frame(Values = as.vector(m1),
fillcol = names(mycols[match(m1, mycols)]),
X = as.vector(row(m1)),
Y = as.vector(col(m1)))
graphics.off()
ggplot(d, aes(x = X, y = Y)) +
geom_tile(color = "black", fill = d$fillcol) +
theme_light() +
coord_equal()
答案 1 :(得分:2)
使用基数R,zlim
函数有一个image
参数来完成这项工作。
set.seed(42)
example_mat1 <- matrix(sample(c(0,0.5,1,1.5,2),100, replace = TRUE), nrow = 10, ncol = 10)
example_mat2 <- example_mat1
example_mat2[example_mat2 == 2] = 0 # remove one of the values
# make rotate function for plot
rotate <- function(x) t(apply(x, 2, rev))
# plot
image(rotate(example_mat1), col=c("white","light blue","blue","lightpink1","red"), zlim=c(0,2), xaxt= "n", yaxt= "n")
grid(nx = 10, ny = 10, col = "black", lty = "solid")
box(which = "plot", lty = "solid")
image(rotate(example_mat2), col=c("white","light blue","blue","lightpink1","red"), zlim=c(0,2), xaxt= "n", yaxt= "n")
grid(nx = 10, ny = 10, col = "black", lty = "solid")
box(which = "plot", lty = "solid")
这将产生以下情节...
答案 2 :(得分:1)
我将使用几个dplyr
和tidyr
函数来处理此问题,以创建形状适合ggplot2
的数据框,然后使用ggplot2
的图块。我将值列视为使其明确离散的字符。如果您有更多值,则可以改用cut
来分解为因子水平。
首先,我将颜色命名为矢量,并将其放入scale_fill_manual
中-颜色是矢量元素,相应的数字是名称,以及刻度尺{{1}的预期设置}参数。
values
然后要重塑数据以进行绘图,我制作了一个数据框,添加了行号,并使用library(ggplot2)
library(dplyr)
library(tidyr)
set.seed(324)
example_mat <- matrix(sample(c(0,0.5,1,1.5,2),100, replace = TRUE), nrow = 10, ncol = 10)
colors <- c("white", "lightblue", "blue", "lightpink1", "red") %>%
setNames(c(0, 0.5, 1, 1.5, 2))
转换为长形。自动列名分别为gather
,V1
,...,因此我使用正则表达式V2
提取了该文本的数字部分以获取列号。
\\d+
然后绘制非常简单,将值视为字符,并为填充指定命名的调色板。
rotate <- function(x) t(apply(x, 2, rev))
mat_long <- rotate(example_mat) %>%
as_tibble() %>%
mutate(row = row_number()) %>%
gather(key = col, value = value, -row) %>%
mutate(col = stringr::str_extract(col, "\\d+") %>% as.numeric())
mat_long
#> # A tibble: 100 x 3
#> row col value
#> <int> <dbl> <dbl>
#> 1 1 1 1
#> 2 2 1 1.5
#> 3 3 1 1.5
#> 4 4 1 2
#> 5 5 1 1.5
#> 6 6 1 0.5
#> 7 7 1 0
#> 8 8 1 1
#> 9 9 1 0.5
#> 10 10 1 0.5
#> # … with 90 more rows
由reprex package(v0.2.1)于2019-03-24创建