0

I am using the code below to plot a figure. As can be seen in the image, for some reason, the unneeded index labels on X-axis overlays the dates. How can they be removed?

enter image description here

using 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')

panda DF input:

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
Gil
  • 457
  • 1
  • 5
  • 16

2 Answers2

1

In genernal you cannot use matplotlib.dates tickers for pandas datetime plots. But you can make pandas plots that are compatible with matplotlib.dates via the x_compat=True argument.

df.plot(..., x_compat=True)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
0

Put your axis formatter code lines before your df.plot.

Dylan_w
  • 472
  • 5
  • 19