Skip empty entries of sparse matrix when plotting a heatmap

lmiq
Fri, 30 Jan 2026 13:00:10 +0000
General Usage

I want to plot a sparse matrix as a heatmap, something like this:

julia> using Plots, SparseArrays

julia> x = sprand(Float64, 5, 5, 0.5)
5×5 SparseMatrixCSC{Float64, Int64} with 11 stored entries:
  ⋅          ⋅         ⋅         ⋅         ⋅
  ⋅         0.838339  0.330949   ⋅         ⋅
  ⋅         0.456005  0.704216   ⋅         ⋅
 0.0524143  0.622022  0.319052  0.406603   ⋅
 0.356594    ⋅        0.787174  0.693707   ⋅

julia> heatmap(x)

which gives:

The issue is that the non-existing values are treated as zeros, and I want them to be treated as missing, which would give:

julia> y = Matrix(x); z = @. ifelse(y == 0, missing, y)
5×5 Matrix{Union{Missing, Float64}}:
  missing    missing   missing   missing  missing
  missing   0.838339  0.330949   missing  missing
  missing   0.456005  0.704216   missing  missing
 0.0524143  0.622022  0.319052  0.406603  missing
 0.356594    missing  0.787174  0.693707  missing

julia> heatmap(z)

Can anyone see a smart way of achieving this without creating a dense matrix as an intermediate?

6 posts - 3 participants