【问题标题】:Pandas auto datetime format in matplotlibmatplotlib 中的 Pandas 自动日期时间格式
【发布时间】:2019-04-28 15:23:50
【问题描述】:

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

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

版本:

Python: 3.7.1
Pandas: 0.23.3
Matplotlib: 2.2.2

所需格式:

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

当前格式:

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

【问题讨论】:

  • 无法重现,您的第一个代码 sn-p 给了我您的“所需”格式。
  • 是的,这是一个简单的例子,只是为了展示我想要使用 matplotlib 实现的格式,而不需要 df.plot()
  • MPL 确实需要一个 copy_formatter() 函数。当索引相等时应该很容易实现。你解决了吗?

标签: python pandas datetime matplotlib plot


【解决方案1】:

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

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

如果您需要将次要刻度用于其他内容,则以下内容将单独格式化主要刻度 - 具有相同的结果。在这里,您将使用 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()

两种情况下的结果都是一样的:

【讨论】:

  • 虽然这适用于完整范围为年的绘图,但当范围更改为一个月或一天时,它无法工作。我也经常使用交互式绘图,这种方法在放大时不会更新 x 轴。我已经更新了我的问题以更好地反映这一点。
  • 完全可以自己编写格式化程序。如果您有兴趣,可以通过this discussion 阅读有关新的通用格式化程序的信息。
猜你喜欢
  • 2017-12-10
  • 2020-10-30
  • 2020-02-02
  • 2014-05-30
  • 2021-11-04
  • 2020-12-07
  • 2018-03-13
  • 2019-05-14
  • 2017-10-13
相关资源
最近更新 更多