当前位置: 首页>>代码示例>>Python>>正文


Python dates.date2num函数代码示例

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


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

示例1: calc_bar_colors

    def calc_bar_colors(measure, end_date, is_planning):
        """Returns calculated bars. The bars are aggregated from
        measure_status_moments from sub measures.

        ** measure can also be a measure_collection. It uses the
           status_moment function only.
        """
        measure_bar = []
        measure_colors = []
        measure_status_moments = measure.measure_status_moments(
            end_date=end_date, is_planning=is_planning)
        for msm_index, msm in enumerate(measure_status_moments):
            # drawing enddate: "infinity" or next status moment
            if msm_index == len(measure_status_moments) - 1:
                msm_end_date = end_date
            else:
                if is_planning:
                    msm_end_date = measure_status_moments[
                        msm_index + 1].planning_date
                else:
                    msm_end_date = measure_status_moments[
                        msm_index + 1].realisation_date

            if is_planning:
                begin = msm.planning_date
            else:
                begin = msm.realisation_date
            date_length = date2num(msm_end_date) - date2num(begin)

            measure_bar.append((date2num(begin), date_length))
            measure_colors.append(msm.status.color.html)
        return measure_bar, measure_colors
开发者ID:swinkels,项目名称:lizard-measure,代码行数:32,代码来源:views.py

示例2: plot_chart

def plot_chart(*tfs, norm=True, realtime=True, markers = None):
    import matplotlib.dates as mdt
    fig, ax = plt.subplots()
    if len(tfs) == 1 and norm is True:
        y = [(mdt.date2num(candle.DateTime), candle.Open, candle.Close, candle.High, candle.Low) for candle in tfs[0].container]
        candlestick(ax, y, width=0.4, colorup='r', colordown='b')
        ax.xaxis_date()
        plt.title(tfs[0].symbol + " chart")
        if markers is not None:
            marker_y, marker_x = [], []
            for elem in tfs[0].container:
                if elem.DateTime in markers:
                    marker_y.append(.5*(elem.Open+elem.Close))
                    marker_x.append(mdt.date2num(elem.DateTime))
            plt.plot(marker_x, marker_y, 'gD')
    else:
        for tf in tfs:
            if realtime is True:
                x = tf.get_Time_list()
            else:
                x = range(len(tf))
            y = np.array(tf.get_C_list())
            if norm is True:
                y -= y.min()
                y /= y.max()
            plt.plot(x, y, label=tf.symbol)
            plt.title("Charts graph")
    plt.legend(loc='upper center', shadow=True)
    plt.xlabel("Time")
    plt.ylabel("Price")
    plt.grid()
    plt.show()
开发者ID:866,项目名称:PyFx,代码行数:32,代码来源:plotting.py

示例3: plotAotiHour

def plotAotiHour():

    fig = plt.figure(figsize=(18, 5))
    rect = fig.patch
    rect.set_facecolor("white")
    df = pd.read_csv("urban-country/aoti_pm25.csv", sep=",", header=0)
    df = df[df["date"] >= 20140514]
    df = df[df["date"] <= 20140527]
    df["date"] = df["date"].astype(str)
    df["hour"] = df["hour"].astype(str)
    dateAndTime = pd.to_datetime(df["date"] + df["hour"], format="%Y%m%d%H")
    aoti = df["奥体中心"].tolist()
    ts_aoti = Series(aoti, index=dateAndTime)
    plot = ts_aoti.plot(linestyle="-", color="black", marker="8", markersize=4, label=u"奥体中心")
    time = dt.datetime(2014, 05, 17, 10)
    df = df[df["date"] == "20140517"]
    df = df[df["hour"] == "10"]
    value = df.iloc[0, 3]
    print mdates.date2num(time), value
    plt.annotate(
        u"aoti24",
        xy=(mdates.date2num(time), value),
        xytext=(30, 20),
        textcoords="offset points",
        arrowprops=dict(arrowstyle="-|>"),
    )
    plt.show()
开发者ID:wuliangradi,项目名称:PM25,代码行数:27,代码来源:beijingPM25.py

示例4: parse_file_to_dict

