这在 R 中非常简单。假设我有一个这样的矩阵:
set.seed(69)
m <- matrix(rpois(100, 5), nrow = 10, dimnames = list(y = 1:10, x = 1:10))
m
#> x
#> y 1 2 3 4 5 6 7 8 9 10
#> 1 5 8 4 6 11 5 5 5 6 6
#> 2 7 4 3 8 4 7 2 6 5 7
#> 3 6 8 6 4 5 6 1 8 5 5
#> 4 7 3 4 5 6 4 5 7 6 4
#> 5 4 3 3 4 3 9 1 2 10 2
#> 6 8 3 3 6 1 6 8 10 5 3
#> 7 3 2 6 6 2 3 4 4 6 5
#> 8 7 6 6 5 3 3 5 5 7 3
#> 9 3 2 2 4 4 7 8 4 5 4
#> 10 1 7 4 5 3 6 6 6 6 5
我可以像这样将它重塑为 x、y 和 value 列:
library(reshape2)
df <- melt(m)
并像这样绘制它:
ggplot(df, aes(x, y, fill = value)) +
geom_tile() +
scale_fill_viridis_c() + coord_equal() + theme_minimal()
您也不必担心重塑的计算时间。这是重塑 700 * 900 矩阵的基准:
m <- matrix(rpois(630000, 5), nrow = 700, dimnames = list(y = 1:700, x = 1:900))
microbenchmark::microbenchmark(melt(m))
#> Unit: milliseconds
#> expr min lq mean median uq max neval
#> melt(m) 10.5401 13.45535 16.60985 14.1058 14.8661 79.3941 100
只需要 14 毫秒,所以你的大矩阵可以在the blink of an eye. 中重塑大约 7 次