gpt4 book ai didi

python - 在 pandas/matplotlib 中格式化时间序列 x 轴

转载 作者:行者123 更新时间:2023-12-01 03:02:10 24 4
gpt4 key购买 nike

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

我已经很接近了。我目前遇到的问题是年份不正确。我发现这是 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

最佳答案

Matplotlib 从 0 开始计算年份,但 UNIX 是从 1970 年开始计算的。因此,您得到的年份是 48、49 等。为了避免 matplotlib 的这种行为,您必须从 pandas 日期时间索引日期部分获取,然后使用 %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

关于python - 在 pandas/matplotlib 中格式化时间序列 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43702486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com