Reputation: 13
I'm using some code that returns a matplotlib.axes object. The code I'm using is the def_density() function at https://github.com/pblischak/HyDe/blob/master/phyde/visualize/viz.py In a loop, I open a data file, parse each line, feed in some data, create an matplotlib.axes object (using the seaborn.kdeplot() method), extract the image and then write the image to file. That works fine, but I'm left with one image per file line. What I really want to do is to gather all of the images, lay them out in a grid and create only one image. I won't know how many images I'll have ahead of time (although of course I could count the number of lines first and then re-iterate over the file with that information).
Here's my code
import phyde as hd
import os
import sys
bootfile = sys.argv[1]
triplesfile = sys.argv[2]
boot = hd.Bootstrap(bootfile)
triples=open(triplesfile, "r")
next(triples)
for line in triples:
triple = line.split()
p1=triple[0]
p2=triple[1]
p3=triple[2]
title="Bootstrap Dist. of Gamma for "+p1+", "+p2+", and "+p3
image= hd.viz.density(boot, 'Gamma', p1, p2, p3, title=title, xlab="Gamma", ylab="Density")
fig = image.get_figure()
figname="density_"+p1+"_"+p2+"_"+p3+".png"
fig.savefig(figname)
My question is, if I have say 20 plots that I want to set out in a 5 x 4 grid, how do I do this? I've tried a number of different methods using examples I found on here, but nothing seems to work (plt.subplots() was something I played around with). Any suggestions would be extremely welcome!
Upvotes: 1
Views: 452
Reputation: 25092
To place the individual density plots in a grid, you have to pass to the plotting function one of the axes in the grid but phyde.viz.density
, a very thin layer over seaborn.kdeplot
, doesn't make a provision for reusing a pre existing axes
.
So you have to define¹ your thin layer that requires a pre existing axes
def density2(ax, boot_obj, attr, p1, hyb, p2, title="", xlab="", ylab="", shade=True, color='b'):
from numpy import array
from seaborn import kdeplot, set_style
set_style("white")
kdeplot(array(boot_obj(attr, p1, hyb, p2)), shade=shade, color=color, ax=ax)
# #####
ax.set(ylabel=ylab, xlabel=xlab, title=title)
and then use plt.subplots
to arrange the individual plots in a grid (you mentioned 5×4 in your question)
...
fig, axes = plt.subplots(5, 4, constrained_layout=True)
for row in axes:
for ax in row:
line = next(triples)
...
density2(ax, boot, 'Gamma', p1, p2, p3, title=title, xlab="Gamma", ylab="Density")
fig.savefig('You have to decide a title for the collection of plots')
1: the function I've defined is (of course) adapted from https://hybridization-detection.readthedocs.io/_modules/phyde/visualize/viz.html
Upvotes: 1