Example #1
0
def graph(df_aggregate, label_tail, fig, i):
    # Create axis to store graph
    ax = fig.add_subplot(3, 3, i)

    # Background color
    ax.set_facecolor('mistyrose')

    # Grid color
    plt.grid(True, color='lightcoral')

    # Graph sides color
    for child in ax.get_children():
        if isinstance(child, spines.Spine):
            child.set_color('#CD5C5C')

    # Turn off scientific notation, give numbers commas, format dates
    ax.get_yaxis().get_major_formatter().set_scientific(False)
    ax.get_yaxis().set_major_formatter(
        tick.FuncFormatter(lambda x, p: format(int(x), ',')))
    ax.get_xaxis().set_major_formatter(dates.DateFormatter('%-m/%-d'))

    # Set axis labels
    ax.set_ylabel(f'Cases {label_tail}')
    ax.set_xlabel('Date')

    # Create rules for major and minor x-axis ticks: major every week,
    # minor every day
    rule = dates.rrulewrapper(dates.DAILY, interval=7)
    rule_minor = dates.rrulewrapper(dates.DAILY, interval=1)
    days = dates.RRuleLocator(rule)
    days_minor = dates.RRuleLocator(rule_minor)

    # Create major and minor ticks: x-axis by rule above, y-axis auto-generated
    ax.xaxis.set_minor_locator(days_minor)
    ax.yaxis.set_minor_locator(tick.AutoMinorLocator())
    ax.xaxis.set_major_locator(days)
    ax.yaxis.set_major_locator(tick.AutoLocator())

    # Graph data lines
    plt.plot('Confirmed', data=df_aggregate, alpha=0.65)
    plt.plot('Active', data=df_aggregate, alpha=0.65)
    plt.plot('Deaths', data=df_aggregate, color='tab:red', alpha=0.65)
    plt.plot('Recovered', data=df_aggregate, color='tab:green', alpha=0.65)

    # Legend colors
    plt.legend(facecolor='lavenderblush', edgecolor='#f0a0a0')

    return ax
Example #2
0
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' )
Example #3
0
    def test_RRuleLocator(self):
        """Test RRuleLocator"""
        fname = self.outFile("RRuleLocator_bounds.png")

        # 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(fname)
        self.checkImage(fname)
Example #4
0
def plot_data(data, fit, predicts, ylabel, saveName):
    #print(len(fit[0]), fit[1].shape)
    #print(predicts.shape)

    rule = mdt.rrulewrapper(mdt.DAILY, interval=15)
    loc = mdt.RRuleLocator(rule)
    formatter = mdt.DateFormatter('%d/%m/%y')
    fig, ax = plt.subplots()
    if data != None:
        plt.plot_date(data[0], data[1], ls='solid')
    if fit != None:
        plt.plot_date(fit[0], fit[1], ls='solid')
    #date_idx = 0

    if predicts != None:
        #for p in predicts:
        #dates = [begin_predict_date + datetime.timedelta(days = date_idx + i) for i in range(0,len(p))]
        plt.plot_date(predicts[0], predicts[1], ls='dashed')
        #date_idx += 1
    ax.xaxis.set_major_locator(loc)
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30, labelsize=10)
    ax.set_xlabel('Data')
    if ylabel != None:
        ax.set_ylabel(ylabel)
    plt.title(saveName)
    plt.savefig('{}_data_plot.png'.format(saveName))
Example #5
0
def convert_date_breaks(breaks_str: str) -> mdates.DateLocator:
    """
    Converts a conversational description of a period (e.g. 2 weeks) to a matplotlib date tick Locator.

    Args:
        breaks_str: A period description of the form "{interval} {period}"

    Returns:
        A corresponding mdates.Locator
    """
    # Column type groupings
    DATE_CONVERSION = {
        "year": YEARLY,
        "month": MONTHLY,
        "week": WEEKLY,
        "day": DAILY,
        "hour": HOURLY,
        "minute": MINUTELY,
        "second": SECONDLY,
    }
    interval, period = breaks_str.split()
    period = period.lower()
    if period.endswith("s"):
        period = period[:-1]
    period = DATE_CONVERSION[period]

    return mdates.RRuleLocator(mdates.rrulewrapper(period, interval=int(interval)))
Example #6
0
def test_rrulewrapper():
    r = rrulewrapper(2)
    try:
        pickle.loads(pickle.dumps(r))
    except RecursionError:
        print('rrulewrapper pickling test failed')
        raise
Example #7
0
def myTest():
    xdata = [
        "2018-01-02", "2018-01-03", "2018-01-04", "2018-01-05", "2018-01-06",
        "2018-01-07", "2018-01-08", "2018-01-09", "2018-01-10", "2018-01-11",
        "2018-01-12"
    ]
    # xdata = [712588., 712688.,
    #          712788., 712888.,
    #          712988., 713088.,
    #          713188., 713288.,
    #          713388., 713488.,
    #          713588.,]
    ydata = [
        5424.455042071198, 5437.436073513513, 5443.326118918919,
        5453.535032397408, 5465.99996972973, 5470.846144864865,
        5442.501206486487, 5329.997431351351, 5311.448544864865,
        5312.012034594594, 5312.620194384449
    ]

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

    formatter = DateFormatter('%Y-%m-%d')
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    xx = [datetime.strptime(x, '%Y-%m-%d') for x in xdata]
    print(xx)
    plt.plot_date(xx, ydata)
    ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))
    ax.xaxis.set_major_formatter(formatter)
    plt.gcf().autofmt_xdate()
    plt.show()
