如何绘制 matplotlib.axes 列表?

我正在使用一些返回 matplotlib.axes 对象的代码。我使用的代码是https://github.com/pblischak/HyDe/blob/master/phyde/visualize/viz.py上的 def_density() 函数 在一个循环中,我打开一个数据文件,解析每一行,输入一些数据,创建一个 matplotlib.axes 对象(使用 seaborn.kdeplot() 方法),提取图像,然后将图像写入文件。这很好用,但我只剩下每个文件行一张图像。我真正想做的是收集所有图像,将它们放在网格中并只创建一个图像。我不会提前知道有多少图像(当然我可以先计算行数,然后使用该信息重新遍历文件)。

这是我的代码

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)

    

我的问题是,如果我说要在 5 x 4 网格中设置 20 个地块,我该怎么做?我已经使用我在此处找到的示例尝试了许多不同的方法,但似乎没有任何效果(plt.subplots() 是我玩过的东西)。任何建议都将非常受欢迎!


德玛西亚99
浏览 123回答 1
1回答

holdtom

要将单独的密度图放置在网格中,您必须将网格中的一个轴传递给绘图函数,但是,phyde.viz.density非常薄的一层seaborn.kdeplot,没有为重用预先存在的axes.所以你必须定义¹你的薄层需要预先存在axesdef 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)然后用于plt.subplots将各个地块排列在网格中(您在问题中提到了 5×4)...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')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python