2

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')

Felix
  • 83
  • 9
  • 1
    I guess there must be a clever way to remove the gridlines for the boundaries `2.0` and `3.0`. However, I don't think there is one to remove a specific line in particular. Would you be interested in an implementation with horizontal lines and axes tick positioning? – Mathieu Oct 15 '19 at 11:57
  • Yes, that sounds like a good approach to me. For ticks I use `xaxis.set_tick_params`, `set_xticks` and `set_xticklabels`, but I am unaware of how to achieve the desired output for grid lines. – Felix Oct 15 '19 at 12:01
  • See my proposition. Note that you can define the horizontal line to be plotted on part of the plot, e.g. between `x1` and `x2`. – Mathieu Oct 15 '19 at 12:12

2 Answers2

2

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)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
0

Here is a proposition with ticks and horizontal lines. The idea is to specify the ticks (not really necessary, but why not), and then to draw horizontal dashes lines where you want your grid.

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)

yticks = np.arange(2, 3, 0.2)
grid_lines = np.arange(2.2, 3, 0.2)

ax.set_yticks(yticks)

for grid in grid_lines:
    ax.axhline(grid, linestyle='--', color='grey', linewidth=3)

Output:

Output plot

Why did I include the yticks? Well you could design a function which takes in input the yticks and return the position of the grid lines accordingly. I think it could be handy depending on your needs. Good luck!

Mathieu
  • 5,410
  • 6
  • 28
  • 55