Example #8
0
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')
Example #9
0
   def test_RRuleLocator( self ):
      """Test RRuleLocator"""
      fname = self.outFile( "RRuleLocator_bounds.png" )

      # 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( fname )
      self.checkImage( fname )
Example #10
0
def test_rrulewrapper():
    r = rrulewrapper(2)
    try:
        pickle.loads(pickle.dumps(r))
    except RecursionError:
        print('rrulewrapper pickling test failed')
        raise
 def build_gantt(self, filename, title):
     '''builds the chart from self.objects'''
     num = len(self.objects)
     pos = np.arange(0.5,num*0.5+0.5,0.5)
     fig_height = 5 + num * 0.25
     fig = plt.figure(figsize=(20,fig_height))
     ax = fig.add_subplot(111)
     ylabels = []
     i = 0
     for obj in self.objects:
         starttime, endtime, uid, color = obj
         start = matplotlib.dates.date2num(starttime)
         end = matplotlib.dates.date2num(endtime)
         ylabels.append(uid)
         ax.barh((i*0.5)+0.5, end - start, left=start, height=0.3, align='center', edgecolor='darkorange', color=color, alpha = 0.8)
         i+=1
     locsy, labelsy = plt.yticks(pos, ylabels)
     plt.setp(labelsy, fontsize = 14)
     ax.set_ylim(ymin = -0.1, ymax = num*0.5+0.5)
     ax.grid(color = 'g', linestyle = ':')
     ax.xaxis_date()
     #rule = rrulewrapper(WEEKLY, interval=1)
     rule = rrulewrapper(WEEKLY, interval=1)
     loc = RRuleLocator(rule)
     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.title(title)
     plt.savefig(filename)
Example #12
0
def plot_temperature_roomsche_twingraph(logfile, room_sche, t, pinterval, pstep, oat, room_zt, room_tsa):
    
    fig = plt.figure()   
#     tfig = fig.add_subplot(111)
#     rsfig = tfig.twinx()    
    rsfig = fig.add_subplot(111)
    tfig = rsfig.twinx()
        
    ind = t # np.arange(len(room_sche[0]))    
    width = 0.02
#     num_room = len(room_sche)
    colors = ('r', 'g', 'b', 'y')
    t_labels = ('R1', 'R2', 'R3', 'R4')
    labels = ('R1', 'R2', 'R3', 'R4')
#     t_labels = ('LRLC', 'LRHC', 'HRLC', 'HRHC')
#     labels = ('LRLC', 'LRHC', 'HRLC', 'HRHC')

    inputd = []
    for i in xrange(len(room_sche)):        
        inputd.append(room_sche[i])        
    data = np.array(inputd)     
    bottom = np.vstack((np.zeros((data.shape[1],), dtype=data.dtype),
                        np.cumsum(data, axis=0)[:-1]))
    
    for dat, col, lab, bot in zip(data, colors, labels, bottom):
        plt.bar(ind, dat, width, color=col, label=lab, bottom=bot)
    
    tfig.plot(ind, oat, 'k', label='Outdoor')
    for i in xrange(len(room_zt)):   
        tfig.plot(ind, room_zt[i], colors[i], label=t_labels[i])        
    tfig.plot(ind, [21]*len(ind), 'k--', label='Comfort Bounds')
    tfig.plot(ind, [23]*len(ind), 'k--')
    tfig.grid(True)
    tfig.set_ylabel("Temperature (Celcius)")
     
    rsfig.axes.set_yticks([])
    rsfig.set_xlabel("Scheduling Periods")
    rsfig.set_ylabel("# of Meetings")
    
    handles, labels = tfig.get_legend_handles_labels()
    fontP = FontProperties()
    fontP.set_size('small')
    rsfig.legend(handles, labels, ncol=2, loc='best', prop=fontP)
           
    ymdhFmt = mdates.DateFormatter('%Y-%m-%d %H:%M')
    rule_1 = rrulewrapper(_getPlotRule((int)(pinterval)), interval=(int)(pstep)) 
    loc_1 = RRuleLocator(rule_1)
    rsfig.xaxis.set_major_locator(loc_1)    
    rsfig.xaxis.set_major_formatter(ymdhFmt)
    datemin = datetime(min(t).year, min(t).month, min(t).day, min(t).hour, min(t).minute) 
    datemax = datetime(max(t).year, max(t).month, max(t).day, max(t).hour, max(t).minute)
    rsfig.set_xlim(datemin, datemax)  
     
    fig.autofmt_xdate()
     
    plt.savefig('Output\\'+ logfile +'_temperature_ralloc.png')
#     plt.show()
    plt.close(fig)
    print "Done!"
