如何使用 matplotlib 在单个页面上绘制多个图?

问题描述:

我编写了一次打开 16 个数字的代码.目前,它们都作为单独的图形打开.我希望它们都在同一页面上打开.不一样的图.我想要在一个页面/窗口上有 16 个单独的图形.同样出于某种原因,numbins 和 defaultreallimits 的格式不超过图 1.我需要使用 subplot 命令吗?我不明白为什么我必须这样做,但不知道我还能做什么?

I have written code that opens 16 figures at once. Currently they all open as separate graphs. I'd like them to open all on the same page. Not the same graph. I want 16 separate graphs on a single page/window. Also for some reason the format of the numbins and defaultreallimits doesn't hold past figure 1. Do I need to use the subplot command? I don't understand why I would have to but can't figure out what else I would do?

import csv
import scipy.stats
import numpy
import matplotlib.pyplot as plt

for i in range(16):
    plt.figure(i)
    filename= easygui.fileopenbox(msg='Pdf distance 90m contour', title='select file', filetypes=['*.csv'], default='X:\herring_schools\')
    alt_file=open(filename)    
    a=[]
    for row in csv.DictReader(alt_file):
        a.append(row['Dist_90m(nmi)'])
    y= numpy.array(a, float)    
    relpdf=scipy.stats.relfreq(y, numbins=7, defaultreallimits=(-10,60))
    bins = numpy.arange(-10,60,10)
    print numpy.sum(relpdf[0])
    print bins
    patches=plt.bar(bins,relpdf[0], width=10, facecolor='black')
    titlename= easygui.enterbox(msg='write graph title', title='', default='', strip=True, image=None, root=None)
    plt.title(titlename)
    plt.ylabel('Probability Density Function')
    plt.xlabel('Distance from 90m Contour Line(nm)')
    plt.ylim([0,1])

plt.show()

要回答您的主要问题,您需要使用 subplot 命令.我认为将 plt.figure(i) 更改为 plt.subplot(4,4,i+1) 应该可行.

To answer your main question, you want to use the subplot command. I think changing plt.figure(i) to plt.subplot(4,4,i+1) should work.