def parse_file_to_dict(data_dict, samp_int_dict, file, counter, format=None,
                       verbose=False, ignore_links=False):
    from matplotlib.dates import date2num
    if ignore_links and os.path.islink(file):
        print("Ignoring symlink: %s" % (file))
        return counter
    try:
        stream = read(file, format=format, headonly=True)
    except:
        print("Can not read %s" % (file))
        return counter
    s = "%s %s" % (counter, file)
    if verbose:
        sys.stdout.write("%s\n" % s)
        for line in str(stream).split("\n"):
            sys.stdout.write("    " + line + "\n")
    else:
        sys.stdout.write("\r" + s)
        sys.stdout.flush()
    for tr in stream:
        _id = tr.getId()
        data_dict.setdefault(_id, [])
        data_dict[_id].append([date2num(tr.stats.starttime),
                               date2num(tr.stats.endtime)])
        try:
            samp_int_dict.\
                setdefault(_id, 1. / (24 * 3600 * tr.stats.sampling_rate))
        except ZeroDivisionError:
            print("Skipping file with zero samlingrate: %s" % (file))
            return counter
    return (counter + 1)
开发者ID:Ciack404,项目名称:obspy,代码行数:31,代码来源:scan.py

示例5: handle

    def handle(self, *args, **options):
        # Get user join dates
        User = get_user_model()
        datetimes = User.objects.values_list('date_joined', flat=True) \
                                .order_by('date_joined')
        dates = map(lambda d: d.date(), datetimes)

        # Get some auxilliary values
        min_date = date2num(dates[0])
        max_date = date2num(dates[-1])
        days = max_date - min_date + 1

        # Initialize X and Y axes
        x = np.arange(min_date, max_date + 1)
        y = np.zeros(days)

        # Iterate over dates, increase registration array
        for date in dates:
            index = int(date2num(date) - min_date)
            y[index] += 1
        y_sum = np.cumsum(y)

        # Plot
        plt.plot_date(x, y_sum, xdate=True, ydate=False, ls='-', ms=0, color='#16171E')
        plt.fill_between(x, 0, y_sum, facecolor='#D0F3FF')
        plt.title('Studentenportal: Registrierte Benutzer')
        plt.rc('font', size=8)
        if options['save']:
            plt.savefig(options['save'])
        else:
            plt.show()
开发者ID:AwaisKazi,项目名称:web,代码行数:31,代码来源:plot_user_registrations.py

示例6: plot_trend_graph_all_tests

 def plot_trend_graph_all_tests(self, save_path='', file_name='_trend_graph.png'):
     time_format1 = '%d-%m-%Y-%H:%M'
     time_format2 = '%Y-%m-%d-%H:%M'
     for test in self.tests:
         test_data = test.results_df[test.results_df.columns[2]].tolist()
         test_time_stamps = test.results_df[test.results_df.columns[3]].tolist()
         start_date = test_time_stamps[0]
         test_time_stamps.append(self.end_date + '-23:59')
         test_data.append(test_data[-1])
         float_test_time_stamps = []
         for ts in test_time_stamps:
             try:
                 float_test_time_stamps.append(matdates.date2num(datetime.strptime(ts, time_format1)))
             except:
                 float_test_time_stamps.append(matdates.date2num(datetime.strptime(ts, time_format2)))
         plt.plot_date(x=float_test_time_stamps, y=test_data, label=test.name, fmt='.-', xdate=True)
         plt.legend(fontsize='small', loc='best')
     plt.ylabel('MPPS/Core (Norm)')
     plt.title('Setup: ' + self.name)
     plt.tick_params(
         axis='x',
         which='both',
         bottom='off',
         top='off',
         labelbottom='off')
     plt.xlabel('Time Period: ' + start_date[:-6] + ' - ' + self.end_date)
     if save_path:
         plt.savefig(os.path.join(save_path, self.name + file_name))
         if not self.setup_trend_stats.empty:
             (self.setup_trend_stats.round(2)).to_csv(os.path.join(save_path, self.name +
                                                                   '_trend_stats.csv'))
         plt.close('all')
开发者ID:hhaim,项目名称:trex-core,代码行数:32,代码来源:TRexDataAnalysis.py

示例7: generate_count

def generate_count(counts):
    import matplotlib
    from matplotlib.pyplot import figure, show
    from matplotlib.dates import DateFormatter

    print len(counts)

    fig = figure()
    matplotlib.rcParams['font.size'] = 8.0
    ax = fig.add_subplot(111)
    ax.plot_date(counts.keys(),counts.values(), markersize=2)
    ax.set_title('Nb of actions per second')
    ax.set_ylabel('Nb of actions')
    ax.fmt_xdata = DateFormatter('%H:%M:%S')

    timestamp = counts.keys()[0]
    start = datetime.datetime(timestamp.year, timestamp.month, timestamp.day,7,0,0)
    end = datetime.datetime(timestamp.year, timestamp.month, timestamp.day,16,1,0)
    ax.set_xlim( date2num(start), date2num(end))

    fig.autofmt_xdate()
    fig.subplots_adjust(left=.05, bottom=.2, right=.95, top=.9)
    filename = 'action_count.png'
    fig.set_size_inches(10., 3.)

    fig.savefig(filename)
    return filename
