Python matplotlib 随机漫步隐藏坐标轴 无数据 显示空白解决办法

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

成功解决
运行效果如图:
在这里插入图片描述

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_binbo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值