Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Căn giữa nhãn tick giữa các dấu tick trong Matplotlib

Đặt nhãn tick ở giữa hai tick marks bằng minor ticks và formatter.

  • Load dữ liệu mẫu aapl.npz.
  • Tạo figure, axes, plot date vs adj_close.
  • Major locator: MonthLocator(), Minor locator: MonthLocator(bymonthday=15).
  • Major formatter: NullFormatter(), Minor formatter: DateFormatter('%b').
  • Đặt tick1line, tick2line markersize=0, label horizontalalignment='center'.
  • xlabel = năm của điểm giữa.
  • show().

Ví dụ

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()

Kết quả

Biểu đồ giá cổ phiếu AAPL với nhãn tháng (Jan, Feb...) đặt ở giữa các khoảng tháng.