Example #13
0
def CreateGanttChart(my_dic, first, last):
    """
        Create gantt charts with matplotlib
        Give file name.
    """

    pos = np.arange(0.5, (len(my_dic) * 0.5) + 0.5, 0.5)
    fig = plt.figure(figsize=(100, 30))
    ax = fig.add_subplot(111)
    cont = 0

    for item in my_dic.items():
        cont = cont + 1
        n = len(item[1]['end_date'])
        for counter in range(0, n):

            curr_barh = ax.barh(((cont - 1) * 0.5) + 0.5,
                                item[1]['width'][counter],
                                left=item[1]['pos'][counter],
                                height=0.2,
                                align='center',
                                color='#80aaff',
                                alpha=0.8)[0]

            text = item[1]['label'][counter]
            # Center the text vertically in the bar
            yloc = curr_barh.get_y() + (curr_barh.get_height() / 2.0)

            ax.text(item[1]['pos'][counter] +
                    (item[1]['width'][counter]) / 2.0,
                    yloc,
                    text,
                    fontsize=9,
                    horizontalalignment='center',
                    verticalalignment='center',
                    color='white',
                    weight='bold',
                    clip_on=True)

    locsy, labelsy = plt.yticks(pos, my_dic.keys())
    plt.setp(labelsy, fontsize=10)
    ax.set_xlabel('Hours')
    ax.set_xticks(np.arange(np.floor(first), np.ceil(last), 1))
    ax.set_ylim(ymin=-0.05, ymax=len(my_dic.keys()) * 0.5 + 0.5)
    ax.grid(color='g', linestyle=':')
    rule = rrulewrapper(WEEKLY, interval=1)
    loc = RRuleLocator(rule)

    # formatter = DateFormatter("%d-%b")

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

    ax.invert_yaxis()
    fig.autofmt_xdate()

    fig.tight_layout(rect=[0.027, 0.069, 0.984, 0.981], h_pad=0.2, w_pad=0.2)
    plt.savefig('gantt.svg')
    plt.show()
Example #14
0
def cleanup_axis_datetime(axis, rule=None):
    if rule is None:
        rule = rrulewrapper(SECONDLY, interval=1)
    loc = RRuleLocator(rule)
    fmt = DateFormatter('%M:%S')
    axis.set_major_locator(loc)
    axis.set_major_formatter(fmt)
    return axis
Example #15
0
    def __drawPlots(self, counter, **kwargs):

        import datetime

        if kwargs['rrulewrapperFrequency'] == 'DAILY':
            rrulewrapperFrequency = DAILY
        elif kwargs['rrulewrapperFrequency'] == 'MONTHLY':
            rrulewrapperFrequency = MONTHLY
        elif kwargs['rrulewrapperFrequency'] == 'YEARLY':
            rrulewrapperFrequency = YEARLY

        rule = rrulewrapper(rrulewrapperFrequency, interval = kwargs['rrulewrapperInterval'])
        loc = RRuleLocator(rule)
        formatter = DateFormatter('%Y/%m/%d')

        plt.style.use("seaborn-whitegrid")
        fig, ax = plt.subplots()

        keys = counter.keys()
        if len(keys) == 1:
            dates = [datetime.date(*[int(item) for item in date.split('-')]) for date in counter['total']['dates']]
            counts = counter['total']['counts']
            plt.plot_date(dates, counts, linestyle = '-', label = 'total')

        else:
            if kwargs['includeTotal']:
                dates = [datetime.date(*[int(item) for item in date.split('-')]) for date in counter['total']['dates']]
                counts = counter['total']['counts']
                plt.plot_date(dates, counts, linestyle = '-', label = 'total')
            for key in sorted(keys):
                if key == 'total':
                    continue
                dates = [datetime.date(*[int(item) for item in date.split('-')]) for date in counter[key]['dates']]
                counts = counter[key]['counts']
                plt.plot_date(dates, counts, linestyle = '-', label = key)

        plt.title('project = \'%s\', componentType = \'%s\' -- Generated on %s' % (kwargs['project'], kwargs['componentType'], kwargs['startTime']))
        plt.xlabel('Date [a.u.]')
        plt.ylabel('Frequency [a.u.]')
        plt.legend()

        ax.xaxis.set_major_locator(loc)
        ax.xaxis.set_major_formatter(formatter)

        # if kwargs['lowerDate'] != None:
        #     plt.gca().set_xlim(left = datetime.date(*[int(item) for item in kwargs['lowerDate'].split('-')]))
        # if kwargs['upperDate'] != None:
        #     plt.gca().set_xlim(right = datetime.date(*[int(item) for item in kwargs['upperDate'].split('-')]))

        if kwargs['savePath'][-4:] == '.pdf':
            plt.savefig(kwargs['savePath'])
        elif kwargs['savePath'][-4:] == '.png':
            plt.savefig(kwargs['savePath'], dpi = 150)
        if kwargs['saveJson']:
            counter['kwargs'] = kwargs
            import json
            with open(kwargs['savePath'][0:-4] + '.json', 'w') as file:
                json.dump(counter, file, sort_keys = True, indent = 4, separators = (',', ': '))
