首页 > 解决方案 > 删除 x 轴覆盖不需要的索引标签

问题描述

我正在使用下面的代码来绘制一个图形。如图所示,由于某种原因,X 轴上不需要的索引标签覆盖了日期。如何将它们移除?

在此处输入图像描述

使用python2.7,matplotlib==2.2.4,pandas==0.23.1

def _create_image(x_labels, y_labels, title):

        df = pd.DataFrame({'date': x_labels, 'count': y_labels})
        df['date'] = pd.to_datetime(df['date'])
        df.set_index('date', inplace=True, drop=True)
        fig, ax = plt.subplots(figsize=(13, 5), sharex='all')

        df.plot(kind='line', ax=ax, marker='o', markerfacecolor='green', markersize=5, legend=False)

        ax.xaxis.set_major_locator(mdates.DayLocator(interval=3))
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%d %b'))

        plt.xlabel('Dates')
        plt.ylabel('Count')

        plt.title(title)
        plt.savefig('/tmp/tmp_pic.png')

熊猫DF输入:

date        count
2019-04-02  247640
2019-04-03  429405
2019-04-04  168808
2019-04-05  227930
2019-04-06   70628
2019-04-07  141943
2019-04-08  143102
2019-04-09  123590
2019-04-10  285473
2019-04-11  203974
2019-04-12   56283
2019-04-13   52168
2019-04-14   58632
2019-04-15  112912
2019-04-16   59196
2019-04-17   30239
2019-04-18  112585
2019-04-19   39416
2019-04-20   99569
2019-04-21   55780
2019-04-22   56596
2019-04-23   67868
2019-04-24   40587
2019-04-25   47498
2019-04-26   22111
2019-04-27   48653
2019-04-28   14990
2019-04-29   49540
2019-04-30   39691

标签: pythonpandasmatplotlib

解决方案


通常,您不能将matplotlib.dates代码用于 pandas 日期时间图。matplotlib.dates但是您可以通过参数制作兼容的熊猫图x_compat=True

df.plot(..., x_compat=True)

推荐阅读