Python 如何将XTICK更改为特定范围

Python 如何将XTICK更改为特定范围,python,matplotlib,seaborn,Python,Matplotlib,Seaborn,我画了一个计数图如下: ax, fig = plt.subplots() sns.countplot(user_id_count[:100]) ax, fig = plt.subplots() sns.countplot(user_id_count[:100]) plt.xticks(range(10, 41, 10)) (数组([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 2

我画了一个计数图如下:

ax, fig = plt.subplots()
sns.countplot(user_id_count[:100])
ax, fig = plt.subplots()
sns.countplot(user_id_count[:100])
plt.xticks(range(10, 41, 10))
(数组([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,35,36,37,38,39,40),

但我想将xticks更改为仅显示这4个数字,因此我检查了文档并按如下方式重新编码:

ax, fig = plt.subplots()
sns.countplot(user_id_count[:100])
ax, fig = plt.subplots()
sns.countplot(user_id_count[:100])
plt.xticks(range(10, 41, 10))

但是xticks不是我想要的。
我已经搜索了相关问题,但没有得到我想要的确切答案。

如果不介意的话,有人能帮我吗?

一种方法是定义x轴上的标签。来自
matplotlib
模块的
setxticklabels
方法执行此任务。 通过定义自己的标签,可以通过将标签设置为
'
来隐藏它们

通过定义自己的标签,您需要注意它们仍然与您的数据保持一致

以下是一个例子:

# import modules
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

#Init seaborn
sns.set()

# Your data to count
y = np.random.randint(0,41,1000)

# Create the new x-axis labels 
x_labels = ['' if i%10 != 0 else str(i) for i in range(len(np.unique(y)))]
print(x_labels)
# ['0', '', '', '', '', '', '', '', '', '', 
# '10', '', '', '', '', '', '', '', '', '', 
# '20', '', '', '', '', '', '', '', '', '', 
# '30', '', '', '', '', '', '', '', '', '', '40']

# Create plot
fig, ax = plt.subplots()
sns.countplot(y)

# Set the new x axis labels
ax.set_xticklabels(x_labels)
# Show graph
plt.show()

那么
plt.xticks(范围(9,40,10),范围(10,41,10))呢
?第一个范围是记号的x值,第二个范围是记号的标签。@Heike你是对的,这是有效的。但如果将范围设置在数据之外,则它将成为绘图中空白的一部分。