subplots用法详解

subplots用法详解

我们经常看到这个函数被用了很多次,尽管这个例子只是试图创建一个图表.还有其他一些优势吗?官方演示subplots() 也用于**f, ax = plt.subplots()**创建单个图表时,它之后只引用了ax.这是他们使用的代码.

#Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

plt.subplots()是一个返回包含图形和轴对象的元组的函数.因此,在使用时fig, ax = plt.subplots(),将此元组解压缩到变量fig和ax.有fig,如果你想改变人物级别的属性或保存数字作为以后的图像文件是非常有用的(例如用fig.savefig(‘yourfilename.png’).你当然不必使用返回的数字对象,但因此它经常可以看到很多人都用到它.此外,所有轴对象(具有绘图方法的对象)都具有父图形对象,因此:

fig, ax = plt.subplots()

比这更简洁:

fig = plt.figure()
ax = fig.add_subplot(111)

以下问题是如果我想在图中有更多的子图?

正如文档中所提到的,我们可以使用fig = plt.subplots(nrows=2, ncols=2)在一个图形对象中设置一组带有网格(2,2)的子图.

然后我们知道,fig, ax = plt.subplots()返回一个元组,让我们fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2)先尝试一下.

ValueError: not enough values to unpack (expected 4, got 2)

它引发了一个错误,但不用担心,因为我们现在看到它plt.subplots()实际上返回了一个包含两个元素的元组.第一个必须是一个图形对象,另一个应该是一组子图对象.

那么让我们再试一次:

fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)

并检查类型:

type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>

当然,如果你使用参数(nrows = 1,ncols = 4),那么格式应该是:

fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)

所以请记住保持列表的构造与我们在图中设置的子图网格相同.

如果你有很多子图怎么办?这样做更容易:fig,axes = plt.subplots(nrows = 10,ncols = 3)axes = axes.flatten().现在你可以用它的索引来引用每个子图:axes [0],axes [1],…

subplots和subplot的区别

可以plt.subplots()一次制作所有子图,然后将子图的图形和轴(复数轴)作为元组返回。可以将图形理解为在其中绘制草图的画布。

#create a subplot with 2 rows and 1 columns
fig, ax = plt.subplots(2,1)

而plt.subplot()如果要单独添加子图,则可以使用。它仅返回一个子图的轴。

fig = plt.figure() # create the canvas for plotting
ax1 = plt.subplot(2,1,1) 
#(2,1,1) indicates total number of rows, columns, and figure number respectively
ax2 = plt.subplot(2,1,2)

但是,plt.subplots()首选,因为它为您提供了更轻松的选项来直接自定义整个图形

#for example, sharing x-axis, y-axis for all subplots can be specified at once

fig, ax = plt.subplots(2,2, sharex=True, sharey=True)

但是,使用时plt.subplot(),必须为每个轴分别指定,这可能会很麻烦。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章