Pandas Plotting MMM-YYYY [duplicate] 형식의 x 축에 모든 날짜 값 표시 (matplolib는 소수의 값만 표시)

Dec 17 2020
import os
import pandas as pd
import matplotlib.pyplot as plt
import datetime

df = pd.read_excel(DATA_DIR+"/"+file_list[0], index_col="Date")
df.head(5)

smooth = df['Pur. Rate'].rolling(window=20).mean()
smooth.plot()

다음 그래프를 얻고 x 축에 모든 MONTH-YEAR의 모든 날짜 값을 플로팅해야합니다. X 축에 대각선으로 서식이 지정된 모든 월과 연도를 형식 (Feb-19)으로 표시하고 싶습니다. jpg로 저장하므로 플롯의 크기를 모두에 맞게 크게 만들 수 있습니다.

x 축에 1 월 16 일, 2 월 16 일, 3 월 16 일, 4 월 16 일, 5 월 16 일, 6 월 16 일, 7 월 16 일, 8 월 16 일, 9 월 16 일, 10 월 16 일, 11 월 16 일, 12 월 16 일, 1 월 17 일 값을 원합니다. , Feb 17… (이 모든 값을 표시하고 싶습니다. matplotlib는 자동으로 이것을 자릅니다. 피하고 ​​싶습니다.)

답변

1 Mr.T Dec 17 2020 at 22:48

주석에서 언급했듯이 로케이터와 포맷터를 모두 설정해야합니다. 이를 위해하기 matplotlib 문서에 잘 설명되어 일반 그래프 와 별도로 날짜 축의 . TickLocators에 대한 설명도 참조하십시오 . 형식화 코드는 Python의 strftime () 및 strptime () 형식 코드 에서 파생됩니다 .

from matplotlib import pyplot as plt
import pandas as pd
from matplotlib.dates import MonthLocator, DateFormatter


#fake data
import numpy as np
np.random.seed(123)
n = 100
df = pd.DataFrame({"Dates": pd.date_range("20180101", periods=n, freq="10d"), "A": np.random.randint(0, 100, size=n), "B": np.random.randint(0, 100, size=n),})
df.set_index("Dates", inplace=True)
print(df)

ax = df.plot()

#defines the tick location 
ax.xaxis.set_major_locator(MonthLocator())
#defines the label format
ax.xaxis.set_major_formatter(DateFormatter("%b-%y"))
ax.tick_params(axis="x", labelrotation= 90)

plt.tight_layout()
plt.show()

샘플 출력 :

Boul Dec 17 2020 at 20:47

팬더 함수만으로 stftime () 을 사용 하여 날짜 스키마 인덱스 '% Y- % m- % d'를 새 형식 '% b- % Y'및 plot의 일부 매개 변수로 대체 할 수 있습니다 .

smoothdf.plot(xticks=smoothdf.index.strftime('%m-%Y').unique()).set_xticklabels(smoothdf.index.strftime('%b-%Y').unique())

xticks 를 사용하여 절대 보고 싶은 레이블을 지정합니다.

set_xticklabels 를 사용하여 레이블 목록을 수정합니다.

LucaAngioloni Dec 17 2020 at 20:14

pandas 플롯이 아닌 matplotlib를 사용하고 다음과 같이 지정한 형식으로 날짜를 플롯하는 것이 좋습니다.

import matplotlib.dates as mdates

from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

myFmt = mdates.DateFormatter('%b-%Y') # date formatter for matplotlib
                                      # %b is Month abbreviated name, %Y is the Year

# ... after some code

fig, ax = plt.subplots(figsize=(15,8))

ax.xaxis.set_major_formatter(myFmt)
fig.autofmt_xdate()

# Plot data ...

ax.set_xticks("""... define how often to show the date""")

다음과 같이 데이터 프레임에서 데이터를 가져올 수 있습니다. .to_numpy()또는 .values().

기능에 대해서는 이 문서 를 참조하십시오 set_xticks.