Example #16
0
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()
Example #17
0
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)
Example #18
0
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()
Example #19
0
def plotTemperatureNAirMassZoom(pinterval, pstep, t, OT, ZT1, TSA1, ASA1, ZT2,
                                TSA2, ASA2, start, end):

    #         ymdhFmt = mdates.DateFormatter('%H:%M')
    ymdhFmt = mdates.DateFormatter('%Y-%m-%d %H:%M')

    rc('mathtext', fontset='stixsans')

    fig = plt.figure()
    ztfig = fig.add_subplot(111)

    ztfig.plot(t, ZT1, 'k--', label='T (S)')
    ztfig.set_xlabel("Scheduling Period", fontsize=12)
    ztfig.set_ylabel("Temperature ($^\circ$C)", fontsize=12)
    #         ztfig.set_ylim(ymin=-2, ymax=maxT+5)
    ztfig_fontP = FontProperties()
    ztfig_fontP.set_size(13)
    #option 1:
    #         ztfig_fontP.set_weight('bold')
    ztfig_handles, ztfig_labels = ztfig.get_legend_handles_labels()
    #         ztfig.legend(ztfig_handles, ztfig_labels, loc='best', prop=ztfig_fontP)
    ztfig.legend(ztfig_handles,
                 ztfig_labels,
                 loc='best',
                 ncol=3,
                 prop=ztfig_fontP)
    #option 2:
    #         box = ztfig.get_position()
    #         ztfig.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
    #         ztfig.legend(loc='upper center', bbox_to_anchor=(0.4, 1.05), ncol=3, prop=ztfig_fontP)
    # #         ztfig.legend(loc='upper center', bbox_to_anchor=(0.5, 1.15), fancybox=True, shadow=False, ncol=3, prop=ztfig_fontP)

    ztfig_rule_1 = rrulewrapper(_getPlotRule((int)(pinterval)),
                                interval=(int)(pstep))
    ztfig_loc_1 = RRuleLocator(ztfig_rule_1)
    ztfig.xaxis.set_major_locator(ztfig_loc_1)
    ztfig.xaxis.set_major_formatter(ymdhFmt)
    ztfig_datemin = datetime(
        min(t).year,
        min(t).month,
        min(t).day,
        min(t).hour,
        min(t).minute)
    ztfig_datemax = datetime(
        max(t).year,
        max(t).month,
        max(t).day,
        max(t).hour,
        max(t).minute)
    ztfig.set_xlim(ztfig_datemin, ztfig_datemax)
    ztfig.grid(True)

    fig.autofmt_xdate()
    plt.tight_layout()

    #         plt.savefig('Output\\2_LRHC_1600_400dpi.png', dpi=400)
    plt.show()
 def build(self, filename, title):
     '''builds the chart from self.objects'''
     #determine the min and max latitude across all objects
     overall_minlat = min([x[2] for x in self.objects])
     overall_maxlat = max([x[3] for x in self.objects])
     print('overall minmax: {} {}'.format(overall_minlat, overall_maxlat))
     lat_height = overall_maxlat - overall_minlat
     height_multiplier = 2.0
     num = len(self.objects)
     #pos = np.arange(0.5, lat_height, 0.5)
     fig_height = height_multiplier * lat_height
     fig = plt.figure(figsize=(20, fig_height))
     ax = fig.add_subplot(111)
     #ylabels = [float('%.4g' % x) for x in np.arange(overall_minlat, overall_maxlat, 0.5)]
     #ylabels = ylabels.extend(float('%.4g' % overall_maxlat))
     ylabels = np.linspace(overall_minlat,
                           overall_maxlat,
                           num=int(lat_height * height_multiplier),
                           endpoint=True)
     ylabels = [float('%.4g' % x) for x in ylabels]
     pos = [float(x) - overall_minlat for x in ylabels]
     for obj in self.objects:
         starttime, endtime, minlat, maxlat, uid, color = obj
         start = matplotlib.dates.date2num(starttime)
         end = matplotlib.dates.date2num(endtime)
         element_height = (maxlat - minlat)
         yposition = (minlat - overall_minlat)
         ax.barh(yposition,
                 end - start,
                 left=start,
                 height=element_height,
                 align='edge',
                 edgecolor='darkorange',
                 color=color,
                 alpha=0.5)
     locsy, labelsy = plt.yticks(pos, ylabels)
     plt.setp(labelsy, fontsize=14)
     #plt.gca().invert_yaxis()
     ax.set_ylim(ymin=0.0, ymax=lat_height)
     ax.grid(color='g', linestyle=':')
     ax.xaxis_date()
     #rule = rrulewrapper(WEEKLY, interval=1)
     rule = rrulewrapper(MONTHLY, interval=1)
     loc = RRuleLocator(rule)
     formatter = DateFormatter("%Y-%m-%d")
     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.title(title)
     plt.savefig(filename)
Example #21
0
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()
Example #22
0
def draw(data: Data):
    available_colors = [c for c in matplotlib.colors.TABLEAU_COLORS]
    colors = {}
    print("PIDs found:")
    for pid in data.list_pids():
        l = data.get_measures(pid)
        m = l[0]
        if m.cmd not in colors:
            i = len(colors) % len(available_colors)
            c = available_colors[i]
            colors[m.cmd] = c
        print(f"- {m.pid} {colors[m.cmd]} {m.cmd}")

    cpu_ax = pyplot.subplot(2, 1, 1)
    cpu_ax.title.set_text("CPU in percent")
    cpu_ax.set_ylabel("cpu%")
    mem_ax = pyplot.subplot(2, 1, 2, sharex=cpu_ax)
    mem_ax.title.set_text("Memory in percent")
    mem_ax.set_ylabel("memory%")
    mem_ax.set_xlabel("datetime")

    # tick every 5th easter
    rule = rrulewrapper(YEARLY, byeaster=1, interval=5)
    loc = RRuleLocator(rule)
    formatter = DateFormatter("%m/%d/%y")
    mem_ax.xaxis.set_major_locator(loc)
    mem_ax.xaxis.set_major_formatter(formatter)
    mem_ax.xaxis.set_tick_params(rotation=30, labelsize=10)
    cpu_ax.xaxis.set_visible(False)

    handles = []
    for pid in data.list_pids():
        l = data.get_measures(pid)
        cmd = l[0].cmd
        color = colors[cmd]
        handles.append(matplotlib.patches.Patch(color=color, label=pid))
        dates = [p.date for p in l]
        cpu = [p.cpu for p in l]
        mem = [p.mem for p in l]
        cpu_ax.plot_date(dates,
                         cpu,
                         linestyle="-",
                         marker="",
                         color=color,
                         label=cmd)
        mem_ax.plot_date(dates,
                         mem,
                         linestyle="-",
                         marker="",
                         color=color,
                         label=cmd)

    mem_ax.legend(handles=handles)
    pyplot.show()