开发者ID:okrane,项目名称:framework,代码行数:27,代码来源:algo_action.py

示例8: demand_analysis

 def demand_analysis(self,date=None,type='day',option=None):
     import calendar
     
     signal = 'Total_KW' # se estima la demanda PPP y PP en base a la estimacion del KW hecha a partir de AWH, BWH y CWH
     
     period = {'day':{'t1':date.replace(hour=0,minute=0,second=0,microsecond=0),\
                      't2':date.replace(hour=18,minute=00,second=00),\
                      't3':date.replace(hour=23,minute=00,second=00),\
                      't4':date.replace(hour=23,minute=59,second=59)}} 
     
     
     PPP     =   list(Measurements.objects.filter(Q(user= self.user),Q(sensor=Sensors.objects.get(pk=self.sensor_id)),\
                                 Q(datetimestamp__gte = period[type]['t1'], datetimestamp__lte =   period[type]['t2']) | Q(datetimestamp__gte = period[type]['t3'],datetimestamp__lte=period[type]['t4'])).extra(select=sql_extra_pairs[signal]['sql']).\
                                 order_by('datetimestamp').\
                                 values('datetimestamp',sql_extra_pairs[signal]['extra']))
     
     #valor maximo parcialmente presente en punta diario (consumo)
     PP    =   list(Measurements.objects.filter(Q(user= self.user),Q(sensor=Sensors.objects.get(pk=self.sensor_id)),\
                                 Q(datetimestamp__gte = period[type]['t2'], datetimestamp__lte =   period[type]['t3'])).extra(select=sql_extra_pairs[signal]['sql']).\
                                 order_by('datetimestamp').\
                                 values('datetimestamp',sql_extra_pairs[signal]['extra']))
     
     #exit if there are no data available
     if len(PP)==0 or len(PPP)==0:
         return {'PP':{'Value':0,'datetimestamp':date,'ave':0,'html':''},\
                 'PPP':{'Value':0,'datetimestamp':date,'ave':0,'html':''}}
     
     power_analisis =   {'PP':{'Value':0,'datetimestamp':date,'ave':0,'html':''},\
                      'PPP':{'Value':0,'datetimestamp':date,'ave':0,'html':''}}
     #busqueda del maximo PP
     for r in range(len(PP)-1):
         delta_r =   (date2num(PP[r+1]['datetimestamp'])-date2num(PP[r]['datetimestamp']))*24
         power_r =   float(PP[r+1][signal])/delta_r
         if power_r > power_analisis['PP']['Value']:
             power_analisis['PP']['Value'] = power_r
             power_analisis['PP']['datetimestamp'] = PP[r+1]['datetimestamp']
     
     power_r=0 #reset
     #busqueda del maximo PP
     for r in range(len(PPP)-1):
         delta_r =   (date2num(PPP[r+1]['datetimestamp'])-date2num(PPP[r]['datetimestamp']))*24
         power_r =   float(PPP[r+1][signal])/delta_r
         if power_r > power_analisis['PPP']['Value']:
             power_analisis['PPP']['Value'] = power_r
             power_analisis['PPP']['datetimestamp'] = PPP[r+1]['datetimestamp']
     
     #preparacion de datos, formatos, ganancias etc.
     power_analisis['PPP']['Value']  = power_analisis['PPP']['Value']*ganancias_dict['Total_KW']['gain']
     power_analisis['PP']['Value']   = power_analisis['PP']['Value']*ganancias_dict['Total_KW']['gain']
     
     power_analisis['PP']['html']    = pretty_print(power_analisis['PP']['Value'],label=['KW','MW'])    
     power_analisis['PPP']['html']   = pretty_print(power_analisis['PPP']['Value'],label=['KW','MW'])
     
     #se calcula la potencia promedio en base a la energia consumida en un periodo de tiempo y se divide por ese tiempo 
     
     power_analisis['PPP']['ave']    = self.calculo_consumo(date=date,type='day',option=['energy_by_time_range','PPP'])['Total']['Value']
     power_analisis['PP']['ave']     = self.calculo_consumo(date=date,type='day',option=['energy_by_time_range','PP'])['Total']['Value']
     
     #print power_analisis
     return power_analisis
