Felix
Felix

Reputation: 83

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

Upvotes: 2

Views: 948

Answers (2)

Mathieu
Mathieu

Reputation: 5746

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!

Upvotes: 0

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339120

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)

Upvotes: 2

Related Questions