How to plot on a square grid with specific colours?

I am trying to plot on a 2D grid the presence of “agents” (integers) on a certain plot, but I can"t get:

  • how to associate a specific colour to a certain cell integer
  • how to force the plot to be squared

Here it is what I have achieved so far:

using Random, Plots
n = 16
nRed = Int(round(n*n*0.1))
nBlue = Int(round(n*n*0.2))
cells = fill(0,n*n)
#cells = Array{Union{Missing,Int64}}(missing,n,n)
cells[1:nRed] .= 1
cells[nRed+1:nRed+nBlue] .= 2
shuffle!(cells)
heatmap(reshape(cells,n,n), legend=nothing, title="Interation 1")

Producing:
image

I think you should be able to manually set the colormap and aspect ratio:

using Plots

Z = rand(0:2, (10, 10));

heatmap(Z; color=palette(:Blues, 3), aspect_ratio=1, size=(600, 600))

I was a bit curious about if we could tweak the colorbar ticks, but it looks like that is not directly supported just yet ([FR] Colorbar properties · Issue #3174 · JuliaPlots/Plots.jl · GitHub). I only did a quick search though, so maybe there is another way.

Here is a similar example in Makie.jl if that might be useful:

f = Figure()
ax = Axis(f[1, 1])
hm = heatmap!(ax, Z'; colormap=cgrad(:Blues, 3; categorical=true))
Colorbar(f[1, 2], hm; ticks=0:2)
colsize!(f.layout, 1, Aspect(1, 1.0))
resize_to_layout!(f)
f

which has deep support for further customizations (e.g., Colorbar, ticks, and aspect ratio)

1 Like

Thanks, I am almost there. Only, the aspect_ratio seems to relate to the inner part of the figure, not the whole figure like in your screenshot…

using Random, Plots
n       = 16
nRed    = Int(round(n*n*0.1))
nBlue   = Int(round(n*n*0.2))
cells   = fill(0,n*n)
cells[1:nRed] .= 1
cells[nRed+1:nRed+nBlue] .= 2
shuffle!(cells)
mypal   = [:white,:red,:blue]
# or mypal = [RGB(255/255, 255/255, 255/255), RGB(255/255, 0/255, 0/255), RGB(0/255, 0/255, 255/255)]
heatmap(reshape(cells,n,n), legend=nothing, title="Iteration 1", color=mypal,aspect_ratio=1)

image

[EDIT]: Ok, I didn’t specified the size, while specifying the size I also obtain the squared figure, thanks!