def test_RRuleLocator_close_minmax():
    # if d1 and d2 are very close together, rrule cannot create
    # reasonable tick intervals; ensure that this is handled properly
    rrule = mdates.rrulewrapper(dateutil.rrule.SECONDLY, interval=5)
    loc = mdates.RRuleLocator(rrule)
    d1 = datetime.datetime(year=2020, month=1, day=1)
    d2 = datetime.datetime(year=2020, month=1, day=1, microsecond=1)
    expected = [
        '2020-01-01 00:00:00+00:00', '2020-01-01 00:00:00.000001+00:00'
    ]
    assert list(map(str, mdates.num2date(loc.tick_values(d1, d2)))) == expected
Example #24
0
def _config_plot(days_interval,
                 minutes_interval,
                 start_date,
                 end_date,
                 x_label,
                 yLabel,
                 titulo,
                 lim_y,
                 max_var,
                 interval_yticker,
                 figsize,
                 dias_corridos=0):
    ax = plt.gca()
    plt.xlim(start_date, end_date)
    plt.ylim(lim_y[0], lim_y[1])
    plt.xlabel(x_label, fontsize=20)
    plt.ylabel(yLabel, fontsize=20)
    plt.title(f'{titulo} [{dias_corridos} Dias]', fontsize=20)
    plt.grid(True)

    ax.yaxis.set_major_locator(ticker.MultipleLocator(interval_yticker))

    rule = rrulewrapper(DAILY, interval=days_interval)
    minor_rule = rrulewrapper(MINUTELY, interval=minutes_interval)
    legenda_tag = []
    loc = RRuleLocator(rule)
    formatter = DateFormatter('%d-%m-%Y')
    minor_loc = RRuleLocator(minor_rule)
    minor_formatter = DateFormatter('%H:%M')
    if (days_interval < 2):
        ax.xaxis.set_major_locator(loc)
        ax.xaxis.set_major_formatter(formatter)
        ax.xaxis.set_tick_params(which='major', rotation=90, pad=60)

        ax.xaxis.set_minor_locator(minor_loc)
        ax.xaxis.set_minor_formatter(minor_formatter)
        ax.xaxis.set_tick_params(which='minor', rotation=90)
    else:
        ax.xaxis.set_major_locator(loc)
        ax.xaxis.set_major_formatter(formatter)
        ax.xaxis.set_tick_params(which='major', rotation=90, pad=0)
Example #25
0
 def _configure_xaxis(self, _ax):
     # 将 x 轴设为日期时间格式
     _ax.xaxis_date()
     rule = mdates.rrulewrapper(mdates.DAILY, interval=1)
     loc = mdates.RRuleLocator(rule)
     formatter = mdates.DateFormatter('%d %b')
     _ax.xaxis.set_major_locator(loc)
     _ax.xaxis.set_major_formatter(formatter)
     xlabels = _ax.get_xticklabels()
     plt.setp(xlabels, rotation=30, fontsize=9)
     # 日期的排列根据图像的大小自适应
     self.fig.autofmt_xdate()
Example #26
0
    def _configure_xaxis(self):
        ''''x axis'''
        # make x axis date axis
        self._axes.xaxis_date()

        rule = mdates.rrulewrapper(mdates.HOURLY, interval=3)
        loc = mdates.RRuleLocator(rule)
        formatter = mdates.DateFormatter("%y-%m-%d %H:%M:%S")

        self._axes.xaxis.set_major_locator(loc)
        self._axes.xaxis.set_major_formatter(formatter)
        xlabels = self._axes.get_xticklabels()
        plt.setp(xlabels, rotation=30, size='x-small')
Example #27
0
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
Example #28
0
def SetDateAxis(ax, form):
    if "year" in form:
        formatter = DateFormatter('%Y')
        rule = rrulewrapper(YEARLY, byeaster=1, interval=5)
        loc = RRuleLocator(rule)
    if "month" in form:
        formatter = DateFormatter('%Y-%m')
        loc = MonthLocator(interval=4)

    ax.xaxis.set_major_locator(loc)
    ax.xaxis.set_major_formatter(formatter)
    plt.xticks(rotation=20)
    plt.tight_layout()
Example #29
0
def run(subreddits):
    for subreddit in subreddits:
        c = Counter()
        fName = f'{subreddit}/{subreddit}.csv'
        if not os.path.isfile(fName) : continue
        print (subreddit)
        # open('test.csv','rU'), encoding='utf-8', engine='c'
        records = pd.read_csv(fName, names = ["author","subreddit", "id", "title", "time","score","num_comments","domain","url",'selftext'],engine='c')
        #Count on same day
        for index, row in records.iterrows():
            if index==0: continue #Headers
            c[ datetime.strptime(row["time"],'%Y-%m-%d %H:%M:%S').strftime("%y/%m/%d")] += 1
        #Convert to numpy
        temp = np.array([ [datetime.strptime(r,"%y/%m/%d"), c[r]] for r in c ] )
        temp = temp[temp[:,0].argsort()] #Sort

        #Start plot
        plt.style.use('ggplot')
        fig, ax = plt.subplots()
        ax.xaxis_date()
        ax.xaxis.set_major_locator(RRuleLocator(rrulewrapper(MONTHLY, bymonthday=15)))
        ax.xaxis.set_major_formatter(DateFormatter('%m/%d/%Y'))
        ax.xaxis.set_tick_params(rotation=90, labelsize=8)

        #Plot with smoothness
        # dateTimeToNumber = np.vectorize( lambda dt: (dt - datetime(1970,1,1)).total_seconds() )
        # numberToDateTime = np.vectorize( lambda num: datetime.utcfromtimestamp(num)  )
        # numeric_x = dateTimeToNumber(temp[:,0]  )
        # f = interp1d( numeric_x, temp[:,1] , kind='nearest')
        # x_range = np.linspace(numeric_x[0], numeric_x[-1],500)
        # y_smooth= f(x_range)
        # plt.plot ( numberToDateTime(x_range) ,y_smooth, "b",linewidth=2 )
        
        #Plot Lines
        # plt.plot( temp[:,0],temp[:,1], "o-", markersize=1, linewidth=0.5 )
        
        #Plot bars
        plt.bar( temp[:,0],temp[:,1], width=1 )

        #Draw region >2018
        # ax.fill_between(temp[:,0], 0, temp[:,1].max(), where=temp[:,0]>datetime(2018,1,1), facecolor='green', alpha=0.25)
        #Axes and labels
        # plt.xlabel('mm/dd/yy')
        plt.ylabel('# Posts')
        plt.title(f'# of Posts related with latinos/hispanic in r/{subreddit}')
        plt.grid(True)
        plt.tight_layout()
        
        #Plot
        # plt.show()
        plt.savefig(f'figs/{subreddit}.png')
