def plot_aerosols(self): fig, ax1 = pl.subplots(figsize=(12, 6)) aerosols = self._set_aerosols_list() stack = 0 for aerosol in aerosols: if self._weight_by_tau: ax1.bar(self.df[self.lbl_date], self.df[aerosol] * self.df[self.lbl_total_aot], bottom=stack, label=aerosol) stack += self.df[aerosol] * self.df[self.lbl_total_aot] else: ax1.bar(self.df[self.lbl_date], self.df[aerosol], bottom=stack, label=aerosol) stack += self.df[aerosol] ax1.xaxis.set_major_formatter(pl.DateFormatter("%y/%m/%d")) ax1.xaxis.set_minor_formatter(pl.DateFormatter("%d")) ax1.set_ylabel('CAMS AOT with aerosol fractions (-)') pl.legend() ax2 = ax1.twinx() ax2.set_ylabel('Relative humidity (%)') ax2.plot(self.df[self.lbl_date], self.df[self.lbl_rh]) fig.autofmt_xdate() pl.title(self._log_file_name) pl.savefig(self._log_file_name[:-4] + "_aerosols.png")
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 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 makePlot(sensors, sensorNames, pdfOutPath=None, pngOutPath=None, figureSize=FIGURE_SIZE_A4, pngDpi=100): import matplotlib matplotlib.use('Agg') import pylab f = pylab.figure(figsize=FIGURE_SIZE_A4) ax = f.gca() df = pylab.DateFormatter('%d.%m.%Y') dl = matplotlib.dates.DayLocator(range(1, 32)) ax.xaxis.set_major_locator(dl) ax.xaxis.set_major_formatter(df) hf = pylab.DateFormatter('%H:%M') hl = matplotlib.dates.HourLocator([0, 3, 6, 9, 12, 15, 18, 21]) ax.xaxis.set_minor_locator(hl) ax.xaxis.set_minor_formatter(hf) ax.xaxis.set_tick_params(which='major', pad=18) ax.tick_params(axis='x', which='minor', labelsize=10) ml = matplotlib.ticker.MultipleLocator(2) ax.yaxis.set_major_locator(ml) ml = matplotlib.ticker.MultipleLocator(1) ax.yaxis.set_minor_locator(ml) ax.set_ylabel(u"\u00B0C", rotation=0) for sensor, data in sensors.items(): if sensor not in sensorNames: sensorNames[sensor] = "Sensor %i" % sensor x, y = zip(*data) ax.plot(x, y, label=sensorNames[sensor]) ax.legend(loc='best', prop={'size': 10}) f.text(0.5, 0.93, 'Archas Temperatures', horizontalalignment='center') ax.xaxis_date() ax.autoscale_view() ax.grid(True) if pngOutPath is not None: f.savefig(pngOutPath, dpi=pngDpi) if pdfOutPath is not None: f.savefig(pdfOutPath)
def predict(recentDate, models): newDates = [] estCPI = [] for i in range(24): newDates.append(add_months(recentDate, 1)) recentDate = newDates[-1] mplDates = pylab.date2num(newDates) for m in models: for x in mplDates: estCPI.append(pylab.polyval(m, x)) fig, ax = pylab.subplots() pylab.rcParams['lines.linewidth'] = 1 pylab.rcParams['axes.titlesize'] = 10 pylab.rcParams['axes.labelsize'] = 10 pylab.rcParams['xtick.labelsize'] = 8 pylab.rcParams['ytick.labelsize'] = 8 pylab.rcParams['xtick.major.size'] = 8 pylab.rcParams['ytick.major.size'] = 8 pylab.rcParams['lines.markersize'] = 5 pylab.rcParams['legend.numpoints'] = 1 pylab.yticks(pylab.arange(min(estCPI), max(estCPI) + 1, 0.5)) ax.fmt_xdata = pylab.DateFormatter('%Y-%m-%d') ax.set_title('Projected Canada CPI Inflation') pylab.xlabel('Date') fig.autofmt_xdate() pylab.ylabel('Est. CPI') pylab.plot(newDates, estCPI)
def plot_count(fname, dpi=70): # Load data date, libxc, c, code, test, doc = np.loadtxt(fname, unpack=True) zero = pl.zeros_like(date) fig = pl.figure(1, figsize=(10, 5), dpi=dpi) ax = fig.add_subplot(111) polygon(date, c + code + test, c + code + test + doc, facecolor='m', label='Documentation') polygon(date, c + code, c + code + test, facecolor='y', label='Tests') polygon(date, c, c + code, facecolor='g', label='Python-code') polygon(date, zero, c, facecolor='r', label='C-code') polygon(date, zero, zero, facecolor='b', label='Fortran-code') months = pl.MonthLocator() months4 = pl.MonthLocator(interval=4) month_year_fmt = pl.DateFormatter("%b '%y") ax.xaxis.set_major_locator(months4) ax.xaxis.set_minor_locator(months) ax.xaxis.set_major_formatter(month_year_fmt) labels = ax.get_xticklabels() pl.setp(labels, rotation=30) pl.axis('tight') pl.legend(loc='upper left') pl.title('Number of lines') pl.savefig(fname.split('.')[0] + '.png', dpi=dpi)
def evaluate_models_on_training(realDates, x, y, models): fig, ax = pylab.subplots() pylab.rcParams['lines.linewidth'] = 1 pylab.rcParams['axes.titlesize'] = 10 pylab.rcParams['axes.labelsize'] = 10 pylab.rcParams['xtick.labelsize'] = 8 pylab.rcParams['ytick.labelsize'] = 8 pylab.rcParams['xtick.major.size'] = 8 pylab.rcParams['ytick.major.size'] = 8 pylab.rcParams['lines.markersize'] = 5 pylab.rcParams['legend.numpoints'] = 1 pylab.yticks(pylab.arange(min(cpi), max(cpi) + 1, 3.0)) ax.fmt_xdata = pylab.DateFormatter('%Y-%m-%d') ax.set_title('Canada CPI Inflation') pylab.xlabel('Date') fig.autofmt_xdate() pylab.ylabel('CPI') pylab.plot(date, cpi) for m in models: estYVals = pylab.polyval(m, x) r2 = r_squared(y, estYVals) std_error = se_over_slope(x, y, estYVals, m) pylab.plot(realDates,estYVals,label = 'Fit of degree '\ + str(len(m)-1)\ + ', R2 = '+str(round(r2,3)) + ', SE/S = '+str(round(std_error,3))) pylab.legend(loc='best') 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 drawCityAQI_avg(self): """ 绘制city级别的AQI曲线 :return: """ pl.title("AVGaqi/time ") # give plot a title pl.xlabel('time') # make axis labels pl.ylabel('aqi') self.fill_cityAqiAVG_hour() # # 画出每个时间点 # data = np.loadtxt(StringIO(self.cityAqiAVG_hour), dtype=np.dtype([("t", "S13"), ("v", float)])) # datestr = np.char.replace(data["t"], "T", " ") # t = pl.datestr2num(datestr) # t1 = dt.datestr2num(datestr) # k = pl.num2date(t) # v = data["v"] # pl.plot_date(t[-20:], v[-20:], fmt="-o") # # polyfit(t[-20:], v[-20:]) # 画出每天00:00的图 self.fill_cityAqiAVG_day() data = np.loadtxt(StringIO(self.cityAqiAVG_day), dtype=np.dtype([("t", "S13"), ("v", float)])) datestr = np.char.replace(data["t"], "T", " ") t = pl.datestr2num(datestr) k = pl.num2date(t) k2 = dt.num2date(t) v = data["v"] pl.plot_date(t, v, fmt="-o") teet = 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 print 'over'
def adaptive_date_ticks(axx, dtrange=None, format=None, formatm=None, nticks=0, fit=None, label=True, lformat=None, ltime=None, debug=False): '''Takes an axis and a time range in seconds and chooses the optimal time display ax is the xaxis or yaxis, trange is the time range of the data in seconds, defaults to the existing plot data range format is the preferred time format e.g. '%Y' vs '%y' or '%b %d, %Y' vs '%m/%d' formatm is the preferred time format for the minor ticks e.g. '%Y' vs '%y' or '%b %d, %Y' vs '%m/%d' nticks forces the number of ticks, defaults to number already in figure axname allows time on y axis (default is x axis) fit determines whether the image should: fit the data range exactly (fit='exact') fit the nearest tick mark outside the data range (fit='tick') use the default fit (default or fit=None) label determines whether to add a label to the axis lformat allows the user to specify the format of the label ltime is the date number to use to generate the label, defaults to middle of data range''' if dtrange is None: bounds = pylab.getp(pylab.getp(axx, 'data_interval'), 'bounds') dtrange = pylab.diff(bounds) trange = dtrange * 86400 if label and ltime is None: ltime = pylab.mean(bounds) if nticks == 0: nticks = len(axx.get_ticklocs()) if trange < 60: #image covers less than 1 minute bt = int(60 / nticks) tloc = MinuteLocator() tlocm = SecondLocator(bysecond=range(bt, 60, bt)) tfor = ':%S' tform = '%M:%S' tlabel = '%b %d, %Y %H:%M' if debug: print 'seconds' elif trange / nticks < 60: tloc = MinuteLocator() tlocm = SecondLocator(bysecond=range(15, 60, 15)) tform = ':%S' tfor = '%M:00' tlabel = '%b %d, %Y %H:' if debug: print 'half minutes' elif trange / nticks < 90: tloc = MinuteLocator(interval=1) tlocm = SecondLocator(bysecond=30) tform = '' tfor = '%M' tlabel = '%b %d, %Y %H:' if debug: print 'minutes' elif trange / nticks < 120: tloc = MinuteLocator(byminute=range(0, 60, 2)) tlocm = SecondLocator(bysecond=(0, 30)) tfor = '%M' tform = '' tlabel = '%b %d, %Y %H:' if debug: print '2 minutes' elif trange / nticks < 240: tloc = MinuteLocator(interval=5) tlocm = MinuteLocator(interval=1) tfor = '%H:%M' tform = '' tlabel = '%b %d, %Y' if debug: print '5 minutes' elif trange / nticks < 600: tloc = MinuteLocator(interval=10) tlocm = MinuteLocator(interval=1) tform = '' tfor = '%H:%M' tlabel = '%b %d, %Y' if debug: print '10 minutes' elif trange / nticks < 1200: tloc = HourLocator(interval=1) tlocm = MinuteLocator(byminute=range(15, 60, 15)) tfor = '%H:%M' tform = ':%M' tlabel = '%b %d, %Y' if debug: print '30 minutes' elif trange / nticks < 2400: tloc = MinuteLocator(byminute=0) tlocm = MinuteLocator(byminute=30) tfor = '%H:00' tform = '' tlabel = '%b %d, %Y' if debug: print 'hour' elif trange / nticks < 4500: tloc = HourLocator(interval=2) tlocm = HourLocator(interval=1) tform = '' tfor = '%H:00' tlabel = '%b %d, %Y' if debug: print '2 hours' elif trange < 86400: tloc = HourLocator(byhour=range(0, 24, 3)) tlocm = HourLocator() tform = '' tfor = '%H:00' tlabel = '%b %d, %Y' if debug: print '3 hours' elif trange < 86400 * 2: tloc = HourLocator(byhour=range(0, 24, 6)) tlocm = HourLocator(byhour=range(0, 24, 2)) tform = '' tfor = '%H:00\n%m/%d' tlabel = '%b %d, %Y' if debug: print '6 hours' elif dtrange < 2.5: tloc = DayLocator() tlocm = HourLocator(byhour=range(6, 24, 6)) tfor = '%m/%d' tform = '%H:%M' tlabel = '%Y' if debug: print '1 day/ 6 hours' elif dtrange < 3: tloc = DayLocator() tlocm = HourLocator(byhour=12) tfor = '%m/%d' tform = '%H:%M' tlabel = '%Y' if debug: print '1 day/ 12 hours' elif dtrange / nticks < 0.5: tloc = DayLocator(interval=1) tlocm = HourLocator(byhour=range(0, 24, 12)) tform = '' tfor = '%m/%d' tlabel = '%Y' if debug: print '1 day' elif dtrange < 31 * 6: tloc = MonthLocator() if dtrange / nticks < 1: interv = 1 endv = 32 elif dtrange / nticks < 2: interv = 2 endv = 31 elif dtrange / nticks < 3: interv = 3 endv = 30 elif dtrange / nticks < 4: interv = 5 endv = 30 elif dtrange / nticks < 6: interv = 7 endv = 28 elif dtrange / nticks < 8: interv = 10 endv = 30 else: interv = 15 endv = 30 tlocm = MonthLocator(bymonthday=range(interv, endv, interv)) tfor = "%d\n%b '%y" tform = '%d' tlabel = 'date' if debug: print 'month' elif dtrange / nticks < 30: tloc = MonthLocator(bymonth=range(1, 13, 2)) tlocm = MonthLocator(bymonth=range(2, 13, 2)) tfor = "%b\n%y" tform = "%b" tlabel = 'date' if debug: print '2 month' elif dtrange < 366: tloc = MonthLocator(bymonth=range(1, 13, 6)) tlocm = MonthLocator(interval=1) tfor = "%b\n'%y" tform = "%b" tlabel = 'date' if debug: print '3 month/month' elif dtrange < 730: tloc = MonthLocator(bymonth=range(1, 13, 6)) tlocm = MonthLocator(bymonth=range(1, 13, 2)) tfor = "%b\n'%y" tform = "%b" tlabel = 'date' elif dtrange < 365 * 3: tloc = MonthLocator(bymonth=range(1, 13, 6)) tlocm = MonthLocator(bymonth=range(1, 13, 2)) tfor = "%b\n'%y" tform = "" tlabel = 'date' if debug: print '6 month/2 month' elif dtrange < 365 * 4: tloc = MonthLocator(bymonth=1) tlocm = MonthLocator(bymonth=7) tfor = "%b\n'%y" tform = "%b" tlabel = 'date' if debug: print '6 month/2 month' elif dtrange / nticks < 240: tloc = YearLocator() tlocm = MonthLocator(bymonth=(1, 7)) tform = "" tfor = "%Y" tlabel = 'Year' if debug: print 'year/6 month' elif dtrange / nticks < 365: tloc = YearLocator(base=2) tlocm = MonthLocator(bymonth=(1, 7)) tfor = '%Y' tform = '' tlabel = 'year' if debug: print '12 month' elif dtrange / nticks < 580: tloc = YearLocator(base=2) tlocm = YearLocator() tfor = '%Y' tform = '' tlabel = 'year' if debug: print '2 year/year' elif dtrange < 20 * 365: tloc = YearLocator(base=5) tlocm = YearLocator() tfor = '%Y' tform = '' tlabel = 'year' if debug: print '5 year/year' elif dtrange < 100 * 365: tloc = YearLocator(base=10) tlocm = YearLocator(base=2) tfor = '%Y' tform = '' tlabel = 'year' if debug: print '10 year' else: interv = 2.7 * dtrange / (nticks * 365.25) print interv interv = int( numpy.round( pylab.matplotlib.numerix.power( 10, int(pylab.matplotlib.numerix.log10(interv) * 3) / 3.) / (pylab.matplotlib.numerix.power( 10, int(pylab.matplotlib.numerix.log10(interv) * 3) / 3))) * (pylab.matplotlib.numerix.power( 10, int(pylab.matplotlib.numerix.log10(interv) * 3) / 3) * 1.)) print interv tloc = YearLocator(base=interv) tlocm = YearLocator(base=int(interv / 5)) tfor = '%Y' tform = '' tlabel = 'year' if debug: print 'variable long scale' if format is None: format = tfor if formatm is None: formatm = tform if lformat is None: lformat = tlabel axx.set_major_locator(tloc) axx.set_minor_locator(tlocm) axx.set_major_formatter(DateFormatter(format)) axx.set_minor_formatter(DateFormatter(formatm)) if label: if ltime is not None: #and lformat.find('%')<0: print 'reached here' dateform = pylab.DateFormatter(lformat) print lformat print pylab.num2date(ltime) tlabel = dateform.strftime(pylab.num2date(ltime), lformat) print tlabel elif lformat.find('%') > 0: tlabel = 'time' #if debug: # str = "range %8.4f range per tick %4.4f ticks %d\ntick format %s label %s" % (dtrange, dtrange/nticks, nticks, tform, tlabel) # print str # ax.set_title(str) pylab.setp(axx.get_label(), text=tlabel) enlarge_allticklines(axx, factor=1.5) pylab.draw_if_interactive()
hold=True) else: print "== %s ==" % k for date, rate, path in v: stamp = time.strftime("%Y-%m-%d %H:%M:%S", date) print stamp, "%10.3f" % rate, path if plot: pylab.grid(which='y') ax = pylab.gca() days = ax.dataLim.xmax - ax.dataLim.xmin #print "days",days, ax.dataLim.xmin, ax.dataLim.xmax if days > 5 * 365: major = pylab.YearLocator(interval=1) minor = pylab.MonthLocator(interval=6) label = pylab.DateFormatter("'%y") elif days > 2 * 365: major = pylab.MonthLocator(interval=6) minor = pylab.MonthLocator(interval=3) label = pylab.DateFormatter("%b '%y") elif days > 365: major = pylab.MonthLocator(interval=3) minor = pylab.MonthLocator(interval=1) label = pylab.DateFormatter("%b '%y") elif days > 365 / 2: major = pylab.MonthLocator(interval=2) minor = pylab.MonthLocator(interval=1, bymonthday=(1, 15)) label = pylab.DateFormatter("%b '%y") elif days > 365 / 6: major = pylab.MonthLocator(interval=1) minor = pylab.MonthLocator(interval=1, bymonthday=(1, 15))
2012-04-04_14 71 2012-04-04_20 69 2012-04-07_02 75 """ data = np.loadtxt(StringIO(data_str), dtype=np.dtype([("t", "S13"), ("v", float)])) datestr = np.char.replace(data["t"], "_", " ") t = pl.datestr2num(datestr) v = data["v"] pl.plot_date(t, v, fmt="-o") pl.subplots_adjust(bottom=0.3) ax = pl.gca() ax.fmt_xdata = pl.DateFormatter('%Y-%m-%d %H:%M:%S') pl.xticks(rotation=90) # pl.xticks(t, datestr) # 如果以数据点为刻度,则注释掉这一行 ax.xaxis.set_major_formatter(pl.DateFormatter('%Y-%m-%d %H:%M')) pl.grid() pl.show()
def draw_domain(dom): n1 = "Wikisource_-_pages_%s.png" % dom fig = pylab.figure(1) 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) 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) pylab.ylim(0) pylab.savefig(savepath + n1) n1 = "Wikisource_-_texts_%s.png" % dom pylab.figure(1) 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) else: pylab.legend([b1[0], b2[0]], ['with transclusion (PR2)', 'older system (PR1)'], loc=3) 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) pylab.ylim(0) pylab.savefig(savepath + n1)
x = pylab.concatenate((x, x[::-1])) y = pylab.concatenate((y1, y2[::-1])) pylab.fill(x, y, *args, **kwargs) fig = pylab.figure() ax = fig.add_subplot(111) polygon(date, code + test, code + test + c, facecolor='r', label='C-code') polygon(date, code, code + test, facecolor='y', label='Tests') polygon(date, [0] * len(date), code, facecolor='g', label='Python-code') polygon(date, [0] * len(date), [0] * len(date), facecolor='b', label='Fortran-code') months = pylab.MonthLocator() months3 = pylab.MonthLocator(interval=3) month_year_fmt = pylab.DateFormatter("%b '%y") ax.xaxis.set_major_locator(months3) ax.xaxis.set_minor_locator(months) ax.xaxis.set_major_formatter(month_year_fmt) labels = ax.get_xticklabels() pylab.setp(labels, rotation=30) pylab.axis('tight') pylab.legend(loc='upper left') pylab.title('Number of lines') pylab.savefig(dir + 'stat.png') os.system('cd; rm -r ' + tmpdir)
def plot_and_format(list_x, list_y, list_color=None, list_format=None, xlabel=None, ylabel=None, xticks=None, yticks=None, format_xticks=None, format_yticks=None, legend=None, loc_legend='best', axes=None, figure_figsize=None, xlim=None, ylim=None, fontsize=10, title=None, plot_date=False): # figure if not figure_figsize is None: pylab.figure(1, figsize=figure_figsize) # axes if axes is None: ax = pylab.axes() else: ax = pylab.axes(axes) # plot p = [] n_plots = len(list_y) for i in range(n_plots): x, y = list_x[i], list_y[i] if plot_date: x_num = pylab.date2num(x) if list_format is None: this_p = pylab.plot_date(x_num, y) else: this_p = pylab.plot_date(x_num, y, list_format[i]) else: this_p = pylab.plot(x, y) if list_format is None: this_p = pylab.plot(x, y) else: this_p = pylab.plot(x, y, list_format[i]) if not list_color is None: pylab.setp(this_p, color=list_color[i]) this_p.append(p) # axis labels if not xlabel is None: pylab.xlabel(xlabel, fontsize=fontsize) if not ylabel is None: pylab.ylabel(ylabel, fontsize=fontsize) # legend if not legend is None: pylab.legend(p, legend, loc=loc_legend) ltext = pylab.gca().get_legend().get_texts() pylab.setp(ltext[0], fontsize=fontsize) # ticks ax.xaxis.tick_bottom() ax.yaxis.tick_left() if not xticks is None: pylab.xticks(xticks['ticks'], xticks['labels']) if not yticks is None: pylab.yticks(yticks['ticks'], yticks['labels']) if plot_date: x_rotation = 45 else: x_rotation = 0 pylab.setp(ax.get_xticklabels(), 'rotation', x_rotation, fontsize=fontsize) pylab.setp(ax.get_yticklabels(), 'rotation', 0, fontsize=fontsize) if not format_xticks is None: if plot_date: fmt = pylab.DateFormatter(format_xticks) else: fmt = pylab.Formatter(format_xticks) ax.xaxis.set_major_formatter(fmt) if not format_yticks is None: ax.yaxis.set_major_formatter(pylab.Formatter(format_yticks)) # title if not title is None: pylab.title(title, fontsize=fontsize) # limits if not xlim is None: if plot_date: xlim = [pylab.date2num(a) for a in xlim] pylab.xlim(xlim) if not ylim is None: pylab.ylim(ylim)
def do_plot_airmass(observer, figure, **kw): obs = observer almanac = obs.almanac_data site = almanac.site_info airmass = obs.airmass_data M.rcParams['timezone'] = 'UTC' #local_tz = MD.timezone(site.timezone) local_tz = timezone(site.timezone) # set major ticks to hours in local time majorTick = MD.HourLocator(tz=local_tz) majorFmt = PL.DateFormatter('%Hh') # set minor ticks to 15 min intervals minorTick = MD.MinuteLocator(range(0,59,15), tz=local_tz) figure.clf() #ax1 = PL.subplot(111) ax1 = figure.add_subplot(111) #ax = PL.subplot(211) #ax.plot_date(dates, y, tz=local_tz) colors = ['r', 'b', 'g', 'c', 'm', 'y'] lstyle = '-' lt_data = [t.datetime() for t in airmass[0].local] for i, am in enumerate(airmass): am_data = N.array(am.airmass) am_min = N.argmin(am_data) am_data_dots = am_data if 'telescope' in kw: if kw['telescope'] != None: tdots = N.array(airmass[0].local) if kw['telescope'] == 'keck1': alimit = 1/N.sin(33.3*(N.pi/180.0)) # Keck 1 limits west am_data_dots = limits(am_data, tdots, alimit, direction='w') if kw['telescope'] == 'keck2': alimit = 1/N.sin(36.8*(N.pi/180.0)) # Keck 2 limits east am_data_dots = limits(am_data, tdots, alimit, direction='e') color = colors[i % len(colors)] lc = color + lstyle # ax1.plot_date(lt_data, am_data, lc, linewidth=1.0, alpha=0.3, aa=True, tz=local_tz) # xs, ys = M.mlab.poly_between(lt_data, 2.02, am_data) # ax1.fill(xs, ys, facecolor=colors[i], alpha=0.2) lstyle = 'o' lc = color + lstyle ax1.plot_date(lt_data, am_data_dots, lc, aa=True, tz=local_tz) # plot object label targname = am.target.name ax1.text(MD.date2num(lt_data[am_data.argmin()]), am_data.min() + 0.08, targname.upper(), color=color, ha='center', va='center') ax1.set_ylim(2.02, 0.98) #PL.ylim(0.98, 2.02) #PL.xlim(lt_data[0], lt_data[-1]) ax1.set_xlim(lt_data[0], lt_data[-1]) ax1.xaxis.set_major_locator(majorTick) ax1.xaxis.set_minor_locator(minorTick) ax1.xaxis.set_major_formatter(majorFmt) labels = ax1.get_xticklabels() ax1.grid(True, color='#999999') # plot current hour lo = datetime.now() #lo = datetime.now(tz=local_tz) hi = lo + timedelta(0, 3600.0) if lt_data[0] < lo < lt_data[-1]: ax1.axvspan(lo, hi, facecolor='#7FFFD4', alpha=0.25) title = 'Airmass for the night of %s' % str(almanac.localdate).split()[0] ax1.set_title(title) ax1.set_xlabel(site.tzname) ax1.set_ylabel('Airmass') #PL.setp(labels,'rotation', 45) #ax = PL.subplot(212) #PL.show() ax2 = ax1.twinx() moon_data = N.array(airmass[0].moon_altitude)*180/N.pi moon_illum = almanac.moon_phase() ax2.plot_date(lt_data, moon_data, '#666666', linewidth=2.0, alpha=0.5, aa=True, tz=local_tz) mxs, mys = M.mlab.poly_between(lt_data, 0, moon_data) # ax2.fill(mxs, mys, facecolor='#666666', alpha=moon_illum) ax2.set_ylabel('Moon Altitude (deg)', color='#666666') ax2.set_ylim(0, 90) ax2.set_xlim(lt_data[0], lt_data[-1]) ax2.xaxis.set_major_locator(majorTick) ax2.xaxis.set_minor_locator(minorTick) ax2.xaxis.set_major_formatter(majorFmt) ax2.set_xlabel('') ax2.yaxis.tick_right()
def scatter_and_format(list_x, list_y, list_color=None, list_s=None, list_marker=None, xlabel=None, ylabel=None, xticks=None, yticks=None, format_xticks=None, format_yticks=None, axes=None, figure_figsize=None, xlim=None, ylim=None, fontsize=10, title=None, plot_date=False): # figure if not figure_figsize is None: pylab.figure(1, figsize=figure_figsize) # axes if axes is None: ax = pylab.axes() else: ax = pylab.axes(axes) # plot n_plots = len(list_y) for i in range(n_plots): x, y = list_x[i], list_y[i] str_scatter = "this_p = pylab.scatter(x, y" if not list_s is None: str_scatter += ', s=%s' % (list_s[i], ) if not list_marker is None: str_scatter += ", marker='%s'" % (list_marker[i], ) str_scatter += ')' exec(str_scatter) if not list_color is None: pylab.setp(this_p, color=list_color[i]) # axis labels if not xlabel is None: pylab.xlabel(xlabel, fontsize=fontsize) if not ylabel is None: pylab.ylabel(ylabel, fontsize=fontsize) # ticks ax.xaxis.tick_bottom() ax.yaxis.tick_left() if not xticks is None: pylab.xticks(xticks['ticks'], xticks['labels']) if not yticks is None: pylab.yticks(yticks['ticks'], yticks['labels']) if plot_date: x_rotation = 45 else: x_rotation = 0 pylab.setp(ax.get_xticklabels(), 'rotation', x_rotation, fontsize=fontsize) pylab.setp(ax.get_yticklabels(), 'rotation', 0, fontsize=fontsize) if not format_xticks is None: if plot_date: fmt = pylab.DateFormatter(format_xticks) else: fmt = pylab.Formatter(format_xticks) ax.xaxis.set_major_formatter(fmt) if not format_yticks is None: ax.yaxis.set_major_formatter(pylab.Formatter(format_yticks)) # title if not title is None: pylab.title(title, fontsize=fontsize) # limits if not xlim is None: if plot_date: xlim = [pylab.date2num(a) for a in xlim] pylab.xlim(xlim) if not ylim is None: pylab.ylim(ylim)
print "Plotting Abrolhos series .............." p2 = pl.subplot(222) xmin = int(tt[0]) xmax = int(tt[-1]) pl.plot([tt[0], tt[-1]], [0, 0], 'k') pl.grid() pl.plot(tt, Vab, 'k', linewidth=1) pl.plot(tt, pl.mean(Vab) * pl.ones(pl.shape(tt)), 'r', linewidth=2) p2.set_xlim(xmin, xmax) p2.set_ylim(-50, 50) p2.set_ylabel("V [cm s$^{-1}$]") p2.set_title(r"Meridional Velocity off Abrolhos Bank - 18$^\circ$S") p2.set_axis_bgcolor('0.95') p2.xaxis.set_major_formatter(pl.DateFormatter('%b')) bbox_props = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.9) p2.text(dt.datetime(2008, 10, 1), -40, r"Southward = 63%", ha="center", va="center", size=12, bbox=bbox_props) p2.text(dt.datetime(2008, 10, 1), 40, r"Mean Velocity = -1.8 cm s$^{-1}$", ha="center", va="center", size=12, bbox=bbox_props,
from datetime import datetime, timedelta from subprocess import list2cmdline import numpy import pylab as P import matplotlib.dates as dates time_mark = int(time.time()) img_path = os.path.expanduser('~/sshfs/asus/root/sdb1/garage') out_path = os.path.join(os.path.dirname(__file__), 'output') r = re.compile('^[0-9A-F]+\(.*\)_\d_(\d+)_\d+\.jpg') dirlist = glob.glob(os.path.join(img_path, '2015*')) hourFormatter = P.DateFormatter('%H') fnames = [] for dname in dirlist: bdname = os.path.basename(dname) jpglist = glob.glob(os.path.join(dname, '*.jpg')) print '%s size:%d' % (bdname, len(jpglist)) hist = [] for f in jpglist: bname = os.path.basename(f) m = r.match(bname) if m: dt = datetime.strptime(m.groups()[0], '%Y%m%d%H%M%S') # print dt.strftime('%Y %H:%M:%S')