How to create an arbitrary number of subplots in Julia Plots

3.1k views Asked by At

I want to make a set of subplots from a multidimensional array using Breloff's Julia Plots. This plot function takes a varargs input and makes them into subplots, but I can't seem to feed my array in properly and am probably overlooking something simple. For example with an array a:

a = randn(5,5,8)
a = a.-mean(a)
a = a./maximum(extrema(a))

If I want to plot some of the 5x5 slices as heatmaps, I can do:

plot(heatmap(a[:,:,1], aspect_ratio=:equal, clims=(-1,1), title=string(1)), 
heatmap(a[:,:,2], aspect_ratio=:equal, clims=(-1,1), title=string(2)),
heatmap(a[:,:,3], aspect_ratio=:equal, clims=(-1,1), title=string(3)))

which produces:

array of 3 heatmaps

but if I want to do all eight (or a variable number which is my goal), I can't make it work with a loop or a splat. I tried the latter to create a tuple but got an error:

plot(tuple([heatmap(a[:,:,i], aspect_ratio=:equal, clims=(-1,1)) for i in 1:8]...))

LoadError: MethodError: Cannot `convert` an object of type String to an object of type MethodError
This may have arisen from a call to the constructor MethodError(...),
since type constructors fall back to convert methods.
while loading In[1], in expression starting on line 1

What is the best approach here?

1

There are 1 answers

2
Chris Rackauckas On BEST ANSWER

I think the easiest way here is to make the separate plots and then put them together in a final plot. You can make an array of plots in a loop:

plot_array = Any[] # can type this more strictly
for i in 1:n
  push!(plot_array,plot(...)) # make a plot and add it to the plot_array
end
plot(plot_array...)

this works because the setup

p1 = plot(...)
p2 = plot(...)
plot(p1,p2)

creates a plot with subplots p1 and p2, and so we are just using that with an arbitrary amount of plots. You can also set layouts here, though that may be more difficult with arbitrary amounts.