Search code examples
pythonmatplotlibdata-visualizationrandom-walk

I can't turn off the axes of my plot in matplotlib


I am writing code for a random walk model, and I use plt.axes().get_xaxis().set_visible(False) to hide the axes but when I run the program the plot still shows both axes. Here is what I wrote:

import matplotlib.pyplot as plt 
from random_walk import RandomWalk

# Keep making random walks, as long as the program is active
while True:
    rw = RandomWalk()
    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=10)

    # Emphasize the first and last points.
    plt.scatter(0, 0, c='green', edgecolors='none', s=50)
    plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', s=50)

    # Remove the axes.
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)    

    plt.show()

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

Solution

  • You may use plt.gca().get_xaxis().set_visible(False) instead of plt.axes().get_xaxis().set_visible(False).

    Here is a code example:

    import matplotlib.pyplot as plt
    import numpy as np
    
    plt.plot(np.random.random(1000))
    plt.gca().get_xaxis().set_visible(False)
    

    This short code will return:

    enter image description here