Adam Hunyadi
Adam Hunyadi

Reputation: 1952

Show or hide gridline on edges consistently

I would like to render a plot (created using subplots() withot edges on the top and on the right side like this:

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

This in fact disables the border edges, only to reveal, that on the top I can see a major gridline, and on the right side I do not: Example plot

I would be fine on having the gridlines on both sides or neither sides, but this is just sloppy. I also do not want to change the axis limits. Is it possible to make the shown gridlines consistent on the edges?

Upvotes: 4

Views: 620

Answers (1)

Stef
Stef

Reputation: 30579

Not sure if this is a bug or the intended behavior for some odd reason.
A workaround would be to switch off clipping for the last x gridline:

ax.xaxis.get_gridlines()[-1].set_clip_on(False)

Example:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(2)

def plotit(ax, clip, title):
    ax.plot()
    ax.grid(b=True, which='major', color='blue', linestyle=':')
    ax.set_xlim(0,1)
    ax.set_ylim(0,1)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    if(not clip):
        ax.xaxis.get_gridlines()[-1].set_clip_on(clip)
    ax.set_title(title)

plotit(axes[0], True, 'default (with clipping)')
plotit(axes[1], False, 'set_clip_on(False)')

enter image description here

Upvotes: 3

Related Questions