开发者ID:jrebolledo,项目名称:energyspy,代码行数:60,代码来源:Elec_Tools.py

示例9: calc_strong_motion

def calc_strong_motion():
    files1 = '/media/PBO/archive/20?[7890]/CX/PATCX/B[HL]Z.D/*.???'
    files2 = '/media/platte/Data/IPOC/raw_PATCX_2011_B-Z/*/*.???'
    acs = []
    vels = []
    for fname in glob(files1) + glob(files2):
        ms = read(fname)
        for tr in ms:
            if tr.stats.endtime - tr.stats.starttime < 1000:
                ms.remove(tr)
                continue
            tr.trim(tr.stats.starttime + 10, tr.stats.endtime - 10)
            tr.stats.filter = ''
            tr.detrend()
            tr.filter('highpass', freq=0.2)
        ms.merge(fill_value=0)
        if len(ms) == 0:
            continue
        tr = ms[0]
        t = tr.stats.starttime + (tr.stats.endtime - tr.stats.starttime) / 2
        maxi = np.max(np.abs(tr.data))
        if 'BH' in fname:
            vels.append((t, maxi))
        elif 'BL' in fname:
            acs.append((t, maxi))
        else:
            print 'wrong filename: ', fname
    dates_vel, vels = zip(*sorted(vels, key=itemgetter(0)))
    dates_ac, acs = zip(*sorted(acs, key=itemgetter(0)))
    np.savez('/home/richter/Results/IPOC/maxima_PATCX_5s.npz',
             dates_ac=date2num(dates_ac), dates_vel=date2num(dates_vel),
             vel=vels, ac=acs)
开发者ID:iceseismic,项目名称:sito,代码行数:32,代码来源:calc_strong_motion.py

示例10: getcodar_ctl_id

def getcodar_ctl_id(model_option,url,datetime_wanted):
    if model_option=='1':
        dtime=open_url(url+'?time')
        dd=dtime['time']  
        #print "This option has data from "+str(num2date(dd[0]+date2num(datetime.datetime(2009, 1, 1, 0, 0))))+" to "+str(num2date(dd[-1]+date2num(datetime.datetime(2009, 1, 1, 0, 0))))           
        print 'This option has data from '+dd[0].strftime("%B %d, %Y")+' to '+dd[-1] .strftime("%B %d, %Y")
        id=datetime_wanted-date2num(datetime.datetime(2009, 1, 1, 0, 0))
        id=str(int(id))
    if model_option=='6':
        dtime=open_url(url+'?time')
        dd=dtime['time']
        ddd=[]
        #print 'This option has data from '+dd[0].strftime("%B %d, %Y")+' to '+dd[-1] .strftime("%B %d, %Y")
        id=datetime_wanted-date2num(datetime.datetime(2006, 1, 1, 0, 0))
        id=str(int(id))
    else:
        dtime=open_url(url+'?time')
        dd=dtime['time']
        ddd=[]
        for i in list(dtime['time']):
            i=round(i,7)
            ddd.append(i)
        
        #print "This option has data from "+str(num2date(dd[0]+date2num(datetime.datetime(2001, 1, 1, 0, 0))))+" to "+str(num2date(dd[-1]+date2num(datetime.datetime(2001, 1, 1, 0, 0)))) 
        #print 'This option has data from '+num2date(dd[0]).strftime("%B %d, %Y")+' to '+num2date(dd[-1]).strftime("%B %d, %Y")          
        id=ml.find(np.array(ddd)==round(datetime_wanted-date2num(datetime.datetime(2001, 1, 1, 0, 0)),7))
        for i in id:
          id=str(i) 
        #print 'codar id is  '+id
    return id    
开发者ID:xhx509,项目名称:drifter_header,代码行数:30,代码来源:sst_function.py

示例11: getemolt_sensor

def getemolt_sensor(mindtime1,maxdtime1,i_mindepth,i_maxdepth,site2,mindtime,maxdtime):
	  #According to the conditions to select data from "emolt_sensor"
	 
	  url2="http://gisweb.wh.whoi.edu:8080/dods/whoi/emolt_sensor?emolt_sensor.SITE,emolt_sensor.TIME_LOCAL,emolt_sensor.YRDAY0_LOCAL,emolt_sensor.TEMP,emolt_sensor.DEPTH_I&emolt_sensor.TIME_LOCAL>="+str(mindtime1)+"&emolt_sensor.TIME_LOCAL<="\
        +str(maxdtime1)+"&emolt_sensor.DEPTH_I>="+str(i_mindepth)+"&emolt_sensor.DEPTH_I<="+str(i_maxdepth)+site2
	  try:   
	           dataset1=open_url(url2)
	  except:
	           print 'Sorry, '+url2+' not available' 
	           sys.exit(0)
	  emolt_sensor=dataset1['emolt_sensor']
	  try:   
	          sites2=list(emolt_sensor['SITE'])
	  except:
	          print "'Sorry, According to your input, here are no value. please check it! ' "
	          sys.exit(0) 
	  #sites2=list(emolt_sensor['SITE'])
	  time=list(emolt_sensor['TIME_LOCAL'])
	  yrday0=list(emolt_sensor['YRDAY0_LOCAL'])
	  temp=list(emolt_sensor['TEMP'])
	  depth1=list(emolt_sensor['DEPTH_I'])
	
	
	  time1,temp1,yrday01,sites1,depth=[],[],[],[],[]
	  for m in range(len(time)):
	      #if mindtime<=dt.datetime.strptime(str(time[m]),'%Y-%m-%d')<=maxdtime:
	      if date2num(mindtime)<=yrday0[m]%1+date2num(dt.datetime.strptime(str(time[m]),'%Y-%m-%d'))<=date2num(maxdtime):
	      #if str(time[m])=='2012-01-01':
	        temp1.append(temp[m])
	        yrday01.append(yrday0[m]%1+date2num(dt.datetime.strptime(str(time[m]),'%Y-%m-%d')))
	        sites1.append(sites2[m])
	        time1.append(date2num(dt.datetime.strptime(str(time[m]),'%Y-%m-%d'))) 
	        depth.append(depth1[m])
	  #print len(temp1)     
	  return time1,yrday01,temp1,sites1,depth,
开发者ID:jian-cui,项目名称:pyocean,代码行数:35,代码来源:hx.py

示例12: PlotEntropyMapDate

def PlotEntropyMapDate(dataset,L):

    f = open('aapl.csv','r')
    f.readline()

    data = []
    dataL = []
    counter = 0
    for lines in f:
        ls = lines.split(',')
        data.append((DT.datetime.strptime(ls[0], "%d-%b-%y"),float(ls[-1])))
        if counter%1000 == 0:
            dataL.append((DT.datetime.strptime(ls[0], "%d-%b-%y"),float(ls[-1])))
        counter = counter + 1

    x = [date2num(date) for (date, value) in data]
    y = [value for (date, value) in data]
    z = [EntropyFilter(Entropy([x,y], ii, L)) for ii in range(len(x))]

    xL = [date2num(date) for (date, value) in dataL]
    yL = [value for (date, value) in dataL]

    fig = plt.figure()

    graph = fig.add_subplot(111)
    graph.set_xticks(xL)
    graph.set_xticklabels([date.strftime("%d-%b-%y") for (date, value) in dataL])

    X = np.array(x)
    Y = np.array(y)
    Z = np.array(z)

    plt.scatter(X, Y, s = Z*10, c = Z)
    plt.show()
开发者ID:HACP,项目名称:EntropyMap,代码行数:34,代码来源:Entropylib.py

示例13: main

