学习matplotlib时遇到的一个小问题,请各位帮我看一下

在导入matplotlib.pyplot并as为plt后
创建了figure画布
fig = plt.figure()
但创建axes对象时,发现fig.后面不会出现任何函数。难道add_subplot需要手打嘛?

img

问题点: 代码无智能提示问题
分析思路: python并不知道你fig到底是什么类型的对象,不知道什么类型那就无从谈起给你提示什么方法。
解决办法:
实例化时, 后面添加 # type.

type:就告诉了IDE,我这是matplotlib.figure.Figure这个对象

import matplotlib.pyplot as plt
import matplotlib.figure  # 添加引用
fig = plt.figure()  # type:matplotlib.figure.Figure
fig.#在此处,点之后就会给出代码提示了

每一次解答都是一次用心理解的过程,期望对你有所帮助。
参考结合AI智能库,如有帮助,恭请采纳。

是的,在创建 matplotlib 的 figure 对象后,需要使用 add_subplot 函数来创建 axes 对象。以下是创建 figure 和 axes 对象的示例代码:

import matplotlib.pyplot as plt  
  
# 创建 figure 对象  
fig = plt.figure()  
  
# 创建 Axes 对象  
ax = fig.add_subplot(1, 1, 1)  
  
# 在 Axes 对象上绘制图形  
ax.plot([1, 2, 3], [4, 5, 6])  
  
# 显示图形  
plt.show()


不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 你可以参考下这篇文章:matplotlib入门---add_subplot切割区域
  • 除此之外, 这篇博客: matplotlib.pyplot中add_subplot方法参数111的含义中的 中add_subplot方法参数111的含义/ 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
     #引入对应的库函数
    import matplotlib.pyplot as plt
    from numpy import *
    
    #绘图
    fig = plt.figure()
    ax = fig.add_subplot(349)
    ax.plot(x,y)
    plt.show()
    

    其中,参数349的意思是:将画布分割成3行4列,图像画在从左到右从上到下的第9块,如下图:
    这里写图片描述

    那第十块怎么办,3410是不行的,可以用另一种方式(3,4,10)。
    如果一块画布中要显示多个图怎么处理?

    import matplotlib.pyplot as plt
    from numpy import *
    
    fig = plt.figure()
    ax = fig.add_subplot(2,1,1)
    ax.plot(x,y)
    ax = fig.add_subplot(2,2,3)
    ax.plot(x,y)
    plt.show()

    这里写图片描述


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

import matplotlib.pyplot as plt

# 创建figure画布
fig = plt.figure()

# 添加第一个子图,参数为子图在整个画布中的位置,例如(2, 2, 1)表示2行2列的子图中的第1个位置
ax1 = fig.add_subplot(2, 2, 1)
ax1.plot([1, 2, 3], [4, 5, 6])

# 添加第二个子图
ax2 = fig.add_subplot(2, 2, 2)
ax2.scatter([1, 2, 3], [4, 5, 6])

plt.show()


import matplotlib.pyplot as plt

# 创建figure画布和一组axes子图
fig, axes = plt.subplots(2, 2)

# 在第一个子图中绘制曲线
axes[0, 0].plot([1, 2, 3], [4, 5, 6])

# 在第二个子图中绘制散点图
axes[0, 1].scatter([1, 2, 3], [4, 5, 6])

plt.show()