如何在 matplotlib 图中的 x 轴上的刻度上获得所需的标签?


x = array([0], [1], [2], [3] ...[175])
y = array([333], [336], [327], ...[351])

两者都有形状 (175,1(

fig, ax = plt.subplots()
fig.set_size_inches(5.5, 5.5)
plt.plot(x, y, color='blue')

我得到这个结果 https://i.stack.imgur.com/pbQ9n.jpg

但是我想在我的 x 轴刻度上单独标记,取自这个数组

year = array([1974], [1974], [1974], ....[1987])

它也有形状(175,1(,但有很多重复值

fig, ax = plt.subplots()
fig.set_size_inches(5.5, 5.5)
plt.plot(year, y, color='blue')

提供 https://i.stack.imgur.com/T8IPb.jpg

fig, ax = plt.subplots()
fig.set_size_inches(5.5, 5.5)
plt.plot(x, y, color='blue')
ax.set_xticklabels(year)

提供 https://i.stack.imgur.com/nvrw8.jpg

我想要在第一个图中获得的结果图,但在第二个图中获得的 xtick 上的标签

如果我将@ImportanceOfBeingErnest和@Jody Klymak 的评论中的建议结合起来,您可以:

  • 将 x 值更改为有意义的值,而不仅仅是索引(计数器值(,即以年表示的时间(浮点值(。
  • 然后,您可以使用set_xticks来指定要查看的刻度标签

例如:

# mimic your data a little bit
x = np.arange(0, 175)
y = 330.0 + 5.0 * np.sin(2 * np.pi * x / 13.0) + x / 10.0
# change the x values in something meaningful
x_in_years = 1974.5 + x / 13.0
fig, ax = plt.subplots()
fig.set_size_inches(5.5, 5.5)
plt.plot(x_in_years, y, color='blue')
# select the ticks you want to display    
ax.set_xticks([1975, 1980, 1985, 1990])
# or
# ax.set_xticks([1974, 1978, 1982, 1986])

感谢@ImportanceOfBeingErnest、@Jody Klymak和@Jan Kuiken的投入。

因此,与其在 x 轴刻度上设置标签,不如设置所需的刻度。

由于"year"与"y">

不兼容正确的绘图,因此我创建了另一个从"year"获得的数组,并且也与带有"y"的绘图兼容。

start = year.min().astype(float)
end = year.max().astype(float)
step = (year.max() - year.min())/len(year)
x = np.arange(start, end, step)
fig, ax = plt.subplots()
fig.set_size_inches(5.5, 5.5)
plt.plot(x, y, color='blue')
ax.xaxis.set_ticks([1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987])
plt.grid(color='y', linestyle='-', linewidth=0.5)

获得的情节 - https://i.stack.imgur.com/CtlEh.jpg

最新更新