【问题标题】:Pandas plots don't align on specific date (month start vs month end)熊猫图在特定日期不对齐(月开始与月末)
【发布时间】:2018-07-19 04:26:57
【问题描述】:

我有一些我想要绘制的月度数据。但当然,每月对齐很重要:无论是月初(例如 01-01-2000)还是月底(例如 31-01-2000)。但是,在绘图时,我发现月份开始和月份结束之间没有区别。

例子:

import pandas as pd

input = [10., 12., 15., 13.,  9., 20., 17., 21., 23., 16., 15., 16.]
index1 = pd.date_range(start='2000-01-31', end='2000-12-31', freq='M')
df1 = pd.DataFrame(input, index=index1)
index2 = pd.date_range(start='2000-01-01', end='2000-12-01', freq='MS')
df2 = pd.DataFrame(input, index=index2)

ax = df1.plot()
df2.plot(ax=ax)

我得到这个输出:

虽然我希望这样:

这是一个错误,还是我犯了一个错误?

【问题讨论】:

    标签: python pandas plot


    【解决方案1】:

    您只需要使用 matplotlib 中的plot_date

    from matplotlib.dates import YearLocator, MonthLocator, DateFormatter
    years = YearLocator()   # every year
    months = MonthLocator()  # every month
    monthsFmt = DateFormatter('%b')
    

    然后

    fig, ax = plt.subplots()
    ax.plot_date(df1.index, df1[0], '-')
    ax.plot_date(df2.index, df2[0], '-')
    ax.xaxis.set_major_locator(months)
    ax.xaxis.set_major_formatter(monthsFmt)
    ax.xaxis.set_minor_locator(months)
    ax.autoscale_view()
    

    输出:

    【讨论】:

    • 好的,谢谢。 pandas.DataFrame.plot 似乎仍然应该正确地做到这一点。
    • @JHBonarius,你是对的。它应该”。 github: DatetimeIndex not formatted for plots 将帮助您理解为什么不这样做。同时,matplotlib 解决方案运行良好。
    猜你喜欢
    • 2021-12-06
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 2017-12-12
    • 1970-01-01
    • 2020-06-04
    相关资源
    最近更新 更多