How to plot a pandas timeseries using months/year resolution (with few lines of code)?

后端 未结 1 1337
误落风尘
误落风尘 2021-01-03 18:54

Assume we want to plot a time series, e.g.:

import pandas as pd
import numpy as np

a=pd.DatetimeIndex(start=\'2010-01-01\',end=\'2014-01-01\' , freq=\'D\')
         


        
相关标签:
1条回答
  • 2021-01-03 19:41

    Pandas does some really weird stuff to the Axes objects, making it hard to avoid matplotlib calls.

    Here's how I would do it

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    import pandas as pd
    
    
    a = pd.DatetimeIndex(start='2010-01-01',end='2014-01-01' , freq='D')
    b = pd.Series(np.random.randn(len(a)), index=a)
    fig, ax = plt.subplots()
    ax.plot(b.index, b)
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
    

    which give me: enter image description here

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