如何在python中隐藏刻度标签但保持刻度不变?

2022-01-25 00:00:00 python matplotlib axis labels

问题描述

我想在我创建的图上隐藏我的刻度标签,但保留这个刻度本身(轴上的小标记).例如,当我尝试使用 .

I want to hide my ticks label on a plot I created, but keep this tick itself (the little marks on the axis). When I try to use what I've found here, for example, the entire tick is removed, and not just the labels. How can I remove only the labels then?

解决方案

Set the tick labels not to be an empty array, but to be a list of empty strings. In the example below, I've replaced the xtick labels with empty strings, leaving the y axis untouched. From here you can selectively keep certain labels if you wished.

import pylab as plt

fig, ax = plt.subplots()
ax.plot([1,2,3],[4,5,6])

labels = [item.get_text() for item in ax.get_xticklabels()]

empty_string_labels = ['']*len(labels)
ax.set_xticklabels(empty_string_labels)

plt.show()

This code is adapted from a previous answer.

相关文章