如何使matplotlib在x轴上显示日期而不在周末绘制空格

时间:2017-08-07 08:00:46

标签: python date matplotlib

我一直在使用this示例: 我试图使用下面显示的代码使网格找到第一个日期(csv文件中的第一个日期,所以它可能是例如3. 7月而不是7月7日。)

months = matplotlib.dates.MonthLocator()
ax.xaxis.set_major_locator(months)

但是当我编写上面的代码时,所有日期都消失了,并且网格没有显示标记x轴的线条(参见下面的代码2):

enter image description here

如何让set_major_locator()找到月中的第一天(首先从csv文件中找到)? 在下面的图片中,我使用

使网格定位在第一天的第一天
ax.plot(r.date, r.adj_close, 'o-')
months = matplotlib.dates.MonthLocator()
ax.xaxis.set_major_locator(months)

enter image description here

这里的问题是,空日会产生空格,当我尝试在图表上绘制线条时会出现问题。

编辑: 代码1(将网格放在正确的位置,但是当我尝试绘制线条时会遇到麻烦,因为它会在周末创建空格等):

def plot1(price, date):
    # first we'll do it the default way, with gaps on weekends
    fig, ax = plt.subplots()
    ax.plot(date, price, 'o-',c='black', markersize=2.7, linewidth=0.9)
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%Y-%d'))
    days_locator = mdates.DayLocator(bymonthday=[1,])
    ax.xaxis.set_major_locator(days_locator)
    ax.set_title("Default")
    fig.autofmt_xdate()
    ax.grid()
    plt.show()

代码2(set_major_locator()不起作用):

def plot2(price, date):
    # next we'll write a custom formatter
    N = len(price)
    ind = np.arange(N)  # the evenly spaced plot indices
    def format_date(x, pos=None):
        thisind = np.clip(int(x + 0.5), 0, N - 1)
        return date[thisind].strftime('%Y-%m-%d')
    fig, ax = plt.subplots()
    ax.plot(ind, price, 'o-',c='black', markersize=2.7, linewidth=0.9)
    ax.xaxis.set_major_formatter(mticker.FuncFormatter(format_date))
    ax.set_title("Custom tick formatter")
    days_locator = mdates.DayLocator(bymonthday=[1,])
    ax.xaxis.set_major_locator(days_locator)
    fig.autofmt_xdate()
    ax.grid()
    plt.show()

1 个答案:

答案 0 :(得分:0)

要找到月份的第一天,您应该使用:

days_locator = mdates.DayLocator(bymonthday=[1,])
ax.xaxis.set_major_locator(days_locator)