def main(sta1, sta2, filterid, components, mov_stack=1, show=True, outfile=None):
    db = connect()
    components_to_compute = get_components_to_compute(db)
    maxlag = float(get_config(db,'maxlag'))
    cc_sampling_rate = float(get_config(db,'cc_sampling_rate'))
    start, end, datelist = build_movstack_datelist(db)
    # mov_stack = get_config(db,"mov_stack")
 
   
    plt.figure(figsize=(16,16))
    sta1 = sta1.replace('.','_')
    sta2 = sta2.replace('.','_')
    if sta2 > sta1: # alphabetical order filtering!
        pair = "%s:%s"%(sta1,sta2)
        
        print("New Data for %s-%s-%i-%i"%(pair,components,filterid, mov_stack))
        format = "matrix"
        nstack, stack_total = get_results(db,sta1,sta2,filterid,components,datelist,mov_stack, format=format)
        # vmax = scoreatpercentile(np.abs(stack_total[np.isnan(stack_total)==False]) , 98)
        # for i in range(stack_total.shape[0]):
            # if not np.all( np.isnan(stack_total[i,:])):
                # print np.max(stack_total[i,:])
                # stack_total[i,:] /= np.max(stack_total[i,:])
        # stack_total /= np.max(stack_total, axis=0)
        xextent = (date2num(start), date2num(end),-maxlag,maxlag)
        ax = plt.subplot(111)
        plt.imshow(stack_total.T, extent=xextent, aspect="auto",interpolation='none',origin='lower',cmap='seismic',
                vmin=-1e-2,vmax=1e-2)
        plt.ylabel("Lag Time (s)")
        plt.axhline(0,lw=0.5,c='k')
        plt.grid()

        ax.xaxis.set_major_locator( YearLocator() )
        ax.xaxis.set_major_formatter(  DateFormatter('%Y-%m') )

        # ax.xaxis.set_minor_locator( MonthLocator(interval=2) )
        # ax.xaxis.set_minor_formatter(  DateFormatter('%Y-%m-%d') )
        
        lag = 120
        plt.ylim(-lag,lag)
        plt.title('%s : %s'%(sta1,sta2))
        name = '%i.%s_%s.png'%(filterid,sta1,sta2)

        #~ plt.savefig('interfero_publi.png',dpi=300)
        # plt.figure()
        # maxx = np.argmax(stack_total, axis=0)
        # plt.plot(maxx)
        
        if outfile:
            if outfile.startswith("?"):
                pair = pair.replace(':','-')
                outfile = outfile.replace('?', '%s-%s-f%i-m%i' % (pair,
                                                                  components,
                                                                  filterid,
                                                                  mov_stack))
            outfile = "interferogram " + outfile
            print("output to:", outfile)
            plt.savefig(outfile)
        if show:
            plt.show()
开发者ID:guillermowfl,项目名称:MSNoise,代码行数:60,代码来源:interferogram.py

示例14: add_plot

    def add_plot(self, sources):
        "Add a subplot to this widget displaying all of the signals in names"
        
        rows = len(self.plots) + 1
        for i, plot in enumerate(self.plots):
            plot.change_geometry(rows, 1, i+1)
            plot.label_outer()
        
        new_plot = LiveSubplot(self.find_source, self, rows, 1, rows)
        td = datetime.timedelta(seconds=self.timescale)
        
        now = datetime.datetime.utcnow()
        new_plot.set_xbound(mdates.date2num(now - td),
                            mdates.date2num(now))
        if len(sources) == 1:
            new_plot.set_title(sources[0]["name"])

        for descr in sources:
            new_plot.add_signal(descr["identifier"],
                                color=descr["color"],
                                style=descr["style"])

        self.figure.add_subplot(new_plot)
        self.plots.append(new_plot)

        return new_plot
开发者ID:kagelump,项目名称:calsol,代码行数:26,代码来源:LiveGraph.py

示例15: output_chart

def output_chart(chart, option):
    fig, ax = chart[:2]
    #ax.autoscale_view()

    xmin = date2num(datetime.fromtimestamp(option['view_start']))
    xmax = date2num(datetime.fromtimestamp(option['view_end']))
    ax.get_xaxis().set_view_interval(xmin, xmax, ignore=True)

    xmin, xmax = ax.get_xaxis().get_view_interval()
    ymin, ymax = ax.get_yaxis().get_view_interval()

    args = dict(color='black', linewidth=2)
    ax.add_artist(Line2D((xmin, xmax), (ymin, ymin), **args))
    ax.add_artist(Line2D((xmax, xmax), (ymin, ymax), **args))
    args = dict(color='black', linewidth=1)
    ax.add_artist(Line2D((xmin, xmax), (ymax, ymax), **args))
    ax.add_artist(Line2D((xmin, xmin), (ymin, ymax), **args))

    from matplotlib.dates import MinuteLocator

    locator = MinuteLocator(interval=int((option['view_end'] - option['view_start']) / 60 / 14))
    ax.get_xaxis().set_major_locator(locator)
    locator = MinuteLocator(interval=int((option['view_end'] - option['view_start']) / 60 / 14 / 2))
    ax.get_xaxis().set_minor_locator(locator)

    ax.get_xaxis().grid(which='both', color='#999999',
                        linestyle=':', lw=0.3)
    ax.get_yaxis().grid(which='both', color='#999999',
                        linestyle=':', lw=0.3)

    output = StringIO()
    plt.savefig(output, format='png', dpi=300)

    return output.getvalue()
开发者ID:jianingy,项目名称:supervised-trader,代码行数:34,代码来源:__init__.py


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