Matplotlib x轴日期刻度频率

时间:2020-06-11 15:43:09

标签: python pandas dataframe datetime matplotlib

我有一个看起来像这样的简单数据框(年份是日期时间索引列):

Year         A          B
2018-01-01  1.049400    1.034076    
2017-01-01  1.056371    1.032066    
2016-01-01  1.063413    1.030055 

我使用以下图表绘制数据:

df['A'].plot()

df['B'].plot()

每5年获得带有日期刻度标签的图表。

enter image description here

如何使年份刻度每隔2年(或其他任何年份)出现一次?

1 个答案:

答案 0 :(得分:2)

检查此代码:

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

x = range(2000, 2018, 1)
year = [f'{str(y)}-01-01' for y in x]

df = pd.DataFrame({'Year': year,
                   'A': np.sin(x),
                   'B': np.cos(x)})

df['Year'] = pd.to_datetime(df['Year'], format = '%Y-%m-%d').dt.date
df.set_index('Year', inplace = True)

fig, ax = plt.subplots(1, 1, figsize = (6, 4))

df['A'].plot()
df['B'].plot()

step = 2
ax.xaxis.set_major_locator(md.YearLocator(step, month = 1, day = 1))
ax.xaxis.set_major_formatter(md.DateFormatter('%Y'))

plt.legend()
plt.show()

您可以使用md.YearLocator(),尤其是step值来管理刻度线的数量。我报告了此方法的documentation
请注意df索引的类型:为了使代码正常工作,数据帧索引列必须为datetime.date,因此我使用了.dt.date方法从{{1} }(因为我以这种方式构建了数据框)到pandas._libs.tslibs.timestamps.Timestamp。这取决于您拥有的数据类型。
一些例子:

步骤= 2

enter image description here

步骤= 4

enter image description here

步骤= 10

enter image description here

相关问题