如何使用 matplotlib 在单个页面上绘制多个绘图?
我编写了一次打开 16 个数字的代码。目前,它们都作为单独的图表打开。我希望他们在同一页面上打开所有内容。不是同一个图表。我想要在单个页面/窗口上显示 16 个独立的图表。此外,由于某种原因,numbins 和 defaultreallimits 的格式不符合图 1。我需要使用 subplot 命令吗?我不明白为什么我必须这样做,但不知道我还能做什么?
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()
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. Furthermore, 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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
las3rjock 的答案(不知何故是 OP 接受的答案)是不正确的——代码无法运行,也不是有效的 matplotlib 语法;该答案没有提供可运行的代码,并且缺少OP在编写自己的代码来解决OP中的问题时可能会发现有用的任何信息或建议。
鉴于这是已接受的答案并且已经收到了几票赞成票,我认为需要进行一些解构。
首先,调用subplot不会不会给你多个图; subplot 被调用来创建单个图,以及创建多个图。另外,“改变plt.figure(i)”是不正确的。
plt.figure() (其中 plt 或 PLT 通常是 matplotlib 的 pyplot 库 导入并反弹为全局变量、plt 或有时是 PLT,如下所示:
上面的行创建一个 matplotlib 图实例;然后为每个绘图窗口(非正式地认为包含单个子图的 x 和 y 轴)调用该对象的 add_subplot 方法(无论是一个子图还是多个子图)。一个页面),就像这样,
这个语法相当于
选择对您有意义的语法,
下面我列出了在一页上绘制两个图的代码,一个在另一个之上,格式是通过传递给 < 的参数完成的。 strong>add_subplot。请注意,第一个图的参数为 (211),而 (212) )对于第二个参数,
每个参数都是在页面上正确放置相应绘图窗口的完整规范
(同样,也可以用 3 编写) 。 -元组形式为 (2,1,1) 表示绘图窗口的两行和一列;第三位数字指定该特定子图窗口相对于其他子图窗口的顺序 - 在本例中,这是第一个图(将其放置在第 1 行),因此图号为 1,第 1 行第 1 列。
参数传递给第二次调用 add_subplot 与第一次的区别仅在于尾随数字(2 而不是 1,因为该图是第二个图(第 2 行,第 1 列)。
包含更多图的示例:如果您希望在 2x2 矩阵配置中在页面上绘制四个图,则可以调用 add_subplot 方法四次,并传入这四个参数 (221)、(222)、(223),和 (224),分别按此顺序在页面上的 10、2、8 和 4 点位置创建四个绘图。
请注意,四个参数中的每一个都包含两个前导 2——编码 2 x 2。配置,即两行和两列,
四个参数中的每一个中的第三个(最右边)数字编码 2 x 2 矩阵中特定绘图窗口的顺序 - 即,第 1 行第 1 列 (1),第 1 行第 2 列 (2)、第 2 行第 1 列 (3)、第 2 行第 2 列 (4)。
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:
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
this syntax is equivalent to
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.
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).
由于这个问题是从 4 年前开始的,新的事物已经被实现,其中有一个 新函数
plt.subplots
非常方便:其中
axes
是AxesSubplot对象的numpy.ndarray
,非常方便只需使用数组索引[i,j]
即可浏览不同的子图。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:where
axes
is anumpy.ndarray
of AxesSubplot objects, making it very convenient to go through the different subplots just using array indices[i,j]
.要回答您的主要问题,您需要使用 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)
toplt.subplot(4,4,i+1)
should work.这也有效:
它在一页上绘制总共 19 个图表。格式为 5 向下 4 横向..
This works also:
It plots 19 total graphs on one page. The format is 5 down and 4 across..
@道格& FS.的回答是非常好的解决方案。我想分享 pandas.dataframe 上迭代的解决方案。
@doug & FS.'s answer are very good solutions. I want to share the solution for iteration on pandas.dataframe.
您可以使用方法
add_subplot
。例如,要创建 6 个 2 行 3 列的子图,您可以使用:结果:
You can use the method
add_subplot
. For example, to create 6 subplots with 2 rows and 3 columns you can use:Result: