연도 눈금이 12개월마다 표시되도록 matplotlib 날짜 조작을 수행하려면 다음 단계를 수행할 수 있습니다. -
- 그림 크기를 설정하고 서브플롯 사이 및 주변 여백을 조정합니다.
- d, y, s, 년, 월, 월Fmt 생성 및 yearsFmt Pandas, Numpy 및 matplotlib 날짜 사용
- DateFormatter에서 "%B"를 사용하여 전체 월 이름을 표시합니다.
- DateFormatter에서 "%Y"를 사용하여 연도를 표시합니다.
- 새 그림을 만들거나 기존 그림을 활성화합니다.
- 하위 플롯 배열의 일부로 그림에 '도끼'를 추가합니다.
- plot()을 사용하여 "dts" 및 "s" 데이터 포인트를 플롯합니다. 방법.
- 단축 또는 장축 로케이터 및 포맷터를 설정합니다. minor_locator 설정 개월로 연도 눈금이 12개월마다 표시되도록 합니다.
- 그림을 표시하려면 show()를 사용하세요. 방법.
예시
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() 출력
다음 출력을 생성합니다.
