matplotlib中的 pandas 自动日期时间格式 [英] Pandas auto datetime format in matplotlib

查看:93
本文介绍了matplotlib中的 pandas 自动日期时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I frequently plot multiple timeseries data from different sources on a single plot, some of which require using matplotlib. When formatting the x-axis, I use matplotlib's autofmt_xdate(), but I much prefer the auto formatting of pandas. I'm aware I can manually set the format using set_major_formatter(), but the plots I create vary from years, to days in total range, so I would need to adjust the formatting based on each plot. Is there a way to set matplotlib to auto format the x-axis with dates similar to pandas?

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

I also use interactive plotting, and when using pandas df.plot() the x-axis updates when zooming to the respective ranges as shown below, which I would also like to achieve using 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()

推荐答案

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

An option to show the years in a second row is to use the major and minor ticklabels.

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确定取决于月份的格式.

If you need the minor ticks for something else, the following would format the major ticks alone - with the same result. Here you would use a FuncFormatter to determine the format depending on the month.

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

两种情况下的结果都相同:

The result is in both cases the same:

这篇关于matplotlib中的 pandas 自动日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