Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Matplotlib를 사용하여 X축의 특정 날짜에 대해 데이터를 그리는 방법은 무엇입니까?

<시간/>

matplotlib를 사용하여 X축의 특정 날짜에 대한 데이터를 플롯하려면 다음 단계를 수행할 수 있습니다. -

  • Figure 크기를 설정하고 서브플롯 사이와 주변의 패딩을 조정합니다.

  • 날짜 목록을 만들어 날짜/시간 형식으로 x로 변환합니다.

  • y 데이터 포인트의 목록을 만드십시오.

  • 주요 티커의 포맷터를 설정합니다.

  • 주요 티커의 로케이터를 설정합니다.

  • plot()을 사용하여 x 및 y 데이터 포인트를 플로팅합니다. 방법.

  • 그림을 표시하려면 show()를 사용하세요. 방법.

예시

from datetime import datetime
from matplotlib import pyplot as plt, dates as mdates

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

dates = ["01/02/2021", "01/03/2021", "01/04/2021", "01/05/2021", "01/06/2021", ]

x = [datetime.strptime(d, "%m/%d/%Y").date() for d in dates]
y = [1, 5, 3, 8, 4]

ax = plt.gca()
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.plot(x, y)

plt.show()

출력

Matplotlib를 사용하여 X축의 특정 날짜에 대해 데이터를 그리는 방법은 무엇입니까?