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()
再次运行就不会出现警告提示。