python - 为什么很多例子在 Matplotlib/pyplot/python 中使用 `fig, ax = plt.subplots()`

标签 python matplotlib plot visualization

我正在通过学​​习示例来学习使用 matplotlib,很多示例似乎在创建单个绘图之前都包含如下一行...

fig, ax = plt.subplots()

这里有一些例子......

我看到这个函数被大量使用,即使这个例子只是试图创建一个图表。有没有其他优势? subplots() 的官方演示在创建单个图表时也使用了 f, ax = 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() 时,您将此元组解包到变量 figax 中。如果您想更改图形级别的属性或稍后将图形保存为图像文件(例如使用 fig.savefig('yourfilename.png')),使用 fig 非常有用.您当然不必使用返回的图形对象,但很多人稍后会使用它,因此很常见。此外,所有轴对象(具有绘图方法的对象)无论如何都有一个父图形对象,因此:

fig, ax = plt.subplots()

比这更简洁:

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

关于python - 为什么很多例子在 Matplotlib/pyplot/python 中使用 `fig, ax = plt.subplots()`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34162443/

相关文章:

python numpy ValueError : operands could not be broadcast together with shapes

python - Google Collab Notebook与普通的Python脚本创建了不同类型的绘图大小

matplotlib - 如何在 basemap 上绘制矩形

python - 调整文本背景透明度

r - 绘制 : color based on the combination of two column levels

python - 如何使用 3 个列表在 Python 中创建嵌套字典

python - 从列中清除字符/str 并将其设为 int 时出现问题

R中箱线图中的反向y轴

python - 在python sqlalchemy中为具有动态名称的列设置值

python : How to create a 2D density map/heat map