在pandas / matplotlib

时间:2017-04-30 02:57:15

标签: python datetime numpy matplotlib

我想显示每个月的缩写,以及一年中的年份。

我很亲密。我目前面临的问题是年份不正确。我已经发现这是numpy.datetime64(日期时间索引采用这种格式)和使用1970年代的python datetime之间的问题。图表上显示的两年应该是2017年和2018年,但它们显示48和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()

如何在这里展示合适的年份?

enter image description here

2 个答案:

答案 0 :(得分:1)

经过一些游戏之后,如果你指定了轴然后在它上面绘图(而不是调用pandas plot函数),它似乎有效。

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)

fig, ax = plt.subplots(1)
ax.plot(df)

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)

fig.show()

另请注意,我将%y 更改为%Y ,因此格式为2017/2018而不是17/18。 enter image description here

答案 1 :(得分:1)

Matplotlib从零开始计算年数,但自1970年以来就是UNIX。因此,您需要48年,49年等等。为了避免matplotlib的这种行为,您必须从您的pandas datetime index date部分获取,然后使用%Y描述符获得主要奖项的完整年份:

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

enter image description here