python - 如何将 xticks 更改为特定范围

标签 python matplotlib seaborn

我画了一个计数图,如下:

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个数字,所以我检查了文档并重新编码如下:

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) 。 通过定义自己的标签,您可以通过将标签设置为等于''来隐藏它们。

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

这是一个例子:

# 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

关于python - 如何将 xticks 更改为特定范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56713197/

相关文章:

python - 显示渐近线的 pylab 图

python - Seaborn.despine() 消除将 y 轴移动到图右侧的效果

python - 打印频域图的最高峰值

python - 如何将手动自定义的 seaborn 图添加到 JointGrid/jointplot

python - 我可以在 matplotlib 中生成没有数据集而只有相关值(中位数、四分位数等)的箱线图吗?

python - Selenium 中的定位器和 Webelement 有什么区别?

python - 保存时的 Matplotlib 图 facecolor alpha(背景色、透明度)

python - 更改模块 __version__ 并在之后保存具有更新版本的模块源文件

python - Pandas 删除超出时间范围的行

python - 我如何让 matplotlib 自动更改线标记?