matplotlib 中的 Pandas 自动日期时间格式

j_b*_*ker 3 python plot datetime matplotlib pandas

我经常在一个图中绘制来自不同来源的多个时间序列数据,其中一些需要使用 matplotlib。当格式化 x 轴时,我使用 matplotlib 的autofmt_xdate(),但我更喜欢 pandas 的自动格式化。我知道我可以使用 手动设置格式set_major_formatter(),但我创建的绘图在总范围内从几年到几天不等,因此我需要根据每个绘图调整格式。有没有办法将 matplotlib 设置为使用类似于 pandas 的日期自动格式化 x 轴?

我还使用交互式绘图,当使用 pandas 时,df.plot()x 轴会在缩放到相应范围时更新,如下所示,我也想使用 matplotlib 来实现:

pandas 格式月份 熊猫格式日 pandas 格式日间

版本:

Python: 3.7.1
Pandas: 0.23.3
Matplotlib: 2.2.2
Run Code Online (Sandbox Code Playgroud)

所需格式:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

ix = pd.date_range('1/1/2017', '11/1/2018', freq='D')
vals = np.random.randn(len(ix))
df = pd.DataFrame({'Values': vals}, index=ix)

fig, ax = plt.subplots(1, 1, figsize=[8,6])
df.plot(ax=ax, lw=1)
plt.show()
Run Code Online (Sandbox Code Playgroud)

所需的 pandas 格式

当前格式:

fig, ax = plt.subplots(1, 1, figsize=[8,6])
ax.plot(df, lw=1)
fig.autofmt_xdate()
plt.show()
Run Code Online (Sandbox Code Playgroud)

当前的 matplotlib 格式

Imp*_*est 5

在第二行显示年份的一个选项是使用主要和次要刻度标签。

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

ix = pd.date_range('1/1/2017', '11/1/2018', freq='D')
vals = np.random.randn(len(ix))
s = pd.DataFrame({'Values': vals}, index=ix)

fig, ax = plt.subplots(figsize=[8,6])
ax.plot(s, lw=1)

ax.xaxis.set_major_locator(YearLocator())
ax.xaxis.set_major_formatter(DateFormatter("\n%Y"))

ax.xaxis.set_minor_locator(MonthLocator((1,4,7,10)))
ax.xaxis.set_minor_formatter(DateFormatter("%b"))

plt.show()
Run Code Online (Sandbox Code Playgroud)

如果您需要次要刻度用于其他用途,则以下内容将单独格式化主要刻度 - 具有相同的结果。在这里,您将使用 FuncFormatter 根据月份确定格式。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, DateFormatter
from matplotlib.ticker import FuncFormatter

ix = pd.date_range('1/1/2017', '11/1/2018', freq='D')
vals = np.random.randn(len(ix))
s = pd.DataFrame({'Values': vals}, index=ix)

fig, ax = plt.subplots(figsize=[8,6])
ax.plot(s, lw=1)

monthfmt = DateFormatter("%b")
yearfmt = DateFormatter("%Y")

def combinedfmt(x,pos):
    string = monthfmt(x)
    if string == "Jan":
        string += "\n" + yearfmt(x)
    return string

ax.xaxis.set_major_locator(MonthLocator((1,4,7,10)))
ax.xaxis.set_major_formatter(FuncFormatter(combinedfmt))

plt.show()
Run Code Online (Sandbox Code Playgroud)

两种情况的结果是相同的:

在此输入图像描述