Reputation: 694
I would like to show the topmost minor gridline (at 2.25) in its full width without adjusting the limits manually. How can I achieve this?
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots(constrained_layout=True)
ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
ax.grid(linewidth=5, axis='y', which='both')
ax.set_ylim(0, 2.25)
plt.show()
Upvotes: 0
Views: 296
Reputation: 740
There are a couple ways to accomplish what you're looking for. I think the best method would be to hide the top and right spines. Alternatively, ax.grid takes Line2D args which includes clip_on. Setting clip_on=False has the intended effect of making the ax box not clip the line - but it does result in the top spine going through the grid line (which is not very attractive in my opinion). Lastly, as you mention, you could make a minor increase in y lim (to 2.26 or 2.27) and that would also make the top grid line more visible.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15,12))
axes = axes.flatten()
ax = axes[0]
ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
ax.grid(linewidth=5, axis='y', which='both', clip_on=False)
[ax.spines[s].set_visible(False) for s in ['top', 'right']]
ax.set_ylim(0, 2.25)
ax.set_title('Hide top/right spines', fontsize=16, fontweight='bold')
ax = axes[1]
ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
ax.grid(linewidth=5, axis='y', which='both', zorder=3, clip_on=False)
ax.set_ylim(0, 2.25)
ax.set_title('Make clip_on=False', fontsize=16, fontweight='bold')
ax = axes[2]
ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
ax.grid(linewidth=5, axis='y', which='both')
ax.set_ylim(0, 2.265)
ax.set_title('Increase ylim to 2.265', fontsize=16, fontweight='bold')
axes[3].axis('off')
Upvotes: 2