Python matplotlib 随机漫步隐藏坐标轴 无数据 显示空白解决办法
近日学习《Python编程-从入门到实践》-【美】Eric Matthes 著
书中301页随机漫步项目,为避免我们注意的是坐标轴而不是随机漫步路径,需要隐藏坐标轴。
出现问题:
根据代码操作隐藏坐标轴,结果坐标不仅健在,还莫名重合,甚至数据点都没了一片空白。
书上隐藏坐标轴部分代码如下:
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
按书中代码运行结果:
以下是查询到的解决方法:
方法一:修改隐藏坐标代码
直接将隐藏坐标轴部分代码修改为:
plt.xticks([])
plt.yticks([])
完整代码如下:
import matplotlib.pyplot as plt
from random_walk import RandomWalk
# Keep making new walks, as long as the program is active.
while True:
# Make a random walk, and plot the points.
rw = RandomWalk(50000)
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues,edgecolors='none', s=1)
# Emphasize the first and last points.
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)
# # Remove the axes.n
plt.xticks([])
plt.yticks([])
plt.show()
keep_running = input("Make another walk? (y/n): ")
if keep_running == 'n':
break
成功解决
效果如图:
方法二:修改隐藏坐标轴代码+挪动代码位置
1.将隐藏坐标轴部分代码修改为:
current_axes = plt.axes()
current_axes.xaxis.set_visible(False)
current_axes.yaxis.set_visible(False)
2.并将代码挪动到 rw.fill_walk()后
修改代码和移动位置两个操作缺一不可。
完整代码如下:
import matplotlib.pyplot as plt
from random_walk import RandomWalk
# Keep making new walks, as long as the program is active.
while True:
# Make a random walk, and plot the points.
rw = RandomWalk(50000)
rw.fill_walk()
# Remove the axes.n
current_axes = plt.axes()
current_axes.xaxis.set_visible(False)
current_axes.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,edgecolors='none', s=1)
# Emphasize the first and last points.
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
成功解决
运行效果如图: