• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python dates.rrulewrapper函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中matplotlib.dates.rrulewrapper函数的典型用法代码示例。如果您正苦于以下问题:Python rrulewrapper函数的具体用法?Python rrulewrapper怎么用?Python rrulewrapper使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了rrulewrapper函数的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_RRuleLocator

def test_RRuleLocator():
    import pylab
    import matplotlib.dates as mpldates
    import matplotlib.testing.jpl_units as units
    from datetime import datetime
    import dateutil
    units.register()

    # This will cause the RRuleLocator to go out of bounds when it tries
    # to add padding to the limits, so we make sure it caps at the correct
    # boundary values.
    t0 = datetime( 1000, 1, 1 )
    tf = datetime( 6000, 1, 1 )

    fig = pylab.figure()
    ax = pylab.subplot( 111 )
    ax.set_autoscale_on( True )
    ax.plot( [t0, tf], [0.0, 1.0], marker='o' )

    rrule = mpldates.rrulewrapper( dateutil.rrule.YEARLY, interval=500 )
    locator = mpldates.RRuleLocator( rrule )
    ax.xaxis.set_major_locator( locator )
    ax.xaxis.set_major_formatter( mpldates.AutoDateFormatter(locator) )

    ax.autoscale_view()
    fig.autofmt_xdate()

    fig.savefig( 'RRuleLocator_bounds' )
开发者ID:ivanov,项目名称:matplotlib-py3,代码行数:28,代码来源:test_dates.py


示例2: test_rrulewrapper

def test_rrulewrapper():
    r = rrulewrapper(2)
    try:
        pickle.loads(pickle.dumps(r))
    except RecursionError:
        print('rrulewrapper pickling test failed')
        raise
开发者ID:vapier,项目名称:matplotlib,代码行数:7,代码来源:test_pickle.py


示例3: plot

def plot(dates,samples,units,samType,graphdir):
	i = 0

	for d in dates:
		if d.find('/')==-1:
			first = d.find('-')
			second = d.rfind('-')
			# Check for missing month/day/year values in the file
			try:
				year = int(d[0:first])
			except ValueError:
				year = 1900
			try:
				month = int(d[first+1:second])
			except ValueError:
				month = 1
			try:
				day = int(d[second+1:])
			except ValueError:
				day = 1
			if(first == -1 and second == -1):
				day = 1
				month = 1
				
			dates[i] = datetime.date(year,month,day)
			i = i+1		
		else:		
			first = d.find('/')
			second = d.rfind('/')
			dates[i] = datetime.date(int(d[second+1:]),int(d[0:first]),int(d[first+1:second]))
			i = i+1
	c = 0
	for s in samples:
		if s == '':
			samples[c]  = '0.0'
		c = c+1
	rule = rrulewrapper(YEARLY)
	loc = RRuleLocator(rule)
	formatter = DateFormatter('%Y')
	#sample_range = (float(max(float(i) for i in samples)) - float(min(float(i) for i in samples)))
	#sample_range = sample_range/25
	
	fig, ax = plt.subplots()

	#if (sample_range != 0):
	#	minorLocator = MultipleLocator(sample_range)
	#	ax.yaxis.set_minor_locator(minorLocator)
	
	plt.plot_date(dates, samples)
	ax.xaxis.set_major_locator(loc)
	ax.xaxis.set_major_formatter(formatter)
	labels = ax.get_xticklabels()
	plt.title(samType)
	plt.ylabel(units)
	plt.setp(labels, rotation=30, fontsize=12)
	plt.savefig(graphdir+'/'+samType+'.png',bbox_inches='tight')
	plt.close()
开发者ID:tuckerrc,项目名称:pyscripts,代码行数:57,代码来源:writer.py


示例4: plotschedule

