Pandas 绘图在 x 轴上显示所有日期值(matplotlib 仅显示几个值),格式为 MM-YYYY [重复]

2024-01-07

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 轴上绘制每个月年的所有日期值。 我想以 (Feb-19) 格式显示 x 轴上对角格式的所有月份和年份。我可以将绘图的大小调大以适应所有情况,因为我会将其另存为 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日、2月17日…… (我想显示所有这些值,matplotlib 自动截断它,我想避免这种情况)


正如评论中提到的,您必须设置定位器和格式化程序。 matplotlib 文档对此进行了很好的解释一般图表 https://matplotlib.org/stable/api/ticker_api.html and 分别用于日期时间轴 https://matplotlib.org/stable/api/dates_api.html。另请参阅 的解释刻度定位器 https://matplotlib.org/3.1.1/gallery/ticks_and_spines/tick-locators.html。格式化代码源自Pythonstrftime() 和 strptime() 格式代码 https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes.

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()

Sample output:![enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pandas 绘图在 x 轴上显示所有日期值(matplotlib 仅显示几个值),格式为 MM-YYYY [重复] 的相关文章

随机推荐