[Python] Remove axis ticks but keep grid using Matplotlib / ggplot style

Discussão em 'Python' iniciado por Stack, Junho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I know that this is a "duplicate" question (Remove the x-axis ticks while keeping the grids (matplotlib)) but the answers that I found didn't solve my problem.

    For example, I have this code:

    %matplotlib inline

    from matplotlib import pyplot as plt
    from matplotlib.lines import Line2D

    import bumpy

    data = numpy.random.randint(0, 100, size=(100,100))

    plt.style.use('ggplot')
    plt.figure(figsize=(10,10))
    plt.imshow(data)

    plt.savefig('myplot.pdf', format='pdf', bbox_inches='tight')
    plt.close()


    Which produces this plot:

    [​IMG]

    However, I want to end up with a plot without any ticks, just the grid. Then, I tried this:

    plt.figure(figsize=(10,10))
    plt.imshow(data)
    plt.grid(True)
    plt.xticks([])
    plt.yticks([])


    Which removes all ticks and grids:

    [​IMG]

    At last, if try this:

    plt.figure(figsize=(10,10))
    plt.imshow(data)
    ax = plt.gca()
    ax.grid(True)
    ax.set_xticklabels([])
    ax.set_yticklabels([])


    I get closer but my .pdf still have some ticks outside the plot. How do I get rid of them, keeping the internal grid?

    [​IMG]

    Continue reading...

Compartilhe esta Página