1

In this question, they answer how to correctly use grid with imshow with matplotlib. I am trying to do the same as they do, but I want to remove all ticks (x and y). When I try to do it, it also eliminates the grid and I just the image displayed without grid and ticks. My code is:

fig, ax = plt.subplots()
data = np.random.rand(20,20)
ax.imshow(data)
ax.set_xticks(np.arange(20))
ax.set_xticklabels(np.arange(20))
ax.set_xticks(np.arange(20)+0.5, minor=True)
ax.grid(which='minor',color='w',axis='x',linewidth=6)
ax.axes.xaxis.set_visible(False)
ax.axes.yaxis.set_visible(False)
plt.show()

Does anyone how to remove the ticks while keeping the grid (along the x axis in my case)?

Schach21
  • 412
  • 4
  • 21
  • I believe `grid` is associated with visibility of the axes. You may want to manually draw the vertical/horizontal lines or you can choose to remove the tick labels. – Quang Hoang May 04 '21 at 21:08

2 Answers2

2

Removing the axes (via set_visible(False)) will also remove the grid.

However, there's a workaround setting both spines and tick marks/labels to be invisible individually:

fig, ax = plt.subplots()
data = np.random.rand(20,20)
ax.imshow(data)
ax.set_xticks(np.arange(20))
ax.set_xticklabels(np.arange(20))
ax.set_xticks(np.arange(20)+0.5, minor=True)
ax.grid(which='minor',color='w',axis='x',linewidth=6)
# set axis spines (the box around the plot) to be invisible
plt.setp(ax.spines.values(), alpha = 0)
# set both tick marks and tick labels to size 0
ax.tick_params(which = 'both', size = 0, labelsize = 0)
plt.show()

Gives you output as:

enter image description here

Note, you might need to adjust xlim/ylim and grid parameters to fit your needs.

dm2
  • 4,053
  • 3
  • 17
  • 28
1

This is not perfect, but you can just set the tick label as an empty list.

ax.axes.get_xaxis().set_ticks([])
ax.axes.get_yaxis().set_ticks([])

enter image description here

Only the minor xticks, used in the grid, remain.

Mathieu
  • 5,410
  • 6
  • 28
  • 55