Matplotlib:Adding an axes using the same arguments as a previous axes

本文探讨了在使用Matplotlib时遇到的一个警告:创建相同参数的Axes实例导致的重复问题。通过调整代码结构,即将图标题和坐标轴标签的设置从主图移至子图中,成功避免了这一警告,确保了图表的正确生成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习《机器学习实战》kNN时,在使用Matplotlib画图时,发现了一个Warining

MatplotlibDeprecationWarning: 
Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
  "Adding an axes using the same arguments as a previous axes "

原因可能是在创建画板fig=plt.figure()后就设置了图标题和坐标轴标签,将图标题和坐标轴标签在定义了子图ax=fig.add_subplot(111)后再设置就不会出现这个Warining了。代码如下

定义子图前设置标题和坐标轴标签,有Warining

def show_1(datingDataMat,datingLabels):
    fig=plt.figure()
    plt.title('散点分析图')
    # 用来正常显示中文标签
    mpl.rcParams ['font.sans-serif']=['KaiTi']
    mpl.rcParams ['font.serif']=['KaiTi']
    plt.xlabel('玩视频游戏所耗时间百分比')
    plt.ylabel('每周消费的冰淇淋公升数')
    ax=fig.add_subplot(111)
    #ax.set_title('散点分析图')
    # ax.set_xlabel('玩视频游戏所耗时间百分比')
    # ax.set_ylabel('每周消费的冰淇淋公升数')
    ax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*array(datingLabels),15.0*array(datingLabels))
    plt.show()
                
      

定义子图后设置标题和坐标轴标签,无Warining 

def show_1(datingDataMat,datingLabels):
    fig=plt.figure()
    #plt.title('散点分析图')
    # 用来正常显示中文标签
    mpl.rcParams ['font.sans-serif']=['KaiTi']
    mpl.rcParams ['font.serif']=['KaiTi']
    #plt.xlabel('玩视频游戏所耗时间百分比')
    #plt.ylabel('每周消费的冰淇淋公升数')
    ax=fig.add_subplot(111)
    ax.set_title('散点分析图')
    ax.set_xlabel('玩视频游戏所耗时间百分比')
    ax.set_ylabel('每周消费的冰淇淋公升数')
    ax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*array(datingLabels),15.0*array(datingLabels))
    plt.show()
                
      

 

 
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值