在 Matplotlib 中繪製 x 刻度線標記與刻度標記間的居中


若要在兩個刻度之間放置標記,我們可以採取以下步驟:

  • 載入一些樣本資料,r。
  • 建立陣列的副本,轉換為指定型別。
  • 使用 **subplots()** 方法建立一個 figure 和一組子圖。
  • 繪製日期和 r 樣本資料。
  • 使用 **set_major_locator()** 和 **set_minor_locator()** 方法設定主刻度和次刻度的定位器。
  • 使用 **set_major_locator()** 和 **set_minor_formatter()** 方法設定主格式化器和次格式化器的定位器。
  • 現在,將刻度標記放置在中心。
  • 若要顯示 figure,使用 **show()** 方法。

示例

import numpy as np
import matplotlib.cbook as cbook
import matplotlib.dates as dates
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
with cbook.get_sample_data('aapl.npz') as fh:
   r = np.load(fh)['price_data'].view(np.recarray)
r = r[-250:]
date = r.date.astype('O')
fig, ax = plt.subplots()
ax.plot(date, r.adj_close)
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=15))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))
for tick in ax.xaxis.get_minor_ticks():
   tick.tick1line.set_markersize(0)
   tick.tick2line.set_markersize(0)
   tick.label1.set_horizontalalignment('center')
imid = len(r) // 2
ax.set_xlabel(str(date[imid].year))
plt.show()

輸出

更新於:2021-05-15

800 瀏覽次數

開啟你的 職業

完成課程獲得認證

開始吧
廣告
© . All rights reserved.