繁体   English   中英

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

[英]How to get the desired labels on ticks on the x-axis in a matplotlib plot?

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.imgur.com/TY6gpKm.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.imgur.com/Nlc9srG.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.imgur.com/Z0AAvMn.jpg

我想要在第一张图中获得的结果 plot 但在第二张图中获得的 xticks 上的标签

如果我将@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 轴刻度上设置标签,不如设置所需的刻度。

由于正确的 plot 的“年”与“y”不兼容,我创建了另一个从“年”获得的数组,并且也与带有“y”的 plot 兼容。

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)

Plot 获得 - https://i.imgur.com/kkdMurH.jpg

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM