【问题标题】:How to make matplotlib show dates in x-axis without plotting spaces in weekends如何使matplotlib在x轴上显示日期而不在周末绘制空格
【发布时间】:2017-08-07 08:00:45
【问题描述】:

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

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

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

如何使set_major_locator() 定位一个月的第一天(首先可从 csv 文件获得)? 在下图中,我使用

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

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

编辑: 代码 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()

【问题讨论】:

    标签: python date matplotlib


    【解决方案1】:

    要定位月份的第一天,您应该使用:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    相关资源
    最近更新 更多