python - Matplotlib x 轴日期刻度频率

标签 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 年(或任何其他年数)出现一次?

最佳答案

检查这段代码:

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 索引的类型:为了使代码正常工作,dataframe 索引列必须是 datetime.date,所以我使用了 .dt.date 方法将 pandas._libs.tslibs.timestamps.Timestamp(因为我以这种方式构建数据框)转换为 datetime.date。这取决于您拥有的数据类型。
一些例子:

步数 = 2

enter image description here

步骤 = 4

enter image description here

步数 = 10

enter image description here

关于python - Matplotlib x 轴日期刻度频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62328174/

相关文章:

python - 使用 Python Matplotlib 使用起点、终点、中心和半径将圆弧绘制为多边形

python - 你如何显示当前运行的python模块的路径?

python - reshape 数据框以提取特定结果

python - 在 pandas 导入上过滤 pytables 表

用数字替换值

python - 如果满足条件,则根据另一个数据框中的匹配项更新数据框

python - 用 Python 3 制作账单

c++ - 在 Python 中制作 Qt/C++ 原型(prototype)

python - 如何像在 SQL 中一样使用 'in' 和 'not in' 过滤 Pandas 数据帧

Python:如何将 sklearn 函数与数据帧一起使用?