def plotschedule(begin, end, deadline, schedule, title='Schedule',
                 timePenalty=defaultTimePenalty, blocking=True, display=False):

    fig = plt.figure()
    fig.set_size_inches(18,13.5)
    ax = fig.add_axes([0.2,0.2,0.75,0.7])  #[left,bottom,width,height]
    ax.set_title(title)

    ax.axvline(x=begin, color="green")
    if end is not None:
        ax.axvline(x=end, color="blue")
    if deadline is not None:
        ax.axvline(x=deadline, color="red")

    # Plot the data
    for (pulsar,start,stop, optimalUTC, priority) in reversed(schedule):
        start_date = matplotlib.dates.date2num(start)
        stop_date = matplotlib.dates.date2num(stop)
        duration = stop_date - start_date
        optimal_start = matplotlib.dates.date2num(optimalUTC) - 0.5*duration

        ax.axhline(y=schedule.index((pulsar,start,stop, optimalUTC, priority)), color=(0.8, 0.8, 0.8), zorder=0)

        ax.barh((schedule.index((pulsar,start,stop, optimalUTC, priority))), duration, left=optimal_start, height=0.5,align='center',label=pulsar, color=(0.9, 0.9, 0.9), edgecolor = "none")
        ax.barh((schedule.index((pulsar,start,stop, optimalUTC, priority))), duration, left=start_date, height=0.6, align='center',label=pulsar, color=(min(determinetimebadness(start, stop, optimalUTC, timePenalty), int(colorNormalizeBadness))/colorNormalizeBadness,  0.0, 0.0))

    # Format y-axis
    pos = range(len(schedule))
    locsy, labelsy = yticks(pos, zip(*schedule)[0])
    plt.setp(labelsy,size='medium')


    # Format x-axis
    ax.axis('tight')
    ax.xaxis_date()

    rule = rrulewrapper(HOURLY, interval=3)
    loc = RRuleLocator(rule)
    formatter = DateFormatter("%d %h - %H h")

    ax.xaxis.set_major_locator(loc)
    ax.xaxis.set_major_formatter(formatter)
    labelsx = ax.get_xticklabels()
    plt.setp(labelsx, rotation=30, fontsize=10)

    if begin is None:
        begin = datetime.datetime.now()
    if deadline is not None:
        plt.xlim(begin - datetime.timedelta(hours=1) ,deadline + datetime.timedelta(hours=1))
    elif end is not None:
        plt.xlim(begin - datetime.timedelta(hours=1) ,end + datetime.timedelta(hours=1))
    else:
        plt.xlim(begin)

    fig.autofmt_xdate()
    plt.savefig('gantt.svg')
    plt.show(block=blocking)
开发者ID:sosl,项目名称:LOFAR-processing,代码行数:57,代码来源:observePulsars.py


示例5: graf

def graf():
    # plt.rc('axes', grid=True)
    # plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5)

    # fig = plt.figure(facecolor='white')
    # textsize = 9
    # left, width = 0.1, 0.8
    # rect1 = [left, 0.7, width, 0.2]
    # axescolor  = '#f6f6f6'  # the axes background color
    fig, ax = plt.subplots()

    # fig, ax = plt.subplots()
    fillcolor = 'darkgoldenrod'
    monthsFmt = DateFormatter("%d %b %y %H:%M:%S")
    with open(r".\report\test_online_main_page.csv", 'r', encoding='utf-8') as f:
        arr = [x.strip().split(';') for x in f]
        arr_time = [datetime.strptime(x[0], '%y/%m/%d %H:%M:%S') for x in arr[1:]]
        arr_value = [x[1] for x in arr[1:]]
    #datetime.strptime("14/07/05 10:20:16", '%y/%m/%d %H:%M:%S')  # 05.06.2011 "%d.%m.%Y"
    dt = datetime.now()
    vv = dates_mt.date2num(dt)
    date = []
    n = []
    # plt.plot(arr_time, arr_value, color=fillcolor)

    #ax.xaxis.set_minor_locator(mondays)
    rule = rrulewrapper(YEARLY, byeaster=1, interval=1)
    loc = RRuleLocator(rule)
    ax.plot_date(arr_time, arr_value, '-')#
    #ax.xaxis.set_major_formatter(monthsFmt)
    #fig.add_subplot(111)
    #ax.xaxis.set_major_locator(loc)
    hour = HourLocator(range(1,25), interval=4)
    formatter = DateFormatter('%H:%M:%S %m/%d/%y')
    ax.xaxis.set_major_locator(hour)
    ax.xaxis.set_major_formatter(formatter)
    ##############################################
    fig, ax2 = fig.add_subplot()
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    sizes = [15, 30, 45, 10]
    colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
    explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')

    plt.pie(sizes, explode=explode, labels=labels, colors=colors,
            autopct='%1.1f%%', shadow=True, startangle=90)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')


    plt.savefig("fname2.png", dpi=None, facecolor='w', edgecolor='w',
        orientation='portrait', papertype=None, format=None,
        transparent=False, bbox_inches=None, pad_inches=0.1,
        frameon=None)
    plt.show()
开发者ID:kn7072,项目名称:kn7072,代码行数:54,代码来源:My_perfomans.py


示例6: _test_rrulewrapper

def _test_rrulewrapper(attach_tz, get_tz):
    SYD = get_tz('Australia/Sydney')

    dtstart = attach_tz(datetime.datetime(2017, 4, 1, 0), SYD)
    dtend = attach_tz(datetime.datetime(2017, 4, 4, 0), SYD)

    rule = mdates.rrulewrapper(freq=dateutil.rrule.DAILY, dtstart=dtstart)

    act = rule.between(dtstart, dtend)
    exp = [datetime.datetime(2017, 4, 1, 13, tzinfo=dateutil.tz.tzutc()),
           datetime.datetime(2017, 4, 2, 14, tzinfo=dateutil.tz.tzutc())]

    assert act == exp
