关于python:如何将xticks更改为特定范围

how to change the xticks to a specific range

本问题已经有最佳答案,请猛点这里访问。

我绘制了一个计数图,如下所示:

1
2
ax, fig = plt.subplots()
sns.countplot(user_id_count[:100])

(array([ 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]), )

enter image description here

但是我想将xticks更改为仅显示10, 20, 30, 40这4个数字,因此我检查了文档并将其重新编码如下:

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

enter image description here

但是xticks并不是我想要的。
我已经搜索了相关问题,但没有得到我想要的。
因此,如果不介意有人可以帮助我吗?


一种方法是在x轴上定义标签。 matplotlib模块中的set_xticklabels方法执行该作业(doc)。
通过定义自己的标签,可以通过将标签设置为''来隐藏它们。

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

这是一个例子:

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

enter image description here