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

Matplotlib – Thao tác ngày để hiển thị tick năm mỗi 12 tháng

Để tick năm hiển thị mỗi 12 tháng trong matplotlib, thực hiện:

  • Thiết lập kích thước hình và padding.
  • Tạo d, y, s, years, months, monthsFmt, yearsFmt bằng Pandas, NumPy, matplotlib dates.
  • Dùng %B trong DateFormatter hiển thị tên tháng đầy đủ.
  • Dùng %Y trong DateFormatter hiển thị năm.
  • Tạo figure mới hoặc kích hoạt figure.
  • Thêm 'ax' vào figure.
  • Vẽ "dts" và "s" bằng plot().
  • Đặt minor/major locator và formatter. Đặt minor_locator là months để tick năm hiện mỗi 12 tháng.
  • Hiển thị bằng show().

Ví dụ

import numpy as np
from matplotlib import pyplot as plt, dates as mdates
import pandas as pd

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

d = pd.date_range("2020-01-01", "2021-06-01", freq="7D")
y = np.cumsum(np.random.normal(size=len(d)))
s = pd.Series(y, index=d)

years = mdates.YearLocator()
months = mdates.MonthLocator()
monthsFmt = mdates.DateFormatter('%B')
yearsFmt = mdates.DateFormatter('\n%Y')

dts = s.index.to_pydatetime()

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(dts, s)

ax.xaxis.set_minor_locator(months)
ax.xaxis.set_minor_formatter(monthsFmt)
plt.setp(ax.xaxis.get_minorticklabels(), rotation=90)

ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)

plt.show()

Đầu ra

Sẽ tạo ra đầu ra:

Matplotlib – Thao tác ngày để hiển thị tick năm mỗi 12 tháng
Matplotlib – Thao tác ngày để hiển thị tick năm mỗi 12 tháng