开发者ID:NelleV,项目名称:matplotlib,代码行数:13,代码来源:test_dates.py


示例7: _configure_xaxis

    def _configure_xaxis(self):
        ''''x axis'''
        # make x axis date axis
        self._ax.xaxis_date()

        # format date to ticks on every 7 days
        rule = mdates.rrulewrapper(mdates.DAILY, interval=7)
        loc = mdates.RRuleLocator(rule)
        formatter = mdates.DateFormatter("%d %b")

        self._ax.xaxis.set_major_locator(loc)
        self._ax.xaxis.set_major_formatter(formatter)
        xlabels = self._ax.get_xticklabels()
        plt.setp(xlabels, rotation=30, fontsize=9)
开发者ID:EricDoug,项目名称:python-data-viz-cookbook,代码行数:14,代码来源:ch08_rec04_gantt.py


示例8: CreateGanttChart

def CreateGanttChart(fname):
    """Create gantt charts with matplotlib
    Give file name.
    """
    ylabels = []
    customDates = []
    textlist = open(fname).readlines()

    for tx in textlist:
        if not tx.startswith('#'):
            ylabel, startdate, enddate = tx.split(',')
            ylabels.append(ylabel.replace('\n', ''))
            customDates.append([_create_date(startdate.replace('\n', '')), _create_date(enddate.replace('\n', ''))])

    ilen = len(ylabels)
    pos = np.arange(0.5, ilen * 0.5 + 0.5, 0.5)
    task_dates = {}
    for i, task in enumerate(ylabels):
        task_dates[task] = customDates[i]
    fig = plt.figure(figsize=(20, 8))
    ax = fig.add_subplot(111)
    for i in range(len(ylabels)):
        start_date, end_date = task_dates[ylabels[i]]
        ax.barh((i * 0.5) + 0.5, end_date - start_date, left=start_date, height=0.3, align='center', edgecolor='lightgreen', color='orange', alpha=0.8)
    locsy, labelsy = plt.yticks(pos, ylabels)
    plt.setp(labelsy, fontsize=14)
    # ax.axis('tight')
    ax.set_ylim(ymin=-0.1, ymax=ilen * 0.5 + 0.5)
    ax.grid(color='g', linestyle=':')
    ax.xaxis_date()
    rule = rrulewrapper(WEEKLY, interval=1)
    loc = RRuleLocator(rule)
    # formatter = DateFormatter("%d-%b '%y")
    formatter = DateFormatter("%d-%b")

    ax.xaxis.set_major_locator(loc)
    ax.xaxis.set_major_formatter(formatter)
    labelsx = ax.get_xticklabels()
    plt.setp(labelsx, rotation=30, fontsize=10)

    font = font_manager.FontProperties(size='small')
    ax.legend(loc=1, prop=font)

    ax.invert_yaxis()
    fig.autofmt_xdate()
    plt.savefig(fname + '.svg')
    plt.show()
开发者ID:bgoodr,项目名称:how-to,代码行数:47,代码来源:gantt_chart_basic.py


示例9: sales_by_month

def sales_by_month(data_map,header,dates):
    fn='sales_by_month.png'

    rule = rrulewrapper(DAILY, byeaster=1, interval=5)
    loc = RRuleLocator(rule)

    years = mdates.YearLocator()   # every year
    months = mdates.MonthLocator()  # every month
    weeks = mdates.WeekdayLocator()
    days = mdates.DayLocator()
    weeks.MAXTICKS = 2000


    formatter = DateFormatter('%a %d/%m/%y')
    #dates_x = drange(date1, date2, delta)
    fig, ax1 = plt.subplots(nrows=1,ncols=1)    
    #ax=ax1
    ax1.xaxis_date()
    ax1.xaxis.set_major_formatter(formatter)
    ax1.xaxis.set_major_locator(weeks)
    ax1.xaxis.set_minor_locator(days)

    labels = ax1.get_xticklabels()
    #labels = ax1.xaxis.get_major_ticks()

    plt.setp(labels, rotation=30, fontsize=10)
    plt.title('Phone Calls, 30 days window')
    ax1.grid()

    key_inbound=(u'Inbound', 'crm.case.categ', 18)
    plot_days(ax1, data_map, dates, key_inbound, line='k', label='Inbound Calls', days=30)

    key_sales= (u'Sales Opportunity', 'crm.case.categ', 15)
    plot_days(ax1, data_map, dates, key_sales, line='r', label='Sales Opportunity', days=30)

    key_phone= (u'Retail Phone', 'sale.shop', 2)
    plot_days(ax1, data_map, dates, key_phone, line='-', label='Closed Sales', days=30)

    ax1.legend()

    image_path=get_module_path('html_reports')
    image_file=os.path.join(image_path,fn)
#    print image_file
    plt.savefig(image_file, bbox_inches='tight')
    #print data_map
    return fn
开发者ID:galtys,项目名称:galtys-addons,代码行数:46,代码来源:main.py


