Matplotlib DateFormatter for axis label not working

前端 未结 2 966
执笔经年
执笔经年 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:

    0 讨论(0)
  • 2020-11-29 06:07

    The accepted answer claims that "pandas won't work well with custom date-time formats", but you can make use of pandas' to_datetime() function to use your existing datetime Series in the dataframe:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.dates import DateFormatter
    import pandas as pd
    
    rng = pd.date_range('1/1/2014', periods=20, freq='m')
    
    blah = pd.DataFrame(data = np.random.randn(len(rng)), index=pd.to_datetime(rng))
    
    fig, ax = plt.subplots()
    
    ax.xaxis.set_major_formatter(DateFormatter('%m-%Y'))
    ax.bar(blah.index, blah[0], width=25, align='center')
    

    Will result in:

    You can see the different available formats here.

    0 讨论(0)
提交回复
热议问题