From 08288050c6f9547053ec6821b0d35fb6320d3f77 Mon Sep 17 00:00:00 2001 From: Alex Hayes Date: Tue, 17 Nov 2026 18:54:51 -0800 Subject: [PATCH] Plot rows of A down the y axis in plot_sparse_matrix() plot_sparse_matrix() mapped row index i to the x axis, so it was the transpose of plot_dense_matrix(), which puts columns on the x axis and rows down the (reversed) y axis. The difference only shows for asymmetric matrices, e.g. directed or rectangular graphs. Map x = j, y = i, and swap the expand_limits() arguments. Co-Authored-By: Claude Opus 5.5 --- R/plotting.R | 6 ++++-- tests/testthat/test-plotting.R | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 tests/testthat/test-plotting.R diff --git a/R/plotting.R b/R/plotting.R index af44f5c..02cb004 100644 --- a/R/plotting.R +++ b/R/plotting.R @@ -80,11 +80,13 @@ plot_sparse_matrix <- function(A) { A <- methods::as(A, "CsparseMatrix") A <- methods::as(A, "generalMatrix") - ggplot(summary(A), aes(x = i, y = j, fill = as.factor(x))) + + # rows of A go down the y axis and columns along the x axis, as in + # plot_dense_matrix() + ggplot(summary(A), aes(x = j, y = i, fill = as.factor(x))) + geom_tile() + scale_fill_grey() + scale_y_reverse() + - expand_limits(x = nrow(A), y = ncol(A)) + + expand_limits(x = ncol(A), y = nrow(A)) + theme_void() + labs( fill = "Edges" diff --git a/tests/testthat/test-plotting.R b/tests/testthat/test-plotting.R new file mode 100644 index 0000000..69f3a79 --- /dev/null +++ b/tests/testthat/test-plotting.R @@ -0,0 +1,14 @@ +test_that("plot_sparse_matrix() has the same orientation as plot_dense_matrix()", { + # a single entry in row 1, column 3 of a 2 x 4 matrix + A <- Matrix::sparseMatrix(i = 1, j = 3, x = 1, dims = c(2, 4)) + + sparse <- ggplot2::layer_data(plot_sparse_matrix(A)) + dense <- ggplot2::layer_data(plot_dense_matrix(as.matrix(A))) + dense <- dense[dense$fill == max(dense$fill), ] + + # columns along the x axis, rows down the (reversed) y axis + expect_equal(sparse$x, 3) + expect_equal(sparse$y, -1) + expect_equal(sparse$x, dense$x) + expect_equal(sparse$y, dense$y) +})