def drawCity(self): """ 作图 :return: """ pl.title("pm25 / time " + str(self.numMonitors) + "_monitors")# give plot a title pl.xlabel('time')# make axis labels pl.ylabel('pm2.5') self.fill_cityPm25List() for monitorStr in self.cityPm25List: data = np.loadtxt(StringIO(monitorStr), dtype=np.dtype([("t", "S13"),("v", float)])) datestr = np.char.replace(data["t"], "T", " ") t = pl.datestr2num(datestr) v = data["v"] pl.plot_date(t, v, fmt="-o") pl.subplots_adjust(bottom=0.3) # pl.legend(loc=4)#指定legend的位置,读者可以自己help它的用法 ax = pl.gca() ax.fmt_xdata = pl.DateFormatter('%Y-%m-%d %H:%M:%S') pl.xticks(rotation=70) # pl.xticks(t, datestr) # 如果以数据点为刻度,则注释掉这一行 ax.xaxis.set_major_formatter(pl.DateFormatter('%Y-%m-%d %H:%M')) pl.grid() pl.show()# show the plot on the screen
def plot_diurnal(headers): """ Diurnal plot of the emails, with years running along the x axis and times of day on the y axis. """ xday = [] ytime = [] print 'making diurnal plot...' for h in iterview(headers): if len(h) > 1: try: s = h[1][5:].strip() x = dateutil.parser.parse(s) except ValueError: print print marquee(' ERROR: skipping ') print h print marquee() continue timestamp = mktime( x.timetuple()) # convert datetime into floating point number mailstamp = datetime.fromtimestamp(timestamp) xday.append(mailstamp) # Time the email is arrived # Note that years, month and day are not important here. y = datetime(2010, 10, 14, mailstamp.hour, mailstamp.minute, mailstamp.second) ytime.append(y) plot_date(xday, ytime, '.', alpha=.7) xticks(rotation=30) return xday, ytime
def globtime(self): mat = np.load('globcummat.npz') jd1 = pl.datestr2num('2003-01-01') jd2 = pl.datestr2num('2012-12-31') jdvec = np.arange(jd1, jd2) figpref.current() pl.close(1) pl.figure(1) pl.plot_date(jdvec, mat['northmat'][10, :], 'r-', alpha=0.5, label="Northern hemisphere") pl.plot_date(jdvec, mat['southmat'][10, :], 'b-', alpha=0.5, label="Southern hemisphere") pl.ylim(0, 1) pl.legend(loc='lower right') pl.savefig('figs/liege/glob_time.pdf', transparent=True, bbox_inches='tight')
def draw_graph(): # Создание графика: # Преобразуем даты в числовой формат (для дальнейшего форматирования тикеров осей) register_matplotlib_converters() x_data_float = matplotlib.dates.date2num( report['date'].astype(dtype='datetime64')) # Вызовем subplot явно, чтобы получить экземпляр класса AxesSubplot, # из которого будем иметь доступ к осям axes = pylab.subplot(1, 1, 1) # Пусть в качестве меток по оси X выводится только месяц.год axes.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%m.%y")) # Изменим локатор, используемый по умолчанию locator = matplotlib.dates.AutoDateLocator(minticks=5, maxticks=12) axes.xaxis.set_major_locator(locator) # Отобразим данные pylab.plot_date(x_data_float, report['value'], fmt="b-") plt.title(f'{category_name}\n{region}\nс {date_min} по {date_max}') plt.plot(x_data_float, report['value']) plt.show()
def get_spot_history(self, instance_type, start=None, end=None, plot=False): if not utils.is_iso_time(start): raise exception.InvalidIsoDate(start) if not utils.is_iso_time(end): raise exception.InvalidIsoDate(end) hist = self.conn.get_spot_price_history(start_time=start, end_time=end, instance_type=instance_type, product_description="Linux/UNIX") if not hist: raise exception.SpotHistoryError(start,end) dates = [ utils.iso_to_datetime_tuple(i.timestamp) for i in hist] prices = [ i.price for i in hist ] maximum = max(prices) avg = sum(prices)/len(prices) log.info("Current price: $%.2f" % hist[-1].price) log.info("Max price: $%.2f" % maximum) log.info("Average price: $%.2f" % avg) if plot: try: import pylab pylab.plot_date(pylab.date2num(dates), prices, linestyle='-') pylab.xlabel('date') pylab.ylabel('price (cents)') pylab.title('%s Price vs Date (%s - %s)' % (instance_type, start, end)) pylab.grid(True) pylab.show() except ImportError,e: log.error("Error importing pylab:") log.error(str(e)) log.error("please check that matplotlib is installed and that:") log.error(" $ python -c 'import pylab'") log.error("completes without error")
def mains_energy(): import psycopg2 conn = psycopg2.connect('dbname=gateway') cursor = conn.cursor() meter_name = 'ug04' date_start = '20111001' date_end = '20111201' query = """select * from midnight_rider where name = '%s' and ip_address = '192.168.1.200' and date >= '%s' and date <= '%s' order by date """ % (meter_name, date_start, date_end) shniz = cursor.execute(query) shniz = cursor.fetchall() dates = [] watthours = [] for s in shniz: dates.append(s[0]) watthours.append(s[2]) import pylab pylab.plot_date(dates,watthours) pylab.grid() pylab.show()
def plotdepthtime(self, FontSize): """ plot depth against time """ pylab.plot_date(vector_epoch2datetime(self['etime']), self['depth'],'o') #pylab.title('Depth-time view') pylab.xlabel('time', fontsize=FontSize) pylab.ylabel('depth', fontsize=FontSize) pylab.gca().invert_yaxis()
def diurnalplot(headers): """ diurnal plot of the emails, with years running along the x axis and times of day on the y axis. """ xday = [] ytime = [] for header in headers: #print(header['Date'], header['From'], email.header.decode_header(header['Subject'])) if len(header['Date']) > 1: #print('Message %s\n' % (h)) #timestamp = mktime(dateutil.parser.parse(h)) #mailstamp = datetime.fromtimestamp(timestamp) mailstamp = dateutil.parser.parse(header['Date']) xday.append(mailstamp) # Time the email is arrived # Note that years, month and day are not important here. yyy = datetime(2010, 10, 14, mailstamp.hour, mailstamp.minute, mailstamp.second) ytime.append(yyy) #print("%s" % (mailstamp)) #print("%s" % (y)) plot_date(xday, ytime, '.', alpha=.7) xticks(rotation=30) return xday, ytime
def load_graph(): pylab.figure(num = 1, figsize=(6, 3)) ax = pylab.gca() #get the current graphics region #Set the axes position with pos = [left, bottom, width, height] ax.set_position([.1,.15,.8,.75]) if zoom == False: print "zoom = False" pylab.plot_date(date, kiln_temp, 'r-', linewidth = 1) if zoom == True: print "zoom = True" zoom_date = date[(len(date)-zoom_level):] zoom_kiln_temp = kiln_temp[(len(kiln_temp)-zoom_level):] pylab.plot(zoom_date, zoom_kiln_temp, 'r-', linewidth = 1) pylab.title(r"Kiln Temperature") ax.xaxis.set_major_formatter(DateFormatter('%H:%M')) xlabels = ax.get_xticklabels() #pylab.setp(xlabels,'rotation', 45, fontsize=10) ylabels = ax.get_yticklabels() #pylab.setp(ylabels,fontsize=10) pylab.savefig('graph.png') pylab.close(1) graph = os.path.join("","graph.png") graph_surface = pygame.image.load(graph).convert() screen.blit(graph_surface, (100,30)) """
def plotmagtime(self, FontSize): """ plot magnitude versus time """ import pylab as plt plt.plot_date(self.time, self.mag) #plt.title('Mag-time view') plt.xlabel('time', fontsize=FontSize) plt.ylabel('magnitude', fontsize=FontSize)
def get_spot_history(self, instance_type, start=None, end=None, plot=False): if not utils.is_iso_time(start): raise exception.InvalidIsoDate(start) if not utils.is_iso_time(end): raise exception.InvalidIsoDate(end) hist = self.conn.get_spot_price_history(start_time=start, end_time=end, instance_type=instance_type, product_description="Linux/UNIX") if not hist: raise exception.SpotHistoryError(start, end) dates = [utils.iso_to_datetime_tuple(i.timestamp) for i in hist] prices = [i.price for i in hist] maximum = max(prices) avg = sum(prices) / len(prices) log.info("Current price: $%.2f" % hist[-1].price) log.info("Max price: $%.2f" % maximum) log.info("Average price: $%.2f" % avg) if plot: try: import pylab pylab.plot_date(pylab.date2num(dates), prices, linestyle='-') pylab.xlabel('date') pylab.ylabel('price (cents)') pylab.title('%s Price vs Date (%s - %s)' % (instance_type, start, end)) pylab.grid(True) pylab.show() except ImportError, e: log.error("Error importing pylab:") log.error(str(e)) log.error("please ensure matplotlib is installed and that:") log.error(" $ python -c 'import pylab'") log.error("completes without error")
def main(): Global.logdir = sys.argv[1] Global.account = sys.argv[2] Global.parameter = sys.argv[3] Global.t_start = datetime.strptime(sys.argv[4], "%Y%m%d%H%M") Global.t_end = datetime.strptime(sys.argv[5], "%Y%m%d%H%M") lines = lines_from_dir("192_168_1_2%s.log" % (Global.account,), Global.logdir) logs = meter_logs(lines) print "Site:", Global.logdir print "Meter:", Global.account print "Parameter:", Global.parameter print "Time Range:", Global.t_start.isoformat(' '), "to", Global.t_end.isoformat(' ') values = sorted([(el['Time Stamp'], el[Global.parameter]) for el in logs], key=lambda t: t[0]) print len(values) print "plotting..." pylab.figure() pylab.title("Site:%s, Meter: %s, Parameter: %s, Time Scale: %s to %s" % ( Global.logdir, Global.account, Global.parameter, Global.t_start, Global.t_end)) pylab.xlabel("Time") pylab.ylabel(Global.parameter) pylab.plot_date(*zip(*values), fmt='-') pylab.grid(True) pylab.savefig('%s_%s_%s_%s_%s' % ( Global.logdir, Global.account, Global.parameter, Global.t_start.strftime("%Y%m%d%H%M"), Global.t_end.strftime("%Y%m%d%H%M"))) pylab.show() print "done."
def plot_diurnal(headers): """ Diurnal plot of the emails, with years running along the x axis and times of day on the y axis. """ xday = [] ytime = [] print 'making diurnal plot...' for h in iterview(headers): if len(h) > 1: try: s = h[1][5:].strip() x = dateutil.parser.parse(s) except ValueError: print print marquee(' ERROR: skipping ') print h print marquee() continue timestamp = mktime(x.timetuple()) # convert datetime into floating point number mailstamp = datetime.fromtimestamp(timestamp) xday.append(mailstamp) # Time the email is arrived # Note that years, month and day are not important here. y = datetime(2010, 10, 14, mailstamp.hour, mailstamp.minute, mailstamp.second) ytime.append(y) plot_date(xday,ytime,'.',alpha=.7) xticks(rotation=30) return xday,ytime
def ForecastDraw(self): """ at the day-level :return: """ pl.title("aqi/time(day)")# give plot a title pl.xlabel('time')# make axis labels pl.ylabel('aqi') data = np.loadtxt(StringIO(self._xyArrayStr), dtype=np.dtype([("t", "S13"), ("v", float)])) datestr = np.char.replace(data["t"], "T", " ") t = dt.datestr2num(datestr) # k = pl.num2date(t) # k2 = dt.num2date(t) v = data["v"] if len(t) > 30: t = t[-30:] v = v[-30:] pl.plot_date(t, v, fmt="-o") self.polyfit(t, v) pl.subplots_adjust(bottom=0.3) # pl.legend(loc=4)#指定legend的位置,读者可以自己help它的用法 ax = pl.gca() ax.fmt_xdata = pl.DateFormatter('%Y-%m-%d %H:%M:%S') pl.xticks(rotation=70) # pl.xticks(t, datestr) # 如果以数据点为刻度,则注释掉这一行 ax.xaxis.set_major_formatter(pl.DateFormatter('%Y-%m-%d %H:%M')) # pl.xlim(('2016-03-09 00:00', '2016-03-12 00:00')) pl.grid() # 有格子 pl.show()# show the plot on the screen return self._forecast_Value
def plotStock(symbol, startDate, endDate): """returns a plot of stock (symbol) between startDate and endDate symbol: String, stock ticker symbol startDate, endDate = tuple(YYYY, MM, DD) """ company = symbol sYear, sMonth, sDay = startDate eYear, eMonth, eDay = endDate start = datetime(sYear, sMonth, sDay) end = datetime(eYear, eMonth, eDay) data = DataReader(company, "yahoo", start, end) closingVals = data["Adj Close"] #convert to matplotlib format dates = [i for i in data.index] dates = matplotlib.dates.date2num(dates) pylab.ylim([0, int(max(closingVals)*1.2)]) pylab.plot_date(dates, closingVals, label = symbol, xdate = True, ydate=False, linestyle = '-') pylab.legend() pylab.show()
def line_plot(data, out): """Turning ([key, ...], [value, ...]) into line graphs""" pylab.clf() pylab.plot_date(data[0], data[1], '-') pylab.savefig(out)
def plot_save(X, Y, title, filename): clf() xticks(rotation=90) suptitle(title) subplots_adjust(bottom=0.2) plot_date(X, Y, "k.") savefig(filename, dpi=600)
def plot_session_timeline(sessions,prefix=fname_prefix): offset = {'behop':1,'lwapp':2 } annot = {'behop':'b-*','lwapp':'r-*'} pylab.figure() for s in sessions: pylab.plot_date(matplotlib.dates.date2num([s['start'],s['end']]),[offset[s['type']],offset[s['type']]], annot[s['type']]) #pylab.plot([s['start'],s['end']],[offset[s['type']],offset[s['type']]], annot[s['type']]) pylab.xlim((STARTING_DAY,END_DAY)) pylab.ylim([0,3]) timespan = END_DAY - STARTING_DAY print "Total Seconds %d" % timespan.total_seconds() timeticks = [STARTING_DAY + timedelta(seconds=x) for x in range(0,int(timespan.total_seconds()) + 1, int(timespan.total_seconds()/4))] plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d-%H')) plt.gca().set_xticks(timeticks) #start = sessions[0]['start'] #dates = [(s['end'] - start).days for s in sessions] #print dates #plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d')) #tick_dates = [start + timedelta(days=i) for i in range(0,max(dates))] #plt.gca().set_xticks(tick_dates) pylab.savefig('%s_timeline' % (prefix))
def mains_energy(): import psycopg2 conn = psycopg2.connect('dbname=gateway') cursor = conn.cursor() meter_name = 'ug04' date_start = '20111001' date_end = '20111201' query = """select * from midnight_rider where name = '%s' and ip_address = '192.168.1.200' and date >= '%s' and date <= '%s' order by date """ % (meter_name, date_start, date_end) shniz = cursor.execute(query) shniz = cursor.fetchall() dates = [] watthours = [] for s in shniz: dates.append(s[0]) watthours.append(s[2]) import pylab pylab.plot_date(dates, watthours) pylab.grid() pylab.show()
def drawCity(self): """ 作图 :return: """ pl.title("pm25 / time " + str(self.numMonitors) + "_monitors") # give plot a title pl.xlabel('time') # make axis labels pl.ylabel('pm2.5') self.fill_cityPm25List() for monitorStr in self.cityPm25List: data = np.loadtxt(StringIO(monitorStr), dtype=np.dtype([("t", "S13"), ("v", float)])) datestr = np.char.replace(data["t"], "T", " ") t = pl.datestr2num(datestr) v = data["v"] pl.plot_date(t, v, fmt="-o") pl.subplots_adjust(bottom=0.3) # pl.legend(loc=4)#指定legend的位置,读者可以自己help它的用法 ax = pl.gca() ax.fmt_xdata = pl.DateFormatter('%Y-%m-%d %H:%M:%S') pl.xticks(rotation=70) # pl.xticks(t, datestr) # 如果以数据点为刻度,则注释掉这一行 ax.xaxis.set_major_formatter(pl.DateFormatter('%Y-%m-%d %H:%M')) pl.grid() pl.show() # show the plot on the screen
def plot_dwaf_data(realtime, file_name='data_plot.png', gauge=True): x = pl.date2num(realtime.date) y = realtime.q pl.clf() pl.figure(figsize=(7.5, 4.5)) pl.rc('text', usetex=True)# TEX fonts pl.plot_date(x,y,'b-',linewidth=1) pl.grid(which='major') pl.grid(which='minor') if gauge: pl.ylabel(r'Flow rate (m$^3$s$^{-1}$)') title = 'Real-time flow -- %s [%s]' % (realtime.station_id[0:6], realtime.station_desc) else: title = 'Real-time capacity -- %s [%s]' % (realtime.station_id[0:6], realtime.station_desc) pl.ylabel('Percentage of F.S.C') labeled_days = DayLocator(interval=3) ticked_days = DayLocator() dayfmt = DateFormatter('%d/%m/%Y') ax = pl.gca() ax.xaxis.set_major_locator(labeled_days) ax.xaxis.set_major_formatter(dayfmt) ax.xaxis.set_minor_locator(ticked_days) pl.xticks(fontsize=10) pl.yticks(fontsize=10) pl.title(title, fontsize=14) pl.savefig(file_name, dpi=100)
def work_1(): data_in = datetime(2010,6,24,8,00,0) data_fin = datetime(2010,6,24,22,00,0) #np.concatenate((dati,dati2)) dati = df.query_db('greenhouse.db','data',data_in,data_fin) Is = dati['rad_int_sup_solar'] lista_to_filter = df.smooht_Is(Is) Is_2 = df.smooth_value(Is,lista_to_filter) tra_P_M = mf.transpiration_P_M(Is_2,dati['rad_int_inf_solar'],0.64,2.96,((dati['temp_1']+dati['temp_2'])/2)+273.15,(dati['RH_1']+dati['RH_2'])/200) tra_weight = mf.transpiration_from_balance(dati['peso_balanca'],300,2260000) delta_peso = np.diff(dati['peso_balanca']) fr,lista_irr,lista_irr_free = mf.find_irrigation_point(delta_peso,dati['data']) lista_night = mf.remove_no_solar_point(dati['rad_int_sup_solar'],50) lista_no = list(set(lista_irr+ lista_night)) tran_weight,lista_yes = mf.transpiration_from_balance_irr(dati['peso_balanca'],300,2260000,lista_no) min_avg = 6 tra_weigh_avg,time_weight = df.avg2(tran_weight,lista_yes,min_avg) tra_P_M_avg,time_P_M = df.avg2(tra_P_M,lista_yes,min_avg) data_plot.plot_time_data_2_y_same_axis(dati['data'][time_P_M], tra_P_M_avg, 'tra Penman', tra_weigh_avg, 'trans weight') RMSE = df.RMSE(tra_P_M_avg, tra_weigh_avg) print "RMSE is", RMSE print "RRMSE is", df.RRMSE(RMSE, tra_weigh_avg) date = dati['data'][time_P_M].astype(object) dates= pylab.date2num(date) pylab.plot_date(dates,tra_weigh_avg,'rx')
def draw_domain(dom): n1 = "Wikisource_-_pages_%s.png"%dom fig = pylab.figure(1, figsize=(12,12)) ax = fig.add_subplot(111) pylab.clf() pylab.hold(True) pylab.grid(True) count = count_array[dom] pylab.fill_between(count[0][1], 0, count[0][0], facecolor="#ffa0a0")#red pylab.fill_between(count[4][1], 0, count[4][0], facecolor="#b0b0ff")#blue pylab.fill_between(count[3][1], 0, count[3][0], facecolor="#dddddd")#gray pylab.fill_between(count[2][1], 0, count[2][0], facecolor="#ffe867")#yellow pylab.fill_between(count[1][1], 0, count[1][0], facecolor="#90ff90")#green x = range(1) b1 = pylab.bar(x, x, color='#ffa0a0') b0 = pylab.bar(x, x, color='#dddddd') b2 = pylab.bar(x, x, color='#b0b0ff') b3 = pylab.bar(x, x, color='#ffe867') b4 = pylab.bar(x, x, color='#90ff90') pylab.legend([b1[0], b3[0], b4[0], b0[0], b2[0]],['not proofread','proofread','validated','without text','problematic'],loc=2, prop={'size':'medium'}) pylab.plot_date(count[0][1],pylab.zeros(len(count[0][1])),'k-' ) ax.xaxis.set_major_locator( pylab.YearLocator() ) ax.xaxis.set_major_formatter( pylab.DateFormatter('%Y-%m-%d') ) fig.autofmt_xdate() pylab.title("%s.wikisource.org"%dom, fontdict = { 'fontsize' : 'xx-large' } ) pylab.ylim(0) pylab.savefig(savepath+n1) n1 = "Wikisource_-_texts_%s.png"%dom pylab.figure(1, figsize=(12,12)) pylab.clf() pylab.hold(True) pylab.grid(True) count = count_array[dom] pylab.fill_between( rm29(dom,count[8][1]), 0,rm29(dom,count[8][0]), facecolor="#b0b0ff") pylab.fill_between( rm29(dom,count[7][1]), 0,rm29(dom,count[7][0]), facecolor="#ffa0a0") pylab.fill_between( rm29(dom,count[9][1]), 0,rm29(dom,count[9][0]), facecolor="#dddddd") x = range(1) b1 = pylab.bar(x, x, color='#b0b0ff') b2 = pylab.bar(x, x, color='#ffa0a0') if dom!='de': pylab.legend([b1[0],b2[0]],['with scans','naked'],loc=3, prop={'size':'medium'}) else: pylab.legend([b1[0],b2[0]],['with transclusion (PR2)','older system (PR1)'],loc=3, prop={'size':'medium'}) pylab.plot_date( rm29(dom,count[8][1]),pylab.zeros(len( rm29(dom,count[8][1]) )),'k-' ) ax.xaxis.set_major_locator( pylab.YearLocator() ) ax.xaxis.set_major_formatter( pylab.DateFormatter('%Y-%m-%d') ) fig.autofmt_xdate() pylab.title("%s.wikisource.org"%dom, fontdict = { 'fontsize' : 'xx-large' } ) pylab.ylim(0) pylab.savefig(savepath+n1)
def run(): # PLOT 1 ############## members = Attendee.objects.filter(membership_started__isnull=False, membership_ended__isnull=False) # PLOT 1 ############## members = Attendee.objects.filter(membership_started__isnull=False, membership_ended__isnull=False) print members.count() membership_durations = [ (member.membership_ended - member.membership_started).days / 356.0 for member in members] membership_durations.sort() for member in members: print member, (member.membership_ended - member.membership_started).days / 356.0 #pylab.hist(membership_durations, cumulative=True, normed=True) pylab.hist(membership_durations) pylab.title('Histogram of membership duration (years)') pylab.ylabel('Number of members') pylab.xlabel('Years a member') pylab.savefig('membership_duration_histogram.pdf') # PLOT 2 ############## guest_attendees = [] member_attendees = [] total_attendees = [] for meeting in Meeting.objects.all(): num_member_attendees = meeting.attendees.filter( membership_started__isnull=False, membership_ended__isnull=False).count() num_attendees_total = meeting.attendees.count() guest_attendees.append( (meeting.date, num_attendees_total - num_member_attendees)) member_attendees.append((meeting.date, num_member_attendees)) total_attendees.append((meeting.date, num_attendees_total)) pylab.figure() # pylab.plot_date(guest_attendees[0], guest_attendees[1]) # member_attendees, 'g-', # total_attendees, 'b-') pylab.title('Attendence rates over time') pylab.ylabel('Number of attendees') pylab.xlabel('Year') pylab.savefig('attendence_over_time.pdf')
def plotdepthtime(self, FontSize): """ plot depth against time """ import pylab as plt plt.plot_date(self.time, self.depth,'o') #plt.title('Depth-time view') plt.xlabel('time', fontsize=FontSize) plt.ylabel('depth', fontsize=FontSize) plt.gca().invert_yaxis()
def plot_sma(rpc,symbol,n=5, range=20 ): data = rpc.exec_tool('tools.ClientTools.simple_moving_average',symbol, n) sma,price, dates =zip(*data[:range]) #price = map(lambda x:x[1],data) dates = map(lambda x: datetime.strptime(str(x),DATEFORMAT),dates) ndates = pylab.date2num(dates) for ydata in [sma,price]: pylab.plot_date(ndates,ydata,'-')
def plotdepthtime(self, FontSize): """ plot depth against time """ pylab.plot_date(vector_epoch2datetime(self['etime']), self['depth'], 'o') #pylab.title('Depth-time view') pylab.xlabel('time', fontsize=FontSize) pylab.ylabel('depth', fontsize=FontSize) pylab.gca().invert_yaxis()
def test_single_date(): time1=[ 721964.0 ] data1=[ -65.54 ] fig = pylab.figure() pylab.subplot( 211 ) pylab.plot_date( time1, data1, 'o', color='r' ) pylab.subplot( 212 ) pylab.plot( time1, data1, 'o', color='r' ) fig.savefig( 'single_date' )
def plot_temp(self, tempVal, aver_temp, dateVal, title, xlabel="Days", ylabel="Temperature", label="Temperature"): pylab.title(title) pylab.xlabel(xlabel) pylab.ylabel(ylabel) pylab.plot_date(dateVal, tempVal, 'b-', label=label) pylab.plot_date([min(dateVal), max(dateVal)], [aver_temp, aver_temp], 'r-', label="Average t="+str(round(aver_temp,2))) pylab.grid(True) pylab.legend(loc=0) pylab.show()
def draw(domlist, index, func, max, tick, name, log=False): if not log: n1 = "Wikisource_-_%s.png" % name else: n1 = "Wikisource_-_%s.log.png" % name fig = pylab.figure(1, figsize=(7, 7)) ax = fig.add_subplot(111) pylab.clf() pylab.hold(True) pylab.grid(True) for dom in domlist: count = count_array[dom][index] if func: count = func(count, dom) if count: if not log: pylab.plot(count[1], count[0], '-', color=colors[dom], label=dom, linewidth=1.5) else: pylab.semilogy(count[1], count[0], '-', color=colors[dom], label=dom, linewidth=1.5) #pylab.xlabel("Days (since 9-24-2007)") ymin, ymax = pylab.ylim() pylab.plot_date(count[1], pylab.zeros(len(count[1])), 'k-') ax.xaxis.set_major_locator(pylab.YearLocator()) ax.xaxis.set_major_formatter(pylab.DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() if not log: if max: ymax = max xmax = int(pylab.xlim()[1] / 7) pylab.yticks(pylab.arange(0, max + 1, tick)) pylab.ylim(ymin, ymax) else: pylab.ylim(100, ymax) pylab.legend(loc=2, ncol=2, prop={'size': 'small'}) pylab.title(name.replace('_', ' ')) pylab.savefig(savepath + n1) return
def draw(self): x = matplotlib.dates.date2num([e['time'] for e in self.history]) y = [e['entropy'] for e in self.history] pylab.figure() fig, ax = pylab.subplots() pylab.setp(pylab.xticks()[1], rotation=30, ha='right') ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%H:%M')) pylab.plot_date(x, y) pylab.savefig('%s.png' % self.name, bbox_inches='tight') pylab.close()
def plot_field(self, field, suffix="", out_dir=None): """ Построение графика изменения параметра field """ tempVal = map(float, self.table[field]) aver_temp = sum(tempVal) / float(len(tempVal)) dateVal = self.get_date_month() maxField, maxDateIdx = self.get_extremum_field(field) maxDate = dateVal[maxDateIdx] minField, minDateIdx = self.get_extremum_field(field, min) minDate = dateVal[minDateIdx] title = 'Day by Day ' + field.upper( ) + ' in ' + self.city + ' in ' + self.date.strftime( "%B") + ' ' + self.date.strftime("%Y") #self.plot_temp(tempVal, aver_temp, dateVal, title) pylab.title(title) pylab.xlabel(r"Days") pylab.ylabel(field) pylab.plot_date(dateVal, tempVal, 'b-', label=field) pylab.plot_date([min(dateVal), max(dateVal)], [aver_temp, aver_temp], 'r-', label="Average " + str(round(aver_temp, 2))) pylab.grid(True) pylab.legend(loc=0) dt = dateVal[-1] - dateVal[0] df = maxField - minField #print dt.seconds offset = (datetime.timedelta(days=dt.days / 20), df / 50) #print offset arrowprops = dict(width=0.2, facecolor='black', shrink=0.05) posMax = (maxDate + offset[0], maxField + offset[1]) pylab.annotate( 'max = ' + str(round(maxField, 2)), xy=(maxDate, maxField), xytext=posMax, arrowprops=arrowprops, horizontalalignment='left', verticalalignment='bottom', ) posMin = (minDate - offset[0], minField - offset[1]) pylab.annotate( 'min = ' + str(round(minField, 2)), xy=(minDate, minField), xytext=posMin, arrowprops=arrowprops, horizontalalignment='right', verticalalignment='top', ) if out_dir is not None: pylab.savefig(os.path.join(out_dir, field + "_" + suffix + ".png")) pylab.close() else: pylab.show()
def csv2png(p): print p title, axis, data = get_data(p) dates = data[0] release_title, release_axis, release_data = get_data( py.path.local("release_dates.dat") ) release_dates, release_names = release_data sprint_title, sprint_axis, sprint_data = get_data( py.path.local("sprint_dates.dat") ) sprint_locations, sprint_begin_dates, sprint_end_dates = sprint_data ax = pylab.subplot(111) for i, d in enumerate(data[1:]): args = [dates, d, colors[i]] pylab.plot_date(linewidth=0.8, *args) ymax = max(pylab.yticks()[0]) #just below the legend for i, release_date in enumerate(release_dates): release_name = release_names[i] if greyscale: color = 0.3 else: color = "g" pylab.axvline(release_date, linewidth=0.8, color=color, alpha=0.5) ax.text(release_date, ymax * 0.4, release_name, fontsize=10, horizontalalignment='right', verticalalignment='top', rotation='vertical') for i, location in enumerate(sprint_locations): begin = sprint_begin_dates[i] end = sprint_end_dates[i] if float(begin) >= float(min(dates[0],dates[-1])): if greyscale: color = 0.8 else: color = "y" pylab.axvspan(begin, end, linewidth=0, facecolor=color, alpha=0.5) ax.text(begin, ymax * 0.85, location, fontsize=10, horizontalalignment='right', verticalalignment='top', rotation='vertical') pylab.legend(axis[1:], "upper left") pylab.ylabel(axis[0]) pylab.xlabel("") ticklabels = ax.get_xticklabels() pylab.setp(ticklabels, 'rotation', 45, size=9) # ax.autoscale_view() ax.grid(True) pylab.title(title) pylab.savefig(p.purebasename + ".png") pylab.savefig(p.purebasename + ".eps") py.process.cmdexec("epstopdf %s" % (p.purebasename + ".eps", ))
def newusersEvolution(cursor=None, title=''): result = cursor.execute("SELECT STRFTIME('%Y-%m-%d', rev_timestamp) AS date, rev_user_text FROM revision WHERE 1 ORDER BY date ASC") newusers = {} for row in result: if not newusers.has_key(row[1]): newusers[row[1]] = datetime.date(year=int(row[0][0:4]), month=int(row[0][5:7]), day=int(row[0][8:10])) newusers2 = {} for newuser, date in newusers.items(): if newusers2.has_key(date): newusers2[date] += 1 else: newusers2[date] = 1 newusers_list = [[x, y] for x, y in newusers2.items()] newusers_list.sort() startdate = newusers_list[0][0] enddate = newusers_list[-1:][0][0] delta = datetime.timedelta(days=1) newusers_list = [] #reset, adding all days between startdate and enddate d = startdate while d < enddate: if newusers2.has_key(d): newusers_list.append([d, newusers2[d]]) else: newusers_list.append([d, 0]) d += delta import pylab from matplotlib.dates import DateFormatter, rrulewrapper, RRuleLocator, drange loc = pylab.MonthLocator(bymonth=(1,6)) formatter = DateFormatter('%Y-%m-%d') dates = drange(startdate, enddate, delta) fig = pylab.figure() ax = fig.add_subplot(1,1,1) ax.set_ylabel('Newusers') ax.set_xlabel('Date (YYYY-MM-DD)') print '#'*100 print len(dates) print dates print '#'*100 print len(pylab.array([y for x, y in newusers_list])) print pylab.array([y for x, y in newusers_list]) print '#'*100 pylab.plot_date(dates, pylab.array([y for x, y in newusers_list]), 'o', color='green') ax.xaxis.set_major_locator(loc) ax.xaxis.set_major_formatter(formatter) ax.set_title(title) ax.grid(True) ax.set_yscale('log') labels = ax.get_xticklabels() pylab.setp(labels, rotation=30, fontsize=10)
def line_plot(data, out): """Turning ([key, ...], [value, ...]) into line graphs""" import matplotlib as mpl mpl.use('Agg') import pylab pylab.clf() pylab.plot_date(data[0], data[1], '-') pylab.savefig(out)
def test_single_date(): time1 = [721964.0] data1 = [-65.54] fig = pylab.figure() pylab.subplot(211) pylab.plot_date(time1, data1, 'o', color='r') pylab.subplot(212) pylab.plot(time1, data1, 'o', color='r') fig.savefig('single_date')
def drawBacktest(benchmarkReturn, portReturn, dailyDate): #pylab.plot_date(pylab.date2num(dailyDate),portReturn,'r',linewidth=0.8,linestyle='-') #pylab.plot_date(pylab.date2num(dailyDate),benchmarkReturn,'g',linewidth=0.8,linestyle='-') pylab.plot_date(dailyDate, portReturn,'r',linewidth=0.8,linestyle='-') xtext = pylab.xlabel('Out-Of-Sample Date') ytext = pylab.ylabel('Cumulative Return') ttext = pylab.title('Portfolio Return Vs Benchmark Return') pylab.grid(True) pylab.setp(ttext, size='large', color='r') pylab.setp(xtext, size='large', weight='bold', color='g') pylab.setp(ytext, size='large', weight='light', color='b') pylab.savefig('backtest.png')
def newpagesEvolution(cursor=None, title=''): result = cursor.execute( "SELECT STRFTIME('%Y-%m-%d', page_creation_timestamp) AS date, COUNT(*) AS count FROM page WHERE 1 GROUP BY date ORDER BY date ASC" ) newpages = {} for row in result: d = datetime.date(year=int(row[0][0:4]), month=int(row[0][5:7]), day=int(row[0][8:10])) newpages[d] = row[1] newpages_list = [[x, y] for x, y in newpages.items()] newpages_list.sort() startdate = newpages_list[0][0] enddate = newpages_list[-1:][0][0] delta = datetime.timedelta(days=1) newpages_list = [] #reset, adding all days between startdate and enddate d = startdate while d < enddate: if newpages.has_key(d): newpages_list.append([d, newpages[d]]) else: newpages_list.append([d, 0]) d += delta import pylab from matplotlib.dates import DateFormatter, rrulewrapper, RRuleLocator, drange loc = pylab.MonthLocator(bymonth=(1, 6)) formatter = DateFormatter('%Y-%m-%d') dates = drange(startdate, enddate, delta) fig = pylab.figure() ax = fig.add_subplot(1, 1, 1) ax.set_ylabel('Newpages') ax.set_xlabel('Date (YYYY-MM-DD)') print '#' * 100 print len(dates) print dates print '#' * 100 print len(pylab.array([y for x, y in newpages_list])) print pylab.array([y for x, y in newpages_list]) print '#' * 100 pylab.plot_date(dates, pylab.array([y for x, y in newpages_list]), 'o') ax.xaxis.set_major_locator(loc) ax.xaxis.set_major_formatter(formatter) ax.set_title(title) ax.grid(True) ax.set_yscale('log') labels = ax.get_xticklabels() pylab.setp(labels, rotation=30, fontsize=10)
def CloseCurve(df): daytime = list(df["Date"]) closelist = list(df["Close"]) pylab.plot_date(pylab.date2num(daytime), closelist, marker='.', mfc='darkblue', linestyle='-') plt.subplots_adjust(bottom=0.15) plt.xlabel("date") #X轴标签 plt.ylabel("close") #Y轴标签 plt.title("hs300 close curve") #标题 plt.show()
def do_plot(x_axis, y_axis, title, xlabel, ylable): import pylab, setting pylab.plot_date(x_axis, y_axis, linestyle='dashed') pylab.xlabel(xlabel) pylab.ylabel(ylable) pylab.title(title) pylab.grid(True) if setting.PIC_SAVE_PATH_AND_PREFIX: title__png_ = setting.PIC_SAVE_PATH_AND_PREFIX + title + ".png" pylab.savefig(title__png_) print "draw:", title__png_ pylab.figure() else: pylab.show()
def test2(): today = datetime.now() dates = [today + timedelta(days=i) for i in range(10)] print(dates) values = [3, 2, 8, 4, 5, 6, 7, 8, 11, 2] pylab.plot_date(pylab.date2num(dates), values, linestyle='-') #text(17, 277, '瞬时流量示意') xt = [d.strftime('%m-%d') for d in dates] xticks(dates, xt) xlabel('时间time (s)') ylabel('单位 (m3)') title('供应商日销售汇总折线图') grid(True) show()
def n_lines_charts(labels, file_path, unit, type, y_max, y_title): plt.style.use('ggplot') plt.figure(figsize=(14, 4)) for x1, x2, x3, x4, x5 in labels: pl.plot_date(x1, x2, label=x3, linestyle=x4, linewidth=x5) ax = pl.gca() xfmt = dt.DateFormatter('%H:%M') ax.xaxis.set_major_formatter(xfmt) pl.gcf().autofmt_xdate() # Y轴单位,例如50%,100% if 'SAMPLE' == type: # 如果是原始变量,直接根据单位设置Y轴单位后缀 if 'percent' == unit: y_tick = y_max suffix = '%' # 单位后缀 elif 'bytes' == unit: if y_max > 1024 * 1024 * 1024 * 1024: y_tick = y_max / 1024 / 1024 / 1024 / 1024 suffix = 'T' if y_max > 1024 * 1024 * 1024: y_tick = y_max / 1024 / 1024 / 1024 suffix = 'G' elif y_max > 1024 * 1024: y_tick = y_max / 1024 / 1024 suffix = 'M' elif y_max > 1024: y_tick = y_max / 1024 suffix = 'K' # 网络流量单位转换 else: y_tick = y_max suffix = 'b' else: # 如果是计算变量,默认设置 y_tick = y_max suffix = '%' y_ticks = [0, 0.5 * y_max, y_max] y_ticks_labels = [ '0', "%.1f" % (0.5 * y_tick) + suffix, "%.1f" % y_tick + suffix ] ax.set_yticks(y_ticks) ax.set_yticklabels(y_ticks_labels) pl.legend(loc='best', fontsize=6) pl.grid(True) pl.ylabel(y_title) pl.savefig(file_path) pl.cla()
def stat_day(messages): import collections from pylab import plot_date, show date2num = collections.defaultdict(int) for time, author, body in messages: date2num[time.strftime('%y-%m-%d')] += 1 dates, nums = [], [] for k in sorted(date2num.iterkeys()): y, m, d = k.split('-') dates.append(datetime(int(y), int(m), int(d))) nums.append(date2num[k]) plot_date(dates, nums, 'go') show()
def newpagesEvolution(cursor=None, title=""): result = cursor.execute( "SELECT STRFTIME('%Y-%m-%d', page_creation_timestamp) AS date, COUNT(*) AS count FROM page WHERE 1 GROUP BY date ORDER BY date ASC" ) newpages = {} for row in result: d = datetime.date(year=int(row[0][0:4]), month=int(row[0][5:7]), day=int(row[0][8:10])) newpages[d] = row[1] newpages_list = [[x, y] for x, y in newpages.items()] newpages_list.sort() startdate = newpages_list[0][0] enddate = newpages_list[-1:][0][0] delta = datetime.timedelta(days=1) newpages_list = [] # reset, adding all days between startdate and enddate d = startdate while d < enddate: if newpages.has_key(d): newpages_list.append([d, newpages[d]]) else: newpages_list.append([d, 0]) d += delta import pylab from matplotlib.dates import DateFormatter, rrulewrapper, RRuleLocator, drange loc = pylab.MonthLocator(bymonth=(1, 6)) formatter = DateFormatter("%Y-%m-%d") dates = drange(startdate, enddate, delta) fig = pylab.figure() ax = fig.add_subplot(1, 1, 1) ax.set_ylabel("Newpages") ax.set_xlabel("Date (YYYY-MM-DD)") print "#" * 100 print len(dates) print dates print "#" * 100 print len(pylab.array([y for x, y in newpages_list])) print pylab.array([y for x, y in newpages_list]) print "#" * 100 pylab.plot_date(dates, pylab.array([y for x, y in newpages_list]), "o") ax.xaxis.set_major_locator(loc) ax.xaxis.set_major_formatter(formatter) ax.set_title(title) ax.grid(True) ax.set_yscale("log") labels = ax.get_xticklabels() pylab.setp(labels, rotation=30, fontsize=10)
def NavCurve(fileaddress): df = pd.read_csv(fileaddress, parse_dates=['NavDate']) daytime = list(df["NavDate"]) navlist = list(df["Nav"]) pylab.plot_date(pylab.date2num(daytime), navlist, marker='.', mfc='darkblue', linestyle='-') plt.subplots_adjust(bottom=0.15) plt.xlabel("date") #X轴标签 plt.ylabel("nav") #Y轴标签 plt.title("baseline nav curve") #标题 plt.show()
def plotData(inputFile, oriThick): timestamp, metalloss = calcData(inputFile, oriThick) timestamp = pylab.array(timestamp) metalloss = pylab.array(metalloss) # pylab.date2num(date),将date 类型转换为pylab的时间类型, # 使用pylab.plot_date()画图 pylab.plot_date(pylab.date2num(timestamp), metalloss, 'bo', label='Metal Loss(mm)') pylab.title('Metal Loss to Time') pylab.xlabel('Time') pylab.ylabel('Metal loss(mm)') pylab.show()
def do_plot(x_axis, y_axis,title,xlabel,ylable): import pylab,setting pylab.plot_date(x_axis, y_axis, linestyle='dashed') pylab.xlabel(xlabel) pylab.ylabel(ylable) pylab.title(title) pylab.grid(True) if setting.PIC_SAVE_PATH_AND_PREFIX: title__png_ = setting.PIC_SAVE_PATH_AND_PREFIX + title + ".png" pylab.savefig(title__png_) print "draw:",title__png_ pylab.figure() else: pylab.show()
def draw_lsjz(data): x, y = [], [] for i in data: x.append(i[0]) y.append(float(i[1])) x.reverse() y.reverse() pl.xticks(rotation='vertical') pl.plot_date(x, y, 'r-') index = 0 xl = len(x) while index < xl: pl.axvline(x=x[index], ymin=0, ymax=1) index += 1 pl.show()
def fig_plot(): lj_hs_rd = open('lj_hs.txt', 'r') wj_hs_rd = open('wj_hs.txt', 'r') date_rd = open('date.txt', 'r') lj_ay = [] wj_ay = [] dt_ay = [] for lj_line in lj_hs_rd.readlines(): lj_list = lj_line.strip().split(' ') for i in range(len(lj_list)): aa = int(lj_list[i]) lj_ay.append(aa) for wj_line in wj_hs_rd.readlines(): wj_list = wj_line.strip().split(' ') for j in range(len(wj_list)): bb = int(wj_list[j]) wj_ay.append(bb) for date_line in date_rd.readlines(): date_list = date_line.strip().split(' ') for k in range(len(date_list)): dt = datetime.datetime.strptime(date_list[k], '%m/%d') dt_ay.append(dt) dt_fl = pl.date2num(dt_ay) plt.figure(1) pl.gca().xaxis.set_major_formatter(mdate.DateFormatter('%m/%d')) pl.gca().xaxis.set_major_locator(mdate.DayLocator()) pl.plot_date(dt_fl, lj_ay, label='lj hosue number', linestyle='-') pl.plot_date(dt_fl, wj_ay, label='wawj house number', linestyle='-') plt.xlabel('date') plt.ylabel('house number') plt.grid(True) plt.legend(loc='upper left') #plt.show() plt.savefig('line_plot.png') plt.figure(2) total_width, n = 0.8, 2 width = total_width / n plt.bar(dt_fl, lj_ay, width=width, label='lj') plt.bar(dt_fl + width, wj_ay, width=width, label='wj') plt.legend() #plt.show() plt.savefig('bar_plot.png')
def plotcounts(self, binsize, pngfile): """ bin the data based on a bin size of binsize days """ #vector_datetime2epoch = scipy.vectorize(converttime.datetime2epoch) #etime = vector_d2e(self['etime']) etime = self['etime'] etimemin = scipy.floor(min(etime) / 86400) * 86400 etimemax = scipy.ceil(max(etime) / 86400) * 86400 r = [etimemin, etimemax] nbins = (etimemax - etimemin) / (binsize * 86400) h = scipy.histogram(etime, nbins, r) ecount = h.__getitem__(0) ebin = h.__getitem__(1) #vector_e2d = scipy.vectorize(converttime.epoch2datetime) edt = vector_epoch2datetime(ebin) pylab.plot_date(edt, ecount, linestyle='steps-mid') pylab.savefig(pngfile)
def group(factorX,factorY,groupNum):#Q是factorX,mv或动量是factorY factorGroup=np.zeros([factorY.shape[0],groupNum]) for i in range(factorY.shape[0]): factorSort=np.sort(factorX[i,])#np.sort 默认升序排列,nan在最后 factorSortIdx=np.argsort(factorX[i,]) firstNanIdx=np.where(np.isnan(factorSort)==True)[0][0] factorSortIdx=factorSortIdx[:firstNanIdx] inGroupNum=int(round(len(factorSortIdx)/groupNum))#每组股票数 for j in range(groupNum-1): factorGroup[i,j]=np.nanmean(factorY[i,factorSortIdx[inGroupNum*j:inGroupNum*(j+1)]]) factorGroup[i,groupNum-1]=np.nanmean(factorY[i,factorSortIdx[inGroupNum*(groupNum-1):]]) for j in range(groupNum): pylab.plot_date(date,mvGroup[:,j],linestyle='-') label = [u'第1组',u'第2组',u'第3组',u'第4组',u'第5组'] plt.legend(label) return factorGroup
def plotcounts(self, binsize, pngfile): """ bin the data based on a bin size of binsize days """ #vector_datetime2epoch = scipy.vectorize(converttime.datetime2epoch) #etime = vector_d2e(self['etime']) etime = self['etime'] etimemin = scipy.floor(min(etime)/86400) * 86400 etimemax = scipy.ceil(max(etime)/86400) * 86400 r = [etimemin, etimemax] nbins = (etimemax - etimemin) / (binsize * 86400) h = scipy.histogram(etime, nbins, r) ecount = h.__getitem__(0) ebin = h.__getitem__(1) #vector_e2d = scipy.vectorize(converttime.epoch2datetime) edt = vector_epoch2datetime(ebin) pylab.plot_date(edt, ecount, linestyle='steps-mid') pylab.savefig(pngfile)
def specframeconvert(val='344.84e9Hz', inframe='TOPO', indoppler='RADIO', restfreq='1.410GHz', timebeg='2011/5/28/01h00m00', timeend='', direction='J2000 12h01m51 -18d52m00', observatory='VLA', outframe='LSRK', npoints=100, doplot=False): """ val= frequency or velocity quantity (e.g '113GHz' or '-25km/s') inframe=frame of input value (e.g 'TOPO', 'GEO', BARY') indoppler=doppler velocity definition if val is velocity ('RADIO', 'OPTICAL', 'Z' etc) restfrequency=line rest frequency if val is in velocity units timebeg=start of time range in UTC e.g '2012/12/25/00h00m00' timeend=end of time range in UTC or '' if only one value is needed direction=Source direction of interest (e.g 'J2000 12h01m51 -18d52m00') observatory=name of observatory to know where on earth this calculation is for outframe=frame of the output frequencies for the time range requested npoints= number of points to have values calculated in time range doplot=True or False (if Frequecy v/s Time plot is needed) """ me.doframe(me.observatory(observatory)) me.doframe(me.source(direction)) me.doframe(me.epoch('utc', timebeg)) epnow=me.epoch('utc', timebeg) interval=0 xday=[] yday=[] if(timeend==''): npoints=1 else: interval=qa.convert(qa.sub(qa.quantity(timeend), qa.quantity(timebeg)), 's')['value'] interval=interval/npoints if ((qa.quantity(val)['unit'].find('Hz')) <0 and (qa.quantity(val)['unit'].find('m/s') >=0)): vel=me.doppler(indoppler, val) freq=me.tofrequency(inframe, vel, qa.quantity(restfreq))['m0'] else: freq=qa.quantity(val) freqval=me.frequency(inframe, freq) for k in range(npoints): me.doframe(epnow) xday.append(pl.date2num(dateutil.parser.parse(qa.time(epnow['m0'], form='ymd')[0]))) yday.append(me.measure(freqval, 'LSRK')['m0']['value']) epnow['m0']=qa.add(epnow['m0'], qa.quantity(interval, 's')) if(doplot): pl.figure(1) pl.clf() pl.plot_date(xday, np.array(yday), 'o') pl.xlabel('Time') pl.ylabel('Frequency in Hz') pl.title('Variation of frequency in '+outframe) return np.array(yday)
def test_single_date(self): """Test single-point date plots.""" fname = self.outFile("single_date.png") time1 = [721964.0] data1 = [-65.54] fig = pylab.figure() pylab.subplot(211) pylab.plot_date(time1, data1, 'o', color='r') pylab.subplot(212) pylab.plot(time1, data1, 'o', color='r') fig.savefig(fname) self.checkImage(fname)
def dataplot(self, *var, **adict): """ Plotting the data with variable names """ # calling convenience functions to clean-up input parameters var, sel = self.__var_and_sel_clean(var, adict) dates, nobs = self.__dates_and_nobs_clean(var, sel) for i in var: pylab.plot_date(dates, self.data[i][sel], 'o-') pylab.xlabel("Time (n = " + str(nobs) + ")") pylab.title("Data plot of " + self.DBname) pylab.legend(var) if adict.has_key('file'): pylab.savefig(adict['file'], dpi=600) pylab.show()
def diurnalPlot(headers): """ diurnal plot of the emails, with years running along the x axis and times of day on the y axis.""" xday = [] ytime = [] for h in headers: if len(h) > 1: timestamp = mktime(parsedate(h[1][5:].replace('.', ':'))) mailstamp = datetime.fromtimestamp(timestamp) xday.append(mailstamp) # Time the email is arrived # Note that years, month and day are not important here. y = datetime(2010, 10, 14, mailstamp.hour, mailstamp.minute, mailstamp.second) ytime.append(y) plot_date(xday, ytime, '.', alpha=.7) xticks(rotation=30) return xday, ytime
def test_graph(): today = datetime.now() dates = [today + timedelta(days=i) for i in range(10)] #values = [random.randint(1, 20) for i in range(10)] values = [3,2,8,4,5,6,7,8,11,2] pylab.plot_date(pylab.date2num(dates), values, linestyle='-') text(17, 277, u'瞬时流量示意') xtext = xlabel(u'时间time (s)') ytext = ylabel(u'单位 (m3)') ttext = title(u'xx示意图') grid(True) setp(ttext, size='large', color='r') #setp(text, size='medium', name='courier', weight='bold',color='b') setp(xtext, size='medium', name='courier', weight='bold', color='g') setp(ytext, size='medium', name='helvetica', weight='light', color='b') #savefig('simple_plot.png') savefig('simple_plot') show()