python隐藏坐标轴_Python Matplotlib-隐藏轴警告提示、解决方案,Pythonmatplotlib,坐标轴,时,出现,的,方法,心得...

在使用Python Matplotlib隐藏坐标轴时遇到警告问题,分析了MatplotlibDeprecationWarning的原因并提供了解决方案,即通过获取当前轴实例并分别设置xaxis和yaxis的可见性来避免重复创建新实例。
摘要由CSDN通过智能技术生成

Python-matplotlib-隐藏坐标轴时出现的警告

在《Python编程-从入门到实践》-【美】Eric Matthes 著,一书中第 301页,对于随机漫步5000点的项目,为了避免坐标轴干扰对随机漫步路径的注意,需要隐藏坐标轴。

环境:python3.9

出现的问题

import matplotlib.pyplot as plt

from random_walk import RandomWalk

while True:

# Create an instance and draw

rw = RandomWalk(50000)

rw.fill_walk()

# Hide axes

plt.axes().get_xaxis().set_visible(False)

plt.axes().get_yaxis().set_visible(False)

point_numbers = list(range(rw.num_points))

plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=1)

# Highlight the start and end

plt.scatter(0, 0, c='green', edgecolors='none', s=100)

plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)

plt.show()

keep_running = input("Make another walk?(y/n):")

if keep_running == 'n':

break

在运行时出现的提示信息:

D:\Python39\python.exe D:/Python39/matplotlib_work/rw_visual.py

D:\Python39\matplotlib_work\rw_visual.py:16: 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.

plt.axes().get_yaxis().set_visible(False)

Make another walk?(y/n):

这里是对隐藏坐标轴的两行代码的第二行进行了警告提示。如果将隐藏坐标轴的两行代码

#--snip--

# Hide axes

plt.axes().get_xaxis().set_visible(False)

plt.axes().get_yaxis().set_visible(False)

#--snip--

放置在

#--snip--

plt.show()

#--snip--

之后。则会出现两次同样的提示。

问题分析

根据对警告提示的说明。我们知道这个提示来自于matplotlib,其中提到了重复创建新实例的问题。那么我们只对一个实例进行操作,就能解决问题。

问题的解决

将代码:

#--snip--

# Hide axes

plt.axes().get_xaxis().set_visible(False)

plt.axes().get_yaxis().set_visible(False)

#--snip--

修改为:

#--snip--

# Hide axes

current_axes = plt.axes()

current_axes.xaxis.set_visible(False)

current_axes.yaxis.set_visible(False)

#--snip--

这里我们将通过 plt.axes() 获得的实例存储在变量current_axes中,再通过对实例中属性xaxis和yaxis的修改来实现对坐标轴的隐藏。

在我们可以在matplotlib/axex/_base.py中看到 xaxis 和 yaxis 。

def _init_axis(self):

# This is moved out of __init__ because non-separable axes don't use it

self.xaxis = maxis.XAxis(self)

self.spines['bottom'].register_axis(self.xaxis)

self.spines['top'].register_axis(self.xaxis)

self.yaxis = maxis.YAxis(self)

self.spines['left'].register_axis(self.yaxis)

self.spines['right'].register_axis(self.yaxis)

self._update_transScale()

再次运行就不会出现警告提示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值