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

X축이 Pandas의 날짜/시간 인덱스인 경우 다중 색상 선을 그리는 방법은 무엇입니까?

<시간/>

X축이 Pandas의 날짜/시간 인덱스인 경우 여러 색상의 선을 그리려면 다음 단계를 수행할 수 있습니다. -

  • 그림 크기를 설정하고 서브플롯 사이 및 주변 여백을 조정합니다.
  • numpy를 사용하여 d, y 및 s 데이터 포인트를 생성합니다.
  • 그림과 서브플롯 세트를 생성합니다.
  • numpy를 사용하여 xval, p 및 s 데이터 포인트를 가져옵니다.
  • 핫 컬러맵과 s 데이터 포인트가 있는 라인 컬렉션 인스턴스를 가져옵니다.
  • 주축 및 부축 로케이터를 설정하고 축 포맷터를 설정합니다.
  • 데이터 제한을 사용하여 보기 제한을 자동으로 조정합니다.
  • 그림을 표시하려면 show()를 사용하세요. 방법.

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

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

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

fig, ax = plt.subplots()

xval = mdates.date2num(s.index.to_pydatetime())
p = np.array([xval, s.values]).T.reshape(-1, 1, 2)
s = np.concatenate([p[:-1], p[1:]], axis=1)
lc = c.LineCollection(s, cmap="hot")
lc.set_array(xval)

ax.add_collection(lc)
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.DayLocator())
m = mdates.DateFormatter("%b")
ax.xaxis.set_major_formatter(m)
ax.autoscale_view()

plt.show()

출력

다음 출력을 생성합니다.

X축이 Pandas의 날짜/시간 인덱스인 경우 다중 색상 선을 그리는 방법은 무엇입니까? X축이 Pandas의 날짜/시간 인덱스인 경우 다중 색상 선을 그리는 방법은 무엇입니까?