matplotlib 刻度标签不生效

2 投票
2 回答
9179 浏览
提问于 2025-05-01 15:27

我有两组数据:

Y = [0.8, 0.9, 0.5, 0.4…0.6]
X = [16,17,18,19…..216]
plt.plot(Y)
plt.xticks(np.arange(min(X), max(X)+1, 10))

这组数据生成了:

在这里输入图片描述

我想把这些数据画出来,但因为X轴上有超过200个点,我想每隔10个点显示一次X轴的刻度。

但是现在X轴不是从16开始,而是从0开始,虽然第一个标签出现在16,但它对应的Y值并不正确。

我该如何绘制X轴,从16开始,每隔10个点显示一次,直到216,比如16、26、36、46……

谢谢!

暂无标签

2 个回答

1

其实你需要用两个数组来设置x轴的刻度标签,第一个数组是你想放置标签的位置,第二个数组就是这些标签的内容。

plt.xticks(np.arange(16, 216, step=10), np.arange(16, 216, step=10))
4

使用pyplot这个界面来做这些事情真的很麻烦,也让人困惑。我会直接和一个叫做 Axes 的对象互动:

import numpy as np
import matplotlib.ticker as mticker
import matplotlib.pyplot as plt
%matplotlib inline

fig, ax = plt.subplots(figsize=(8, 3))
xtickslocs = np.arange(16, 217, step=10)
#ax.plot(x_data, y_data, ...)
ax.xaxis.set_major_locator(mticker.FixedLocator(xtickslocs))
ax.set_xlim(left=-5, right=225) # change this to suite your needs

这样做会给我以下结果:

enter image description here

撰写回答