Matplotlib DateFormatter for axis label not working

前端 未结 2 986
执笔经年
执笔经年 2020-11-29 05:09

I\'m trying to adjust the formatting of the date tick labels of the x-axis so that it only shows the Year and Month values. From what I\'ve found online, I have to use

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 06:05

    pandas just doesn't work well with custom date-time formats.

    You need to just use raw matplotlib in cases like this.

    import numpy
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    import pandas
    
    N = 20
    numpy.random.seed(N)
    
    dates = pandas.date_range('1/1/2014', periods=N, freq='m')
    df = pandas.DataFrame(
        data=numpy.random.randn(N), 
        index=dates,
        columns=['A']
    )
    
    fig, ax = plt.subplots(figsize=(10, 6))
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
    ax.bar(df.index, df['A'], width=25, align='center')
    

    And that gives me:

提交回复
热议问题