在pandas/matplotlib中格式化时间序列x轴 [英] formatting timeseries x-axis in pandas/matplotlib

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

问题描述

我想显示每个月的缩写以及年份的年份.

I would like to show each month abbreviation, as well as the year on the year.

我很近.我目前遇到的问题是年份不正确.我已经发现这是numpy.datetime64(datetime索引采用这种格式)和python datetime(在1970年时代)之间存在的问题.图表上显示的两年应该是2017年和2018年,但它们显示的是48年和49年.

I am quite close. The issue I am currently having is that the years are incorrect. I have figured out that this is a issue between numpy.datetime64 (the datetime index is in this format), and python datetime which is used the 1970 epoch. The two years shown on the chart should be 2017 and 2018 but they show 48 and 49.

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

from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter, YearLocator

indx = pd.date_range('2017-04-01', '2019-01-01')
s = pd.Series(np.random.randn(len(indx)), index=indx)

df = pd.DataFrame(s)

ax = df.plot()
months = MonthLocator(range(1, 13), bymonthday=1, interval=1)
monthsFmt = DateFormatter("%b")
years = YearLocator(1, month=4, day=1)
yrsFmt = DateFormatter("\n %y")

ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yrsFmt)


ax.xaxis.set_minor_locator(months)
ax.xaxis.set_minor_formatter(monthsFmt)

plt.show()

如何在此处显示正确的年份?

How do I show the right years here?

推荐答案

Matplotlib从1970开始就是零,但是从1970年开始是UNIX.因此,您有48、49等年份.要避免matplotlib的这种行为,您必须从您的熊猫datetime索引日期部分,然后使用%Y描述符获取主要刻度的完整年份:

Matplotlib counts years from zero but UNIX since 1970. Therefore you got years of 48, 49 and etc. To avoid this behavior of matplotlib you have to get from your pandas datetime index date part and then use %Y descriptor to get full years for major ticks:

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

indx = pd.date_range('2017-04-01', '2019-01-01')
s = pd.Series(np.random.randn(len(indx)), index=indx.date) # get dates
df = pd.DataFrame(s)

months = MonthLocator() # MonthLocator without args set ticks for every month
monthsFmt = DateFormatter("%b")
years = YearLocator(month=4, day=1)
yrsFmt = DateFormatter("\n%Y") # correct year descriptor

ax = df.plot()
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_minor_formatter(monthsFmt)
for tick in ax.xaxis.get_minor_ticks():tick.label.set_fontsize(9) 
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yrsFmt)

plt.show()

这篇关于在pandas/matplotlib中格式化时间序列x轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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