Example #30
0
    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)
Example #31
0
 def get_locator(self, dmin, dmax):
     # get the recommended tick locations from AutoDateLocator, then
     # go one level more numerous ticks
     self.old_refresh()
     major_freq = self._freq
     tick_locations = self._old_locator.tick_values(dmin, dmax)
     tick_dt = tick_locations[1] - tick_locations[0]
     # tick_dt is in terms of days. convert it to major_freq
     dt = self._freqconverter[major_freq](tick_dt)
     # Check each possible interval of self._freq
     minor_interval = 0
     minor_interval_index = 0
     minor_freq = major_freq
     for i, interval in enumerate(self.intervald[major_freq]):
         if dt - .5 > interval:
             minor_interval = interval
             minor_interval_index = i
         else:
             break
     if minor_interval == 0:
         # Then we need to go to the next smaller time interval
         minor_freq = self.next_freq(major_freq)
         minor_interval = self.intervald[minor_freq][-3]
         minor_interval_index = len(self.intervald[minor_freq]) - 3
     byranges = [None, 1, 1, 0, 0, 0, None]
     for i, freq in enumerate(self._freqs):
         if freq != minor_freq:
             byranges[i] = None
         else:
             break
     minor_freq_index = self.freq_to_index(minor_freq)
     byranges[minor_freq_index] = self._byranges[minor_freq_index]
     if minor_freq != self._freqs[-1]:
         _, bymonth, bymonthday, byhour, byminute, bysecond, _ = byranges
         rrule = rrulewrapper(minor_freq,
                              interval=minor_interval,
                              dtstart=dmin,
                              until=dmax,
                              bymonth=bymonth,
                              bymonthday=bymonthday,
                              byhour=byhour,
                              byminute=byminute,
                              bysecond=bysecond)
         locator = RRuleLocator(rrule, self.tz)
     else:
         locator = MicrosecondLocator(minor_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
    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)
Example #33
0
    def plotOutdoor(self, pinterval, pstep, oatdat, pcfg,
                    Tinit, Toccmin, ToccminRange, Toccmax, ToccRange, xtime, oat):
        
        t = xtime
        OT = oat.values()
        min_occ1 = [21] * len(t)
        max_occ1 = [23] * len(t)
        min_occ2 = [22] * len(t)
        max_occ2 = [24] * len(t)
        
        ymdhFmt = mdates.DateFormatter('%Y-%m-%d %H:%M')
        
        fig = plt.figure()
        ztfig = fig.add_subplot(111)         
#         ztfig.set_title(" \nOutdoorTemp: " + oatdat + "\nInitial Temp: [" + str(Tinit) + 'C]\n Occ Zone Temp Bound: [' +
#                         str(Toccmin+ToccminRange) + 'C $\leq$ T $\leq$ ' + str(Toccmax-ToccRange) + ']\n UnOcc Zone Temp Bound: [' +
#                         str(Toccmin) + 'C $\leq$ T $\leq$ ' + str(Toccmax) +
#                         'C]', fontsize=12)
            
        ztfig.plot(xtime, OT, 'r-', label='Outdoor Temperature')
        ztfig.plot(xtime, min_occ1, 'g-', label='Min Occupied Zone Temperature 21C')        
        ztfig.plot(xtime, max_occ1, 'b-', label='Max Occupied Zone Temperature 23C')
        ztfig.plot(xtime, min_occ2, 'g--', label='Min Occupied Zone Temperature 22C')        
        ztfig.plot(xtime, max_occ2, 'b--', label='Max Occupied Zone Temperature 24')
        ztfig.set_xlabel("Scheduling Period",fontsize=12)
        ztfig.set_ylabel("Celcius",fontsize=12)
        
        handles, labels = ztfig.get_legend_handles_labels()
        fontP = FontProperties()
        fontP.set_size('small')
        ztfig.legend(handles, labels, loc='best', prop=fontP)  
        
        ztfig_rule_1 = rrulewrapper(self._getPlotRule((int)(pinterval)), interval=(int)(pstep)) 
        ztfig_loc_1 = RRuleLocator(ztfig_rule_1)
        ztfig.xaxis.set_major_locator(ztfig_loc_1)
        ztfig.xaxis.set_major_formatter(ymdhFmt)
        ztfig_datemin = datetime(min(t).year, min(t).month, min(t).day, min(t).hour, min(t).minute) 
        ztfig_datemax = datetime(max(t).year, max(t).month, max(t).day, max(t).hour, max(t).minute)
        ztfig.set_xlim(ztfig_datemin, ztfig_datemax)        
        
        fig.autofmt_xdate()
        plt.tight_layout()
        
        plt.savefig('Output\\OutdoorTemperature_' + datetime.now().strftime('%Y_%m_%d_%H_%M_%S_%f') +'.png')        
#         plt.show()   
        plt.close(fig)
        
        
Example #34
0
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()
Example #35
0
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
Example #36
0
 def test_RRuleLocator( self ):
    """Test RRuleLocator"""
    fname = self.outFile( "RRuleLocator_bounds.png" )
    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( fname )
    self.checkImage( fname )
def printTimeSeries(
        CDF4Variable,
        timeseries,
        fileName='/Users/viniciussantino/Documents/PhD/Code/figure1.pdf',
        labelsArray=['CNDC', 'TEMP', 'PRES_REL', 'DOX1_3', 'CPHL', 'TURB']):
    timeData = num2date(timeseries[-1, :],
                        CDF4Variable.variables['TIME'].units)

    fig1 = figure(num=None,
                  figsize=(25, 20),
                  dpi=80,
                  facecolor='w',
                  edgecolor='k')

    for i in range(0, len(labelsArray)):
        ax1 = subplot((len(labelsArray) + 1) / 2, 2, i + 1)
        plot(timeData, timeseries[i, :])
        title(  #DF4Variable.title + '\n' +
            #'%0.2f m depth\n'% TEMP.sensor_depth +
            #'location: lat=%0.2f; lon=%0.2f' % (CDF4Variable.variables['LATITUDE'][:],
            #                                    CDF4Variable.variables['LONGITUDE'][:])
            CDF4Variable.variables[labelsArray[i]].long_name)
        xlabel(CDF4Variable.variables['TIME'].long_name)
        ylabel(CDF4Variable.variables[labelsArray[i]].units)

        rule = rrulewrapper(DAILY, interval=60)
        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()

    fig1.savefig(fileName,
                 dpi=None,
                 facecolor='w',
                 edgecolor='w',
                 orientation='portrait',
                 papertype=None,
                 format='png',
                 transparent=True,
                 bbox_inches=None,
                 pad_inches=0.1,
                 frameon=None)
Example #38
0
def plot_data(dates, code_stock):
    # Plot the data
    ax = plt.gca()
    code_stockplot = {}
    for code, stock in sorted(code_stock.items()):
        stock = code_stock[code]
        stockplot = StockPlot(code)
        line, = ax.plot_date(dates,
                             stock.prices,
                             label=code,
                             linestyle='solid',
                             marker='None',
                             picker=5)
        stockplot.plot_line = line
        color = line.get_color()
        line, = ax.plot_date(stock.buy_dates,
                             stock.buy_rates,
                             marker='o',
                             markersize=5,
                             color=color)
        stockplot.buy_line = line
        line, = ax.plot_date(stock.sell_dates,
                             stock.sell_rates,
                             marker='s',
                             markersize=5,
                             color=color)
        stockplot.sell_line = line
        line = ax.axhline(y=stock.cost_price, color=color, alpha=0.7)
        stockplot.cost_line = line
        code_stockplot[code] = stockplot
    # Format dates on x-axis.
    rule = rrulewrapper(MONTHLY, interval=2)
    loc = RRuleLocator(rule)
    date_format = "%d-%b-%y"
    formatter = DateFormatter(date_format)
    ax.xaxis.set_major_locator(loc)
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30, labelsize=10)
    # Other settings - tight axes, grid, title.
    ax.set_xlim(dates[0], dates[-1])
    ax.grid(b=True, axis='y')
    ax.set_title('Stock Price History')
    return code_stockplot
Example #39
0
    def do_plot(self, dates, values, x_fit, y_fit, min_level, save_as):

        rule = mdates.rrulewrapper(mdates.WEEKLY)
        loc = mdates.RRuleLocator(rule)
        formatter = mdates.DateFormatter('%d/%m/%y')

        fig, ax = plt.subplots()
        plt.plot_date(dates, values)
        plt.plot(x_fit, y_fit, 'b-')
        plt.plot([x_fit[0], x_fit[-1]], [min_level, min_level], 'r-')

        plt.ylim(300, 700)

        plt.grid(True)

        plt.xticks(rotation=90)
        ax.xaxis.set_major_locator(loc)
        ax.xaxis.set_major_formatter(formatter)

        plt.title('Helium Fill Level')
        plt.text(dates.min() + 1,
                 425,
                 'by fit: ' +
                 str("{:3.2f}".format(self.slope) + str(' units/day')),
                 horizontalalignment='left',
                 verticalalignment='center',
                 fontsize=12)
        plt.text(dates.min() + 1,
                 375,
                 'est. date: ' + self.fill_date_str,
                 horizontalalignment='left',
                 verticalalignment='center',
                 fontsize=12)
        #ax.xaxis.set_tick_params(rotation=30, labelsize=10)

        #        now = datetime.now().date()
        #        now_year = now.year
        #        now_month = now.month
        #        now_day = now.day

        fig.savefig(self.data_file[0:10] + '_' + save_as,
                    bbox_inches='tight',
                    dpi=400)
Example #40
0
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()
    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' )
