python - 如何调整字符串x轴的 'tick frequency'

标签 python matplotlib

我有一个 list 要画。有没有办法显示部分 x 轴标签,例如 x[0], x[10], ...,但保持图形不变?

x = ['alice', 'bob', ...] # string list, len > 100
y = [23, 323, ...] # int list
plt.plot(x, y)
plt.show()

After rotate 90 degree

编辑 1:还有一些其他问题,例如 Changing the "tick frequency" on x or y axis in matplotlib?处理 int 标签。但对我不起作用。

编辑 2:旋转 x 轴标签无济于事。

最佳答案

执行此操作的一种方法是减少 x 轴上的刻度数。您可以使用 ax.set_xticks() 设置刻度。在这里,您可以使用切片符号 [::2]x 列表进行切片,以在每个第 2 个条目处设置一个刻度。然后使用 ax.set_xticklabels() 设置 x 刻度标签,在设置刻度时使用相同的切片。

例如:

x = ["Ant", "Bob", "Crab", "Donkey", "Elephant", "Fire", "Giant","Hello",
     "Igloo", "Jump", "Kellogg","Llama", "More", "Night"]
y = np.random.randint(0,10,14)

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(9,5))
ax1.plot(x,y)
ax1.set_title("Crowded x axis")

ax2.plot(x,y)
ax2.set_xticks(x[::2])
ax2.set_xticklabels(x[::2], rotation=45)
ax2.set_title("Every 2nd ticks on x axis")

plt.show()

enter image description here

关于python - 如何调整字符串x轴的 'tick frequency',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50128668/

相关文章:

python - 重命名组名标题 pandas

python - PyQt5 中的信号和槽

python - Pandas :如何用平均值填充缺失数据?

python - 根据 bins 组合字典键

python - 在类方法Python中调用多处理

python - 引发 LinAlgError ("SVD did not converge") LinAlgError : SVD did not converge in matplotlib pca determination

python - python中函数的自适应绘图

python - matplotlib 保存每 n 个步骤的动画

python - Matplotlib:绘制数据然后进行时间序列预测

python - matplotlib 在不重新采样的情况下绘制小图像