示例10: yticks

# 	# ax.barh((i*0.5)+1.0, end_date - mid_date, left=mid_date, height=0.3, align='center',label=labels[1], color='yellow')
 
# Format the y-axis
 
locsy, labelsy = yticks(pos,ylabels)
plt.setp(labelsy, fontsize = 14)
 
# Format the x-axis
 
ax.axis('tight')
ax.set_ylim(ymin = -0.1, ymax = 6.5)
ax.grid(color = 'g', linestyle = ':')
 
ax.xaxis_date() #Tell matplotlib that these are dates...
 
rule = rrulewrapper(WEEKLY, interval=1)
loc = RRuleLocator(rule)
formatter = DateFormatter("%b %d")
 
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(formatter)
labelsx = ax.get_xticklabels()
plt.setp(labelsx, rotation=30, fontsize=12)
 
# Format the legend
 
# font = font_manager.FontProperties(size='small')
# ax.legend(loc=1,prop=font)
 
# Finish up
ax.invert_yaxis()
开发者ID:dthiagarajan,项目名称:grozi_tf,代码行数:31,代码来源:gantt.py


示例11: figure

# Select only good data
qcLevel = 1
index_qcLevel = TEMP_qcFlag[:, 0, 0] == qcLevel
timeData = timeData[index_qcLevel]
tempData = TEMP[:, 0, 0]
tempData = tempData[index_qcLevel]

# plot temperature timeseries
figure1 = figure(num=None, figsize=(15, 10), dpi=80, facecolor="w", edgecolor="k")
ax1 = subplot(111)
plot(timeData, tempData)

title(
    faimms_DATA.title
    + "\n"
    + "%0.2f m depth\n" % TEMP.sensor_depth
    + "location: lat=%0.2f; lon=%0.2f" % (faimms_DATA.variables["LATITUDE"][:], faimms_DATA.variables["LONGITUDE"][:])
)
xlabel(TIME.long_name)
ylabel(TEMP.standard_name + " in " + TEMP.units)

rule = rrulewrapper(DAILY, interval=1)
formatter = DateFormatter("%d/%m/%y")
loc = RRuleLocator(rule)
ax1.xaxis.set_major_locator(loc)
ax1.xaxis.set_major_formatter(formatter)
labels = ax1.get_xticklabels()
setp(labels, rotation=30, fontsize=10)

show()
开发者ID:aodn,项目名称:imos-user-code-library,代码行数:30,代码来源:faimms.py


示例12: main


#.........这里部分代码省略.........

    for line in content[1:]:
        #filter only pages with total (or dic is -d) greater or smaller than X
        if opts.excludemorethan:
            if float(line[tot_index]) > opts.excludemorethan:
                continue
        if opts.excludelessthan:
            if float(line[tot_index]) < opts.excludelessthan:
                continue

        mat.append([x for x in _gen_data(line, opts.id_col,
                                         ignorecols, onlycols)])
        totals.append(float(line[tot_index]))
        timestamps.append(ts2dt(line[opts.id_col]))
    del content

    mat = np.array(mat, dtype=np.float).transpose()
    logging.info("Input file read. Ready to plot")
    pdf_pag = PdfPages(files[1])

    with Timr("Plotting"):
        for i, series in enumerate(mat):
            logging.info("Plotting page %d", i + 1)

            # Don't plot zeros and skip zero revisions!
            #ser = [x for x in series if x != 0]
            #time = [x for k, x in enumerate(timestamps) if series[k] != 0]
            #tot = [x for k, x in enumerate(totals) if series[k] != 0]
            ser = [x for k, x in enumerate(series) \
                   if (not opts.start or timestamps[k] >= opts.start) and \
                      (not opts.end or timestamps[k] <= opts.end)]
            time = [x for k, x in enumerate(timestamps) \
                    if (not opts.start or x >= opts.start) and \
                       (not opts.end or x <= opts.end)]
            tot = [x for k, x in enumerate(totals) \
                   if (not opts.start or timestamps[k] >= opts.start) and \
                      (not opts.end or timestamps[k] <= opts.end)]

            if opts.smooth and len(time) and len(ser) and len(tot):
                time, ser, tot = smooth_values(time, ser, tot,
                                               opts.smooth)

            if opts.window and len(time) and len(ser) and len(tot):
                time, ser, tot = collapse_values(time, ser, tot,
                                                 opts.window)

            mean = float(sum(series)) / len(series)
            #rel_mean is the mean for the period [opts.end, opts.start]
            rel_mean = float(sum(ser)) / len(ser)

            if opts.perc:
                try:
                    mean = float(sum(series)) / sum(totals)
                    rel_mean = float(sum(ser)) / sum(tot)
                except ZeroDivisionError:
                    mean = 0
                    rel_mean = 0
                # Calculate percentages
                ser = [calc_perc(x, tot[k]) for k, x in enumerate(ser)]
                # Set axis limit 0-1 IS IT GOOD OR BAD?
                #axis.set_ylim(0, 1)
                plt.ylabel("%")

            first_time = time[0].date()
            last_time = time[-1].date()
            plt.clf()
            plt.subplots_adjust(bottom=0.25)
            plt.xticks(rotation=90)
            fig = plt.gcf()
            fig.set_size_inches(11.7, 8.3)
            axis = plt.gca()
            axis.xaxis.set_major_formatter(md.DateFormatter('%Y-%m-%d'))
            axis.set_xlim(matplotlib.dates.date2num(first_time),
                          matplotlib.dates.date2num(last_time))
            if last_time - first_time < timedelta(days=30):
                axis.xaxis.set_major_locator(md.DayLocator(interval=1))
                axis.xaxis.set_minor_locator(md.DayLocator(interval=1))
            else:
                axis.xaxis.set_minor_locator(md.MonthLocator(interval=1))
                #auto_loc = md.AutoDateLocator(minticks=8, maxticks=12, interval_multiples=True)
                #auto_loc.intervald[md.MONTHLY] = [6]
                rule = md.rrulewrapper(md.MONTHLY, interval=4)
                auto_loc = md.RRuleLocator(rule)
                axis.xaxis.set_major_locator(auto_loc)
            axis.tick_params(labelsize='x-small')
            plt.xlabel("Revisions Timestamp")

            if len(time) and len(ser):
                if opts.window:
                    time = [t.date() for t in time]
                logging.info("Mean: %f", mean)
                logging.info("Relative Mean: %f", rel_mean)
                if header[i] == "negemo" or header[i] == "posemo":
                    print ser  # ONLY FOR TESTING, FIXME WHEN FINISHED
                plt.plot(matplotlib.dates.date2num(time), ser, "b.-")
                plt.axhline(y=mean, color="r")
                plt.title("%s - Mean: %.5f - Relative mean: %.5f" % (header[i], round(mean, 5), round(rel_mean, 5)))
                pdf_pag.savefig()

        pdf_pag.close()
