Search code examples
pythonmatplotlibgridgridlines

Exclude grid lines from boundaries of plot in python?


I am looking for a way to remove grid lines from the axes of a plot, but unfortunately, I've not come up to a solution for this issue and neither found it anywhere else.

Is there a way to remove certain grid lines or choose which grid lines to plot without having to rely on the automatic function?

I've coded a quick example outputting a plot for illustration below and would be glad for any help.

import matplotlib.pyplot as plt
import numpy as np

def linear(x, a, b):
    return a*x+b

x = np.linspace(0, 1, 20)
y = linear(x, a=1, b=2)

fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 6))

ax.plot(x, y, color='darkred')
ax.set_xlim(0, 1)
ax.set_ylim(2, 3)
ax.grid(which='major', axis='y', linestyle='--', color='grey', linewidth=3)

plt.savefig("Testplot.pdf", format='pdf')


Solution

  • The major gridlines appear at positions of the major ticks. You can set any individual gridline invisible. E.g. to set the fifth gridline off,

    ax.yaxis.get_major_ticks()[5].gridline.set_visible(False)