Example #41
0
    def __showChart(self, chartData):

        figure1 = pyplot.figure()
        ax = figure1.add_subplot(111)
        for i in range(len(chartData.getYLabels())):
            startDate, endDate = chartData.getTaskDates()[
                chartData.getYLabels()[i]]
            ax.barh((i * 0.5) + 0.5,
                    endDate - startDate,
                    left=startDate,
                    height=0.3,
                    align='center',
                    edgecolor='lightblue',
                    color='blue',
                    alpha=1)

        iLen = len(chartData.getYLabels())
        pos = np.arange(0.5, iLen * 0.5 + 0.5, 0.5)
        locsy, labelsy = pyplot.yticks(pos, chartData.getYLabels())
        pyplot.setp(labelsy, fontsize=8)
        ax.set_ylim(bottom=-0.1, top=iLen * 0.5 + 0.5)
        ax.grid(color='lightblue', linestyle=':')
        ax.xaxis_date()

        ax.xaxis.set_major_locator(
            RRuleLocator(rrulewrapper(MONTHLY, interval=4)))
        ax.xaxis.set_major_formatter(DateFormatter("%d-%b-%Y"))
        pyplot.setp(ax.get_xticklabels(), rotation=30, fontsize=8)

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

        ax.invert_yaxis()
        figure1.autofmt_xdate()

        #  Works only on Windows.
        #    pyplot.get_current_fig_manager().window.state('zoomed')
        pyplot.show()
Example #42
0
    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
Example #43
0
# 	# 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()
Example #44
0
  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() )
    return locator
Example #45
0
# 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()
Example #46
0
def main():
    import optparse
    from sonet.lib import SonetOption
    p = optparse.OptionParser(
        usage="usage: %prog [options] input_file output_file",
        option_class=SonetOption)
    p.add_option('-v', action="store_true", dest="verbose", default=False,
                 help="Verbose output")
    p.add_option('-i', '--ignorecols', action="store", dest="ignorecols",
                 help="Columns numbers of the source file to ignore"
                      "(comma separated and starting from 0)")
    p.add_option('-I', '--id', action="store", dest="id_col", type="int",
                 help="Id column number (starting from 0)", default=0)
    p.add_option('-o', '--onlycols', action="store", dest="onlycols",
                 help="Select only this set of columns" + \
                      "(comma separated and starting from 0)")
    p.add_option('-p', '--percentages', action="store_true", dest="perc",
                 help="Use percentages instead of absolute value")
    p.add_option('-w', '--window', action="store", dest="window", type=int,
                 help="Collapse days")
    p.add_option('-S', '--sliding', action="store", dest="smooth", type=int,
                 help="Sliding window")
    p.add_option('--exclude-less-than', action="store",
                 dest="excludelessthan", type=int,
                 help="Exclude lines with totals (or dic if -d option is used) " + \
                      "smaller than this parameter")
    p.add_option('--exclude-more-than', action="store",
                 dest="excludemorethan", type=int,
                 help="Exclude lines with totals (or dic if -d option is used) " + \
                      "greater than this parameter")
    p.add_option('-s', '--start', action="store",
        dest='start', type="yyyymmdd", metavar="YYYYMMDD", default=None,
        help="Look for revisions starting from this date")
    p.add_option('-e', '--end', action="store",
        dest='end', type="yyyymmdd", metavar="YYYYMMDD", default=None,
        help="Look for revisions until this date")
    p.add_option('-d', '--dic', action="store_true", dest="dic", default=False,
                 help="Calculate percentage over dic column instead of total")
    opts, files = p.parse_args()

    if len(files) != 2:
        p.error("Wrong parameters")
    if opts.verbose:
        logging.basicConfig(stream=sys.stderr,
                            level=logging.DEBUG,
                            format='%(asctime)s %(levelname)s %(message)s',
                            datefmt='%Y-%m-%d %H:%M:%S')
    csv_reader = csv.reader(open(files[0]), delimiter="\t")
    onlycols = None
    ignorecols = None
    if opts.onlycols:
        onlycols = [int(x) for x in opts.onlycols.split(",")]
    if opts.ignorecols:
        ignorecols = [int(x) for x in opts.ignorecols.split(",")]

    # content contains all the csv file
    content = [row for row in csv_reader]

    # CSV header, only of interesting columns
    header = [x for x in _gen_data(content[0], opts.id_col,
                                   ignorecols, onlycols)]

    # Creates a matrix (list) with percentages of the occurrencies of every
    # category. Don't count id, total, text, ignore columns. If onlycols is set
    # consider only them.
    mat = []
    timestamps = []
    totals = []
    tot_index = -2
    if opts.dic:
        tot_index = -4

    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()
Example #47
0
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()
Example #48
0
"""
Show how to use an rrule instance to make a custom date ticker - here
we put a tick mark on every 5th easter

See https://moin.conectiva.com.br/DateUtil for help with rrules
"""
from matplotlib.matlab import *
from matplotlib.dates import YEARLY, DateFormatter, \
     rrulewrapper, RRuleLocator, drange
import datetime

# tick every 5th easter
rule = rrulewrapper(YEARLY, byeaster=1, interval=5)
loc = RRuleLocator(rule)
formatter = DateFormatter('%m/%d/%y')
date1 = datetime.date( 1952, 1, 1 )
date2 = datetime.date( 2004, 4, 12 )
delta = datetime.timedelta(days=100)

dates = drange(date1, date2, delta)
s = rand(len(dates)) # make up some random y values


ax = subplot(111)
plot_date(dates, s)
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(formatter)
labels = ax.get_xticklabels()
set(labels, rotation=30, fontsize=10)

# 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()
    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)")
Example #51
0
    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