开发者ID:SoNetFBK,项目名称:wiki-network,代码行数:101,代码来源:pywc_plot.py


示例13: float

    splt = l.split(" ")
    date_str = splt[0]

    date.append( datetime.strptime(date_str,"%Y-%m-%dT%H%M%S.%f") )
    voltage.append( float(splt[1]) )
    gps_on.append( (splt[2] == "True") )
    humidity.append( float(splt[3]) )
    temp0.append( float(splt[4]) )
    temp1.append( float(splt[5]) )
    temp2.append( float(splt[6]) )
    temp3.append( float(splt[7]) )
    temp4.append( float(splt[8]) )

fig, (ax0, ax1, ax2, ax3) = plt.subplots(nrows=4, sharex=True)
formatter = DateFormatter('%d/%m/%y')
rule = rrulewrapper(DAILY)
loc = RRuleLocator(rule)

ax0.plot(date,voltage, ".")
ax0.xaxis.set_major_formatter(formatter)
ax0.xaxis.set_major_locator(loc)
ax0.set_title("voltage (V)")

ax1.plot(date,temp0, ".")
ax1.plot(date,temp1, ".")
ax1.plot(date,temp2, ".")
ax1.plot(date,temp3, ".")
ax1.plot(date,temp4, ".")
ax1.xaxis.set_major_formatter(formatter)
ax1.xaxis.set_major_locator(loc)
ax1.set_title("temperature (degC)")
开发者ID:thorsteinssonh,项目名称:nicair-fits-tools,代码行数:31,代码来源:plot_env_data.py


示例14: subplot

# plot current profiles
figure1 =figure( figsize=(13, 18), dpi=80, facecolor='w', edgecolor='k')
ax1 = subplot(211)

pcolor(prof_2D_mesh , heightData_mesh , uCurrentData[:,:,0,0],cmap=cmap)
clim(UCUR.valid_min, UCUR.valid_max)
cbar = colorbar()
cbar.ax.set_ylabel(UCUR.long_name + ' in ' + UCUR.units)

title(anmn_DATA.title + '\nplot of ' + flag_meanings[qcLevel[0]] + 
      ' and ' + flag_meanings[qcLevel[1]] + ' only')
xlabel('Profile Index')
ylabel(HEIGHT.long_name +' in ' + HEIGHT.units)

# plot profile index with time 
ax2 = subplot(212)
plot(timeData,profIndex)
ylabel('Profile Index')
xlabel(anmn_DATA.variables['TIME'].long_name +' in DD/MM/YY')

# format date ticks
rule = rrulewrapper(MONTHLY, bymonthday=1, interval=1)
formatter = DateFormatter('%d/%m/%y')
loc = RRuleLocator(rule)
ax2.xaxis.set_major_locator(loc)
ax2.xaxis.set_major_formatter(formatter)
labels = ax2.get_xticklabels()
setp(labels, rotation=30, fontsize=10)

