python - 如何将 xticks 更改为特定范围
问题描述
我画了一个计数图如下:
ax, fig = plt.subplots()
sns.countplot(user_id_count[:100])
(数组([ 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 更改为只显示10, 20, 30, 40
这 4 个数字,所以我检查了文档并将其重新编码如下:
ax, fig = plt.subplots()
sns.countplot(user_id_count[:100])
plt.xticks(range(10, 41, 10))
但 xticks 不是我想要的。
我已经搜索了相关问题,但我没有得到我想要的东西。
所以如果不介意有人可以帮助我吗?
解决方案
一种方法是在 x 轴上定义标签。模块中的set_xticklabels
方法matplotlib
完成工作(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()
推荐阅读
- javascript - 反应:无法将 useState 设置为对象数组。控制台日志显示未定义
- c - 结构的 int 字段在同一结构的 int* 上的 malloc() 之后被修改
- c++ - C ++:对构造函数的未定义引用
- python - 参数化熊猫组
- wso2 - WSO2 Micro Integrator 7.1 中的仪表板
- python - Julia中的“数组[]中的1”是什么意思?
- reactjs - InertiaJS 表单响应以模态打开,带有快速缓存控制消息
- bash - 循环遍历一个扩展文件并将每一列用作输入
- python - 如何使用自定义损失函数处理批量大小错误?
- javascript - 关于 ES6 类的语法问题(构造函数/超级)