如何使用 matplotlib 在一个页面上制作多个图形?

我写的代码可以同时打开16位数字。目前,它们都以独立的图形形式打开。我希望他们都能在同一页上打开。不是同一张图。我希望在一个单独的页面/窗口上有16个独立的图表。此外,由于某些原因,numbins 和缺省限制的格式没有保留过去的图1。我需要使用子图命令吗?我不明白为什么我必须这么做,但是我不知道我还能做什么?

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()
284981 次浏览

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.

The answer from las3rjock, which somehow is the answer accepted by the OP, is incorrect--the code doesn't run, nor is it valid matplotlib syntax; that answer provides no runnable code and lacks any information or suggestion that the OP might find useful in writing their own code to solve the problem in the OP.

Given that it's the accepted answer and has already received several up-votes, I suppose a little deconstruction is in order.

First, calling subplot does not give you multiple plots; subplot is called to create a single plot, as well as to create multiple plots. In addition, "changing plt.figure(i)" is not correct.

plt.figure() (in which plt or PLT is usually matplotlib's pyplot library imported and rebound as a global variable, plt or sometimes PLT, like so:

from matplotlib import pyplot as PLT


fig = PLT.figure()

the line just above creates a matplotlib figure instance; this object's add_subplot method is then called for every plotting window (informally think of an x & y axis comprising a single subplot). You create (whether just one or for several on a page), like so

fig.add_subplot(111)

this syntax is equivalent to

fig.add_subplot(1,1,1)

choose the one that makes sense to you.

Below I've listed the code to plot two plots on a page, one above the other. The formatting is done via the argument passed to add_subplot. Notice the argument is (211) for the first plot and (212) for the second.

from matplotlib import pyplot as PLT


fig = PLT.figure()


ax1 = fig.add_subplot(211)
ax1.plot([(1, 2), (3, 4)], [(4, 3), (2, 3)])


ax2 = fig.add_subplot(212)
ax2.plot([(7, 2), (5, 3)], [(1, 6), (9, 5)])


PLT.show()

Each of these two arguments is a complete specification for correctly placing the respective plot windows on the page.

211 (which again, could also be written in 3-tuple form as (2,1,1) means two rows and one column of plot windows; the third digit specifies the ordering of that particular subplot window relative to the other subplot windows--in this case, this is the first plot (which places it on row 1) hence plot number 1, row 1 col 1.

The argument passed to the second call to add_subplot, differs from the first only by the trailing digit (a 2 instead of a 1, because this plot is the second plot (row 2, col 1).

An example with more plots: if instead you wanted four plots on a page, in a 2x2 matrix configuration, you would call the add_subplot method four times, passing in these four arguments (221), (222), (223), and (224), to create four plots on a page at 10, 2, 8, and 4 o'clock, respectively and in this order.

Notice that each of the four arguments contains two leadings 2's--that encodes the 2 x 2 configuration, ie, two rows and two columns.

The third (right-most) digit in each of the four arguments encodes the ordering of that particular plot window in the 2 x 2 matrix--ie, row 1 col 1 (1), row 1 col 2 (2), row 2 col 1 (3), row 2 col 2 (4).

This works also:

for i in range(19):
plt.subplot(5,4,i+1)

It plots 19 total graphs on one page. The format is 5 down and 4 across..

Since this question is from 4 years ago new things have been implemented and among them there is a new function plt.subplots which is very convenient:

fig, axes = plot.subplots(nrows=2, ncols=3, sharex=True, sharey=True)

where axes is a numpy.ndarray of AxesSubplot objects, making it very convenient to go through the different subplots just using array indices [i,j].

@doug & FS.'s answer are very good solutions. I want to share the solution for iteration on pandas.dataframe.

import pandas as pd
df=pd.DataFrame([[1, 2], [3, 4], [4, 3], [2, 3]])
fig = plt.figure(figsize=(14,8))
for i in df.columns:
ax=plt.subplot(2,1,i+1)
df[[i]].plot(ax=ax)
print(i)
plt.show()

For example, to create 6 subplots with 2 rows and 3 columns you can use:

funcs = [np.cos, np.sin, np.tan, np.arctan]
x = np.linspace(0, 10, 100)


fig = plt.figure(figsize=(10, 5))


for num, func in enumerate(funcs, start=1):
ax = fig.add_subplot(2, 2, num) # plot with 2 rows and 2 columns
ax.plot(x, func(x))
ax.set_title(func.__name__)


# add spacing between subplots
fig.tight_layout()

Result:

enter image description here