In matplotlib how to hide a single tick grid line, but keep displaying this tick label?
Oct 13, 3:33pm
Gridlines are separate Line2D objects, so you can hide individual ones after they've been created:
python
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0, 1, 2, 3, 4], [0, 1, 0, 1, 0])
ax.grid(True)
# Force a draw so gridlines are positioned on the current ticks
fig.canvas.draw()
hide_at = 3 # x value whose gridline you want to hide
for tick_pos, gridline in zip(ax.get_xticks(), ax.xaxis.get_gridlines()):
if tick_pos == hide_at:
gridline.set_visible(False)
plt.show()
Key points:
ax.xaxis.get_gridlines() returns one gridline per tick position, so you match it against ax.get_xticks(). Use ax.yaxis / ax.get_yticks() for the y axis.
fig.canvas.draw() first is important: gridlines are created/positioned at draw time, so ticks must be final before you hide anything. If you later change limits or ticks, re-hide.
The tick label and the tick mark are independent of the gridline, so they stay visible.
If you want to hide the gridline and keep everything else, set_visible(False) is enough. If you instead want to alter only the label later, that's per-Tick via ax.xaxis.get_major_ticks() (e.g. tick.label1.set_visible(...)).
Oct 13, 3:33pm
This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.