簡體   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