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

标签 python pandas datetime matplotlib plot

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

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

pandas format month pandas format day pandas format inter-day

版本:

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

desired pandas format

当前格式:

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

Current matplotlib format

最佳答案

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

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

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

enter image description here

关于python - matplotlib 中的 Pandas 自动日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53490318/

相关文章:

mysql - 使用 sqlalchemy、mysql 和 pandas 读取框架

python - 使用轴显示相关矩阵

python - “DataFrame”对象没有属性 'col_name'

python - 如何在Python中读取url目录

python - Pandas 有条件地选择多列

mysql - MySql 中的多个 SELECT 语句,返回 date_sub()

r - 将日期时间数据与 ggplot scale_colour_gradient 一起使用

c# - 在 NodaTime 中处理不从午夜开始的日子

python - 尝试在某些 GIMP Python 插件代码上运行 Sphinx 时出错

python - 为什么在文本模式下编辑时不应该使用 os.linesep?