heliosdrm / GRUtils.jl

Tools for using the GR framework in Julia
Other
31 stars 6 forks source link

Aspect ratio vs figure dimensions #85

Open dpo opened 3 years ago

dpo commented 3 years ago

Thanks for working on GRUtils! I'm really liking the syntax and speed.

I have a question regarding aspect ratio. I've been playing around with the following implementation of spy() (to plot a matrix sparsity pattern). In there, I set the aspect ratio so the plot looks like the actual matrix. But the figure seems to have larger dimensions so that the title and axis labels appear far out. How can I make the figure tight around the plot?

function spy(A::AbstractSparseMatrix)
  nrows, ncols = size(A)
  rows, cols, vals = findnz(A)
  vals .= abs.(vals)
  vals .= 255 * vals ./ maximum(vals)
  scatter(cols, rows,
          50 * ones(length(rows)),  # symbol size
          vals,                     # symbol color
          xlim=(1, ncols),
          ylim=(1, nrows),
          yflip=true,
          grid=false,
          colorbar=false)
  title("$nrows x $ncols, nnz = $(length(vals))")
  xlabel("row")
  ylabel("col")
  aspectratio(ncols / nrows)
  xticks(nrows/10, 10)
  yticks(ncols/10, 10);
end

3865A678-5FB2-4A24-AC50-A2071D947549

Thanks for any comments. I also think it would be nice to have a spy() function in GRUtils!

heliosdrm commented 3 years ago

Hi, thanks for reporting this. You're right: it is not nice that there is so much empty space between the axes an their labels. I'd like to solve it. In the meanwhile, as a quick workaround you might make that plot in a properly sized figure, instead of the default 600x450 size (see ?Figure). For instance:

function spy(A::AbstractSparseMatrix, width=600) # 600 px by default
  nrows, ncols = size(A)
  rows, cols, vals = findnz(A)
  vals .= abs.(vals)
  vals .= 255 * vals ./ maximum(vals)
  height = round(Int, width * nrows/ncols * 1.25) # <- This line and the next one are new
  Figure((width, height))
  scatter(cols, rows,
          50 * ones(length(rows)),  # symbol size
          vals,                     # symbol color
          xlim=(1, ncols),
          ylim=(1, nrows),
          yflip=true,
          grid=false,
          colorbar=false)
  title("$nrows x $ncols, nnz = $(length(vals))")
  xlabel("row")
  ylabel("col")
  aspectratio(ncols / nrows)
  xticks(nrows/10, 10)
  yticks(ncols/10, 10);
end
dpo commented 3 years ago

Many thanks for your quick reply. That already helps. I guess there will be more details to figure out. For instance,

julia> A = sprand(50, 750, 0.2);
julia> spy(A)

gives

Screen Shot 2021-02-18 at 22 55 44

(A = sprand(750, 50, 0.2) looks even funkier ;-). Do you have suggestions for how to set the figure size in semi-reliable manner?