show()
开发者ID:XUESHANXIAOXIA,项目名称:imos-user-code-library,代码行数:30,代码来源:anmn_adcp.py


示例15: get_locator

    def get_locator(self, dmin, dmax):
        'Pick the best locator based on a distance.'

        delta = relativedelta(dmax, dmin)

        numYears = (delta.years * 1.0)
        numMonths = (numYears * 12.0) + delta.months
        numDays = (numMonths * 31.0) + delta.days
        numHours = (numDays * 24.0) + delta.hours
        numMinutes = (numHours * 60.0) + delta.minutes
        numSeconds = (numMinutes * 60.0) + delta.seconds

        # numticks = 5
        # Difference to original AutoDateLocator: less ticks
        numticks = self.numticks

        # self._freq = YEARLY
        interval = 1
        bymonth = 1
        bymonthday = 1
        byhour = 0
        byminute = 0
        bysecond = 0
        if (numYears >= numticks):
            self._freq = YEARLY
            interval = int(numYears // numticks)
        elif (numMonths >= numticks):
            self._freq = MONTHLY
            bymonth = range(1, 13)
            interval = int(numMonths // numticks)
        elif (numDays >= numticks):
            self._freq = DAILY
            bymonth = None
            bymonthday = range(1, 32)
            interval = int(numDays // numticks)
        elif (numHours >= numticks):
            self._freq = HOURLY
            bymonth = None
            bymonthday = None
            byhour = range(0, 24)      # show every hour
            interval = int(numHours // numticks)
        elif (numMinutes >= numticks):
            self._freq = MINUTELY
            bymonth = None
            bymonthday = None
            byhour = None
            byminute = range(0, 60)
            interval = int(numMinutes // numticks)
            # end if
        elif (numSeconds >= numticks):
            self._freq = SECONDLY
            bymonth = None
            bymonthday = None
            byhour = None
            byminute = None
            bysecond = range(0, 60)
            interval = int(numSeconds // numticks)
            # end if
        else:
            # do what?
            #   microseconds as floats, but floats from what reference point?
            pass

        rrule = rrulewrapper(self._freq, interval=interval,
                             dtstart=dmin, until=dmax,
                             bymonth=bymonth, bymonthday=bymonthday,
                             byhour=byhour, byminute=byminute,
                             bysecond=bysecond)

        locator = RRuleLocator(rrule, self.tz)
        locator.set_axis(self.axis)

        locator.set_view_interval(*self.axis.get_view_interval())
        locator.set_data_interval(*self.axis.get_data_interval())
        return locator
开发者ID:nens,项目名称:nens-graph,代码行数:75,代码来源:common.py


示例16: get_locator

    def get_locator(self, dmin, dmax):
        'Pick the best locator based on a distance.'
        delta = relativedelta(dmax, dmin)
        tdelta = dmax - dmin

        # take absolute difference
        if dmin > dmax:
            delta = -delta
            tdelta = -tdelta

        # The following uses a mix of calls to relativedelta and timedelta
        # methods because there is incomplete overlap in the functionality of
        # these similar functions, and it's best to avoid doing our own math
        # whenever possible.
        numYears = float(delta.years)
        numMonths = (numYears * MONTHS_PER_YEAR) + delta.months
        numDays = tdelta.days   # Avoids estimates of days/month, days/year
        numHours = (numDays * HOURS_PER_DAY) + delta.hours
        numMinutes = (numHours * MIN_PER_HOUR) + delta.minutes
        numSeconds = np.floor(tdelta.total_seconds())
        numMicroseconds = np.floor(tdelta.total_seconds() * 1e6)

        nums = [numYears, numMonths, numDays, numHours, numMinutes,
                numSeconds, numMicroseconds]

        use_rrule_locator = [True] * 6 + [False]

        # Default setting of bymonth, etc. to pass to rrule
        # [unused (for year), bymonth, bymonthday, byhour, byminute,
        #  bysecond, unused (for microseconds)]
        byranges = [None, 1, 1, 0, 0, 0, None]

        usemicro = False  # use as flag to avoid raising an exception

        # Loop over all the frequencies and try to find one that gives at
        # least a minticks tick positions.  Once this is found, look for
        # an interval from an list specific to that frequency that gives no
        # more than maxticks tick positions. Also, set up some ranges
        # (bymonth, etc.) as appropriate to be passed to rrulewrapper.
        for i, (freq, num) in enumerate(zip(self._freqs, nums)):
            # If this particular frequency doesn't give enough ticks, continue
            if num < self.minticks:
                # Since we're not using this particular frequency, set
                # the corresponding by_ to None so the rrule can act as
                # appropriate
                byranges[i] = None
                continue

            # Find the first available interval that doesn't give too many
            # ticks
            for interval in self.intervald[freq]:
                if num <= interval * (self.maxticks[freq] - 1):
                    break
            else:
                # We went through the whole loop without breaking, default to
                # the last interval in the list and raise a warning
                warnings.warn('AutoDateLocator was unable to pick an '
                              'appropriate interval for this date range. '
                              'It may be necessary to add an interval value '
                              "to the AutoDateLocator's intervald dictionary."
                              ' Defaulting to {0}.'.format(interval))

            # Set some parameters as appropriate
            self._freq = freq

            if self._byranges[i] and self.interval_multiples:
                byranges[i] = self._byranges[i][::interval]
                interval = 1
            else:
                byranges[i] = self._byranges[i]

            # We found what frequency to use
            break
        else:
            if False:
                raise ValueError(
                    'No sensible date limit could be found in the '
                    'AutoDateLocator.')
            else:
                usemicro = True

        if not usemicro and use_rrule_locator[i]:
            _, bymonth, bymonthday, byhour, byminute, bysecond, _ = byranges

            rrule = rrulewrapper(self._freq, interval=interval,
                                 dtstart=dmin, until=dmax,
                                 bymonth=bymonth, bymonthday=bymonthday,
                                 byhour=byhour, byminute=byminute,
                                 bysecond=bysecond)

            locator = RRuleLocator(self._dates, rrule, self.tz)
        else:
            locator = MicrosecondLocator(interval, tz=self.tz)

        locator.set_axis(self.axis)

        locator.set_view_interval(*self.axis.get_view_interval())
        locator.set_data_interval(*self.axis.get_data_interval())
        return locator
开发者ID:remroc,项目名称:backtrader,代码行数:99,代码来源:locator.py


示例17: get_locator

  def get_locator( self, dmin, dmax ):
    'pick the best locator based on a distance'

    delta = relativedelta( dmax, dmin )
    numYears = ( delta.years * 1.0 )
    numMonths = ( numYears * 12.0 ) + delta.months
    numDays = ( numMonths * 31.0 ) + delta.days
    numHours = ( numDays * 24.0 ) + delta.hours
    numMinutes = ( numHours * 60.0 ) + delta.minutes
    numSeconds = ( numMinutes * 60.0 ) + delta.seconds

    numticks = 5

    # self._freq = YEARLY
    interval = 1
    bymonth = 1
    bymonthday = 1
    byhour = 0
    byminute = 0
    bysecond = 0

    if numYears >= numticks:
      self._freq = YEARLY
    elif numMonths >= numticks:
      self._freq = MONTHLY
      bymonth = range( 1, 13 )
      if ( 0 <= numMonths ) and ( numMonths <= 14 ):
        interval = 1      # show every month
      elif ( 15 <= numMonths ) and ( numMonths <= 29 ):
        interval = 3      # show every 3 months
      elif ( 30 <= numMonths ) and ( numMonths <= 44 ):
        interval = 4      # show every 4 months
      else:   # 45 <= numMonths <= 59
        interval = 6      # show every 6 months
    elif numDays >= numticks:
      self._freq = DAILY
      bymonth = None
      bymonthday = range( 1, 32 )
      if ( 0 <= numDays ) and ( numDays <= 9 ):
        interval = 1      # show every day
      elif ( 10 <= numDays ) and ( numDays <= 19 ):
        interval = 2      # show every 2 days
      elif ( 20 <= numDays ) and ( numDays <= 35 ):
        interval = 3      # show every 3 days
      elif ( 36 <= numDays ) and ( numDays <= 80 ):
        interval = 7      # show every 1 week
      else:   # 100 <= numDays <= ~150
        interval = 14     # show every 2 weeks
    elif numHours >= numticks:
      self._freq = HOURLY
      bymonth = None
      bymonthday = None
      byhour = range( 0, 24 )      # show every hour
      if ( 0 <= numHours ) and ( numHours <= 14 ):
        interval = 1      # show every hour
      elif ( 15 <= numHours ) and ( numHours <= 30 ):
        interval = 2      # show every 2 hours
      elif ( 30 <= numHours ) and ( numHours <= 45 ):
        interval = 3      # show every 3 hours
      elif ( 45 <= numHours ) and ( numHours <= 68 ):
        interval = 4      # show every 4 hours
      elif ( 68 <= numHours ) and ( numHours <= 90 ):
        interval = 6      # show every 6 hours
      else:   # 90 <= numHours <= 120
        interval = 12     # show every 12 hours
    elif numMinutes >= numticks:
      self._freq = MINUTELY
      bymonth = None
      bymonthday = None
      byhour = None
      byminute = range( 0, 60 )
      if numMinutes > ( 10.0 * numticks ):
        interval = 10
      # end if
    elif numSeconds >= numticks:
      self._freq = SECONDLY
      bymonth = None
      bymonthday = None
      byhour = None
      byminute = None
      bysecond = range( 0, 60 )
      if numSeconds > ( 10.0 * numticks ):
        interval = 10
      # end if
    else:
      # do what?
      #   microseconds as floats, but floats from what reference point?
      pass

    rrule = rrulewrapper( self._freq, interval = interval, \
                          dtstart = dmin, until = dmax, \
                          bymonth = bymonth, bymonthday = bymonthday, \
                          byhour = byhour, byminute = byminute, \
                          bysecond = bysecond )

    locator = RRuleLocator( rrule, self.tz )
    locator.set_axis( self.axis )

    locator.set_view_interval( *self.axis.get_view_interval() )
    locator.set_data_interval( *self.axis.get_data_interval() )
#.........这里部分代码省略.........
开发者ID:DIRACGrid,项目名称:DIRAC,代码行数:101,代码来源:GraphUtilities.py


示例18: generate_gantt_chart

def generate_gantt_chart():
	# Data
	ylabels = []
	customDates = []
	
	for epic in projects:
		epic_name = epic["name"]
	 	start_date = epic["start_date"]
		exp_end_date = epic["exp_end_date"]
		act_end_date = epic["act_end_date"]
		if act_end_date != "":
			est_end_date = ""
		else:
			est_end_date = epic["est_end_date"]
		
		customDates.append([format_date(start_date),format_date(exp_end_date),format_date(est_end_date),format_date(act_end_date),epic_name])

	customDates.sort(key=lambda x: (x[2], x[3]))

	for label in customDates:
		ylabels.append(label.pop())
	
	task_dates = {}
	for i,task in enumerate(ylabels):
		task_dates[task] = customDates[i]
	 
	# Initialise plot
	fig = plt.figure()
	ax = fig.add_subplot(111)

	# Set up legend
	calculated = mpatches.Patch(color="gold", label="Calculated")
	planned = mpatches.Patch(color="palegreen", label="Planned")
	behind = mpatches.Patch(color="lightcoral", label="Behind")
	actual = mpatches.Patch(color="lightgrey", label="Actual")

	colors = [calculated,planned,behind,actual]
	labels = [color.get_label() for color in colors]
	plt.legend(colors, labels)

	# Plot the data
	today = format_date(dt.date.today().strftime("%m/%d/%Y"))

	for i in range(-1,len(ylabels)-1):
		start_date,exp_end_date,est_end_date,act_end_date = task_dates[ylabels[i+1]]
		if start_date != "":
			if est_end_date != "":
				ax.barh((i*0.5)+0.95, est_end_date - start_date, left=start_date, height=0.3, align='center', color='gold', alpha = 0.75, edgecolor='gold')
			if exp_end_date != "":
				if act_end_date == "":
					if today > exp_end_date:
						ax.barh((i*0.5)+0.95, today - exp_end_date, left=exp_end_date, height=0.1, align='center', color='lightcoral', alpha = 0.75)
				else:
					ax.barh((i*0.5)+0.95, act_end_date - start_date, left=start_date, height=0.3, align='center', color='lightgrey', edgecolor='lightgrey', alpha = 0.75)
					if act_end_date > exp_end_date:
						ax.barh((i*0.5)+0.95, act_end_date - exp_end_date, left=exp_end_date, height=0.1, align='center', color='lightcoral', alpha = 0.75)
				ax.barh((i*0.5)+0.95, exp_end_date - start_date, left=start_date, height=0.1, align='center', color='palegreen', alpha = 0.75)
	 
	# Format the y-axis
	pos = arange(0.45,(len(ylabels) / 2),0.5)
	locsy, labelsy = yticks(pos,ylabels)
	plt.setp(labelsy, fontsize = 14)
	 
	# Format the x-axis
	max_value = 1 + (len(ylabels) / 2)
	ax.axis('tight')
	ax.set_ylim(ymin = -0.1, ymax = max_value)
	ax.grid(color = 'g', linestyle = ':')
	 
	ax.xaxis_date()
	 
	rule = rrulewrapper(MONTHLY, interval=1)
	loc = RRuleLocator(rule)
	formatter = DateFormatter("%b '%y")
	 
	ax.xaxis.set_major_locator(loc)
	ax.xaxis.set_major_formatter(formatter)
	labelsx = ax.get_xticklabels()
	plt.setp(labelsx, rotation=30, fontsize=12)
	 
	# Format the legend
	font = font_manager.FontProperties(size='medium')
	ax.legend(loc=1,prop=font)
	 
	# Finish up
	ax.invert_yaxis()
	fig.autofmt_xdate()
	return plt.show()
开发者ID:valeriewilson,项目名称:sandglass,代码行数:88,代码来源:gantt_chart.py



注:本文中的matplotlib.dates.rrulewrapper函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python dates.strpdate2num函数代码示例发布时间:2022-05-27
下一篇:
Python dates.num2date函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap