h10g
h10g

Reputation: 516

How can I remove certain grid line but keep this tick in matplotlib

My matplotlib code is like this:

if __name__ == '__main__':
    import matplotlib.pyplot as plt
    from matplotlib.pyplot import MultipleLocator

    x = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]
    y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    f, ax = plt.subplots(figsize=(10, 7), dpi=200)
    ax.xaxis.set_major_locator(MultipleLocator(50))

    plt.plot(x, y, 'o-', color="r", lw=4, ms=10)
    plt.grid()
    plt.savefig("question.png")

The figure it draws is like this enter image description here

How can I remove the grid line in the 50 of the x axis, but keep the 50 tick in the graph?

Upvotes: 1

Views: 284

Answers (1)

U13-Forward
U13-Forward

Reputation: 71570

Try using plt.axvline:

if __name__ == '__main__':
    import matplotlib.pyplot as plt
    from matplotlib.pyplot import MultipleLocator

    x = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]
    y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    f, ax = plt.subplots(figsize=(10, 7), dpi=200)
    ax.xaxis.set_major_locator(MultipleLocator(50))

    plt.plot(x, y, 'o-', color="r", lw=4, ms=10)
    for loc in plt.xticks()[0]:
        if loc != 50:
            plt.axvline(x=loc, color = 'grey', linestyle = '-', linewidth = 0.4)
    plt.show()

Output:

enter image description here

Upvotes: 1

Related Questions