matplotlib only business days without weekends on x-axis with plot_date

后端 未结 1 1781
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 20:30

I have the following persistent problem:

The following code should draw a straight line:

import numpy as np
import pandas as pd
import matplotlib.pyp         


        
相关标签:
1条回答
  • 2020-12-20 20:59

    plot_date does a trick, it converts dates to number of days since 1-1-1 and uses these numbers to plot, then converts the ticks to dates again in order to draw nice tick labels. So using plot_date each day count as 1, business or not.

    You can plot your data against a uniform range of numbers but if you want dates as tick labels you need to do it yourself.

    d = pd.date_range(start="1/1/2012", end="2/1/2012", freq="B")
    v = np.linspace(1,10,len(d))
    
    plt.plot(range(d.size), v)
    xticks = plt.xticks()[0]
    xticklabels = [(d[0] + x).strftime('%Y-%m-%d') for x in xticks.astype(int)]
    plt.xticks(xticks, xticklabels)
    plt.autoscale(True, axis='x', tight=True)
    

    But be aware that the labels can be misleading. The segment between 2012-01-02 and 2012-01-09 represents five days, not seven.

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