简体   繁体   English

如何使Matplotlib在X轴上显示日期而不在周末绘制空间

[英]How to make matplotlib show dates in x-axis without plotting spaces in weekends

I've been using this example: and I am trying to use the code shown below to make grid locate the first date (first date in csv file, so it might be eg 3. July instead of 1. July). 我一直在使用示例:并且我正在尝试使用下面显示的代码来使网格定位第一个日期(csv文件中的第一个日期,因此它可能是例如3月7日,而不是1月7日)。

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

However when I write the code above all dates disappear, and the grid show no lines marking the x-axis (see code 2 below): 但是,当我在上面编写代码时,所有日期都消失了,并且网格中没有显示标记x轴的线(请参见下面的代码2):

在此处输入图片说明

How can I make set_major_locator() to locate the first day in month (first available from csv file)? 如何使set_major_locator()定位每月的第一天(从csv文件中首先可用)? In the picture below I've made the grid locate first day in month by using 在下面的图片中,我已经使用

ax.plot(r.date, r.adj_close, 'o-')
months = matplotlib.dates.MonthLocator()
ax.xaxis.set_major_locator(months)

在此处输入图片说明

The problem here is that empty days make spaces, and this makes problems when I'm trying to plot lines on the graph. 这里的问题是空天会产生空间,而当我试图在图表上绘制线条时,这会带来问题。

edit: Code 1 (puts grid in right place, but makes trouble when I try to plot lines as it makes spaces in weekends etc): 编辑:代码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()

Code 2 (set_major_locator() doesn't work): 代码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()

To locate the first day of months, you should use: 要查找月份的第一天,应使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM