【问题标题】:Removing ticks when using grid with imshow matplotlib使用带有 imshow matplotlib 的网格时删除刻度
【发布时间】:2021-07-27 05:43:07
【问题描述】:

this 问题中,他们回答了如何正确使用带有imshow 和matplotlib 的网格。我正在尝试和他们做同样的事情,但我想删除所有刻度(x 和 y)。当我尝试这样做时,它也消除了网格,我只显示了没有网格和刻度的图像。我的代码是:

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

有没有人如何在保持网格的同时删除刻度(在我的例子中是沿着 x 轴)?

【问题讨论】:

  • 我相信grid 与轴的可见性有关。您可能想要手动绘制垂直/水平线,或者您可以选择删除刻度标签。

标签: python matplotlib imshow xticks


【解决方案1】:

移除轴(通过 set_visible(False))也会移除网格。

但是,有一种解决方法将脊椎和刻度线/标签分别设置为不可见:

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

给你输出:

注意,您可能需要调整 xlim/ylim 和网格参数以满足您的需要。

【讨论】:

    【解决方案2】:

    这并不完美,但您可以将刻度标签设置为空列表。

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

    仅保留网格中使用的次要 xticks。

    【讨论】:

      猜你喜欢
      • 2016-12-22
      • 2016-07-28
      • 2013-12-23
      • 2012-03-12
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      相关资源
      最近更新 更多