def show_plot(title, true1, true2, data1, data2, x, plot): if (not plot): return pylab.clf() pylab.title(title) l1 = "-" l2 = "--" colt = "r" # true data cold = "b" # data colr = "g" # residual pylab.plot(x, true1, label='true-1', color=colt, linestyle=l1) pylab.plot(x, true2, label='true-2', color=colt, linestyle=l2) pylab.plot(x, data1, label='data-1', color=cold, linestyle=l1) pylab.plot(x, data2, label='data-2', color=cold, linestyle=l2) pylab.legend(loc='upper left') pylab.twinx() pylab.plot(x, (data1-true1)/true1, label='data-1 % err', color=colr, linestyle=l1) pylab.plot(x, (data2-true2)/true2, label='data-2 % err', color=colr, linestyle=l2) pylab.legend(loc='upper right') pylab.show() return
def draw_hist_cdf(data,fig=None,nbins=None,subpl=None,nohist=False,**figargs): '''input data is a list of dicts with keys: data,histcolor,plotline ''' bins = None if fig: pylab.figure(fig,**figargs) if subpl: pylab.subplot(subpl) results = [] for d in data: if bins is not None: n,bins,patches=pylab.hist(d['data'],bins=bins,normed=1,fc=histcolors[d['plotline'][0]]) elif nbins is not None: n,bins,patches=pylab.hist(d['data'],bins=nbins,normed=1,fc=histcolors[d['plotline'][0]]) else: n,bins,patches=pylab.hist(d['data'],normed=1,fc=histcolors[d['plotline'][0]]) results.append(n) if nohist: pylab.cla() else: pylab.twinx() for i,d in enumerate(data): y = pylab.plot(bins,numpy.cumsum(results[i])/sum(results[i]), d['plotline'], linewidth=2)
def main(): """ 随着时间的推移,美国缅因州的离婚率和该国人均人造黄油消费量之间存在一种奇怪但毫无意义的相关性。 这里的两个序列拥有不同的单位和意义,所以应在不同的y轴上绘制,共享一个共同的x轴(年)。 :return: """ years = range(2000, 2010) divorce_rate = [5.0, 4.7, 4.6, 4.4, 4.3, 4.1, 4.2, 4.2, 4.2, 4.1] margarine_consumption = [8.2, 7, 6.5, 5.3, 5.2, 4, 4.6, 4.5, 4.2, 3.7] matplotlib.rcParams['font.sans-serif'] = [u'Arial Unicode MS'] matplotlib.rcParams['axes.unicode_minus'] = False pylab.title( "Compare with the divorce rate and margarine consumption(per capita) in Maine" ) line1 = pylab.plot(years, divorce_rate, 'b-o', label="缅因州离婚率") pylab.ylabel("Divorce rate in Maine") pylab.twinx() line2 = pylab.plot(years, margarine_consumption, 'r-o', label="黄油消耗水平") pylab.ylabel("margarine consumption(per capita)") lines = line1 + line2 labels = [] for line in lines: labels.append(line.get_label()) pylab.legend(lines, labels) pylab.show()
def plot_dH_ds(self, mean=0): # self.mu = mean x = np.linspace(1E-2,5,1000) def h(s): self.sigma = np.sqrt(s) self.sigma2 = s self.compute_Z() return self.H() def dh(s): self.sigma = np.sqrt(s) self.sigma2 = s self.compute_Z() return self.dH_dvar() def dmean_dvar(s): self.sigma = np.sqrt(s) self.sigma2 = s self.compute_Z() return self.dmean_dvar() H = np.vectorize(h) dH = np.vectorize(dh) # MV = np.vectorize(dmean_dvar) for m in range(1): # self.mu = m self.compute_Z() pb.figure("mu:{:.4f} var:{:.4f} side:{:s}".format(self.mu, self.sigma, self.side)) pb.clf() pb.plot(x,dH(x), label='dH', lw=1.5) #pb.plot(x,MV(x), label='dMV', lw=1.5) pb.plot(x[:-1], np.diff(H(x))/np.diff(x), label='numdH', lw=1.5) pb.legend() pb.twinx() pb.plot(x,H(x), label='H')
def atomic_potential(A, B): r = pylab.linspace(0.2, 0.6, 1001) pylab.xlabel('Distance (nm)') pylab.xlim(0.2, 0.6) U = ((B / pylab.array(r)**12) - (A / pylab.array(r)**6)) * 10**18 func1 = pylab.plot(r, U, 'b-', label=r'$U(r) = \frac{B}{r^{12}} - \frac{A}{r^6}$') pylab.ylabel('Energy (aJ)') pylab.ylim(-0.003, 0.004) pylab.legend() pylab.twinx() F = ((12 * B / pylab.array(r)**13) - (6 * A / pylab.array(r)**7)) * 10**18 func2 = pylab.plot(r, F, 'r--', label=r'$F(r) = \frac{12B}{r^{13}} - \frac{6A}{r^7}$') pylab.ylabel('Force (aN)') pylab.ylim(-0.06, 0.08) funcs = func1 + func2 labels = [] for func in funcs: labels.append(func.get_label()) pylab.legend(funcs, labels) pylab.show() return ('\u03b5: ' + '{:.5f}'.format(min(U[1:])) + ' nJ; ' + 'r_0: ' + '{:.5f}'.format((2 * B / A)**(1 / 6)))
def plot_comparison(results_dir): '''INTERFACE: Plot the results of comparing two accounts for common ads. Args: results_dir: Directory path containing the comparison results file and also where the comparison plot should be saved. ''' fd = open(results_dir + "/results.txt", "r") bases = [] counts = [] others = [] misses = [] founds = [] for line in fd.readlines(): if "BaseTrial" in line: continue base, count, other, missed = line.strip().split() base = int(base) + 1 count = int(count) other = int(other) + 1 missed = int(missed) found = 1 - (missed/float(count)) if len(bases) > 0 and bases[-1] == base: others[-1] = other misses[-1] = missed founds[-1] = found else: bases.append(base) counts.append(int(count)) others.append(other) misses.append(missed) founds.append(found) fd.close() pylab.ylim([0, 1]) pylab.yticks(adLib.float_range(0, 1, 0.1)) pylab.xlabel("Base Trial") pylab.ylabel("Fraction of Ads Found") pylab.plot(bases, founds, "b.", label="Found " + \ str(round(sum(founds)/len(founds), 3))) pylab.legend(loc="upper left", prop={'size':10}) pylab.title("Common Ads in Identical Accounts") pylab.twinx() pylab.xlim([0, 100]) pylab.xticks(range(0, 100, 10)) pylab.ylim([0, 15]) pylab.yticks(range(0, 15, 1)) pylab.ylabel("Number of Trials to Find Base Ads") pylab.plot(bases, others, "r.", label="In Trials " + \ str(round(sum(others)/float(len(others)), 3))) pylab.legend(loc="lower right", prop={'size':10}) pylab.savefig(results_dir + "/results.png") pylab.clf() print results_dir, sum(counts)/float(len(counts)), sum(misses)/float(len(misses))
def optimize_lbfgsb(self, hessian_terms=10, plotfn=None): XX = [] OO = [] def objective(x, tractor, stepsizes, lnp0): res = lnp0 - tractor(x * stepsizes) print('LBFGSB objective:', res) if plotfn: XX.append(x.copy()) OO.append(res) return res from scipy.optimize import fmin_l_bfgs_b stepsizes = np.array(self.getStepSizes()) p0 = np.array(self.getParams()) lnp0 = self.getLogProb() print('Active parameters:', len(p0)) print('Calling L-BFGS-B ...') X = fmin_l_bfgs_b(objective, p0 / stepsizes, fprime=None, args=(self, stepsizes, lnp0), approx_grad=True, bounds=None, m=hessian_terms, epsilon=1e-8, iprint=0) p1, lnp1, d = X print(d) print('lnp0:', lnp0) self.setParams(p1 * stepsizes) print('lnp1:', self.getLogProb()) if plotfn: import pylab as plt plt.clf() XX = np.array(XX) OO = np.array(OO) print('XX shape', XX.shape) (N, D) = XX.shape for i in range(D): OO[np.abs(OO) < 1e-8] = 1e-8 neg = (OO < 0) plt.semilogy(XX[neg, i], -OO[neg], 'bx', ms=12, mew=2) pos = np.logical_not(neg) plt.semilogy(XX[pos, i], OO[pos], 'rx', ms=12, mew=2) I = np.argsort(XX[:, i]) plt.plot(XX[I, i], np.abs(OO[I]), 'k-', alpha=0.5) plt.ylabel('Objective value') plt.xlabel('Parameter') plt.twinx() for i in range(D): plt.plot(XX[:, i], np.arange(N), 'r-') plt.ylabel('L-BFGS-B iteration number') plt.savefig(plotfn)
def plot_error(x, x_hat, title=''): import pylab pylab.figure() pylab.plot(x, x) pylab.plot(x, x_hat) pylab.twinx() pylab.plot(x, x_hat - x) pylab.title(title + ' RMSE: %f' % rms(x - x_hat))
def plot_error(x,x_hat): import pylab pylab.figure() pylab.plot(x,x) pylab.plot(x,x_hat) pylab.twinx() pylab.plot(x,x_hat-x) pylab.title('RMSE: %f'%rms(x-x_hat))
def plotStatsForClusterBased(x, y1, y2, y3, outputFile, ylabel, title=""): 'Uses pylab to produce a plot of cumulative statistics.' xlen = len(y1) pylab.ylabel('Mean LV and Mv Lengths(meter)', fontsize='x-large') pylab.xlabel("Number of transformers connected", fontsize='x-large') MV = pylab.plot(x, y2, 'b--', linewidth=5) LV = pylab.plot(x, y3, 'y.-', linewidth=5) pylab.ylim(0, 100) pylab.twinx() meanCost = pylab.plot(x, y1, 'm-', linewidth=5) if x[0] == 1: pylab.xlabel("Number of transformers connected", fontsize='x-large') ticks = [] for i in range(0, xlen / 20 + 1): ticks.append(i * 20) ticks.append(xlen) if title == "Ruhiira": pylab.xticks(ticks, ('0/%i' % (xlen), '20/%i' % (xlen), '40/%i' % (xlen), '49/%i' % (xlen)), fontsize='xlarge') if title == "Pampaida": pylab.xticks(ticks, ('0/%i' % (xlen), '20/%i' % (xlen), '40/%i' % (xlen), '60/%i' % (xlen), '80/%i' % (xlen), '100/%i' % (xlen), '115/%i' % (xlen)), fontsize='x-large') if title == "Mbola": pylab.xticks(ticks, ('0/%i' % (xlen), '20/%i' % (xlen), '40/%i' % (xlen), '60/%i' % (xlen), '80/%i' % (xlen), '100/%i' % (xlen), '120/%i' % (xlen), '139/%i' % (xlen)), fontsize='large') if title == "Tiby": #tick leri de degistir pylab.xticks(ticks, ('0/%i' % (xlen), '5/%i' % (xlen), '10/%i' % (xlen), '15/%i' % (xlen)), fontsize='large') else: pylab.xlabel("Transformers connected (%)", fontsize='xlarge') pylab.xticks([0, 20, 40, 60, 80, 100], ('0%', '20%', '40%', '60%', '80%', '100%'), fontsize='x-large') pylab.xlim(0, 100) pylab.ylabel(ylabel, fontsize='x-large') pylab.ylim(min(min(y1), min(y2), min(y3)), max(max(y1), max(y2), max(y3)) + 100) pylab.xlabel("Number of transformers connected", fontsize='x-large') pylab.yticks(fontsize='large') pylab.title(title, fontsize='x-large') pylab.legend((MV, LV, meanCost), ('MeanMV', 'MeanLV', 'MeanCost'), loc="upper left") pylab.savefig(outputFile, dpi=300) pylab.clf() return 0
def doPlotting(y, y2, d, d2, LOD, mu_MLE, mu_pstr, mu_pstr2, V_pstr, V_pstr2, left, right, bins, plotFile=None): import pylab X = bins if y2 is not None: old = numpy.seterr(all="ignore") for curr_y2, curr_d2, curr_mu_pstr2, in zip(y2, d2, mu_pstr2): pylab.plot(X, curr_y2/curr_d2 , "+", alpha=0.6) pylab.plot(X, curr_mu_pstr2/N, lw=2) numpy.seterr(**old) old = numpy.seterr(all="ignore") pylab.plot(X, y/d, "r+", alpha=0.6) numpy.seterr(**old) pylab.xlabel("bp (%d bp loci)" % res) pylab.ylabel("Allele frequency") if y2 is not None: for val, alpha in [(0.025, 0.3), (0.005, 0.1), (0.0005, 0.05)]: for curr_mu_pstr2, curr_V_pstr2 in zip(mu_pstr2, V_pstr2): CI = scipy.stats.norm.isf(val, 0, numpy.sqrt(curr_V_pstr2)) # pylab.fill_between(X, (curr_mu_pstr2 - CI)/N, (curr_mu_pstr2 + CI)/N, alpha=alpha) pylab.fill_between(X, (curr_mu_pstr2 - CI)/N, (curr_mu_pstr2 + CI)/N, color='r', alpha=alpha) else: for val, alpha in [(0.025, 0.3), (0.005, 0.1), (0.0005, 0.05)]: CI = scipy.stats.norm.isf(val, 0, numpy.sqrt(V_pstr)) # pylab.fill_between(X, (mu_MLE - CI)/N, (mu_MLE + CI)/N, color='r', alpha=alpha) pylab.fill_between(X, (mu_pstr - CI)/N, (mu_pstr + CI)/N, color='r', alpha=alpha) pylab.axhline(0.5, color='k', ls=':') targStart = left*res targStop = right*res pylab.fill_between([targStart-res/2,targStop-res/2], 0, 1, color="k", alpha=0.2) pylab.axis([X[0],X[-1],0,1]) pylab.twinx() pylab.ylabel("LOD score") pylab.plot(X, LOD, 'g-', lw=2) if N < 10000: posteriors = numpy.zeros((N,T)) for c in xrange(T): posteriors[:,c] = scipy.stats.norm.pdf(numpy.arange(0,1.0,1.0/N), mu_pstr[c]/N, numpy.sqrt(V_pstr[c])/N) posteriors[:,c] /= numpy.sum(posteriors[:,c]) pylab.axis([X[0],X[-1],LOD.min(),LOD.max()+3]) if plotFile is not None: pylab.savefig(plotFile) else: pylab.show()
def test(): starttime = time.time() # set up theta, phi, r, quantities rlo = 6.2e10 rhi = 6.96e10 thi = 40.0*numpy.pi/180. tlo = -40.0*numpy.pi/180. phi = 40.0*numpy.pi/180. plo = -40.0*numpy.pi/180. dr = (rhi - rlo)/100 dth = (thi - tlo)/100 dphi = (phi - plo)/100 radius = numpy.arange(rlo, rhi+dr, dr) theta = numpy.arange(tlo, thi+dth, dth) phi = numpy.arange(plo, phi+dphi, dphi) # data has dimensions of (nth, nphi, nr, nq=1) data = func(radius, theta, phi) # avgdata has dimensions of (nr, nq) avgdata = shell_avg(data, theta, phi, method='simp') # only consider first quantity avgdata = avgdata[:,0] true = exact(radius, phi, theta) l2norm = numpy.sqrt(dr*numpy.sum((true-avgdata)**2)) print "\nL2 Norm: ",l2norm print endtime = time.time() print "elapsed time: ", endtime-starttime print pylab.clf() pylab.plot(radius, true, label='true', color='r', linestyle='--') pylab.plot(radius, avgdata, label='avg', color='b', linestyle='-') pylab.legend(loc='lower left') pylab.twinx() pylab.plot(radius, (avgdata - true)/true, label='% err', color='g', linestyle='--') pylab.legend(loc='lower right') pylab.show() return
def test_dT_impact(xvals, f, nmpc, sim, start=0.1, end=0.8, step=0.02, ymax=200, sample_size=100, label=None): """Used to generate Figure XX of the paper.""" c = raw_input("Did you remove iter/time caps in IPOPT settings? [y/N] ") if c.lower() not in ['y', 'yes']: print "Then go ahead and do it." return stats = [Statistics() for _ in xrange(len(xvals))] fails = [0. for _ in xrange(len(xvals))] pylab.ion() pylab.clf() for (i, dT) in enumerate(xvals): f(dT) for _ in xrange(sample_size): nmpc.on_tick(sim) if 'Solve' in nmpc.nlp.return_status: stats[i].add(nmpc.nlp.solve_time) else: # max CPU time exceeded, infeasible problem detected, ... fails[i] += 1. yvals = [1000 * ts.avg if ts.avg is not None else 0. for ts in stats] yerr = [1000 * ts.std if ts.std is not None else 0. for ts in stats] pylab.bar(xvals, yvals, width=step, yerr=yerr, color='y', capsize=5, align='center', error_kw={ 'capsize': 5, 'elinewidth': 5 }) pylab.xlim(start - step / 2, end + step / 2) pylab.ylim(0, ymax) pylab.grid(True) if label is not None: pylab.xlabel(label, fontsize=24) pylab.ylabel('Comp. time (ms)', fontsize=20) pylab.tick_params(labelsize=16) pylab.twinx() yfails = [100. * fails[i] / sample_size for i in xrange(len(xvals))] pylab.plot(xvals, yfails, 'ro', markersize=12) pylab.plot(xvals, yfails, 'r--', linewidth=3) pylab.xlim(start - step / 2, end + step / 2) pylab.ylabel("Failure rate [%]", fontsize=20) pylab.tight_layout()
def plot_quality(btquality): """Make diagnostic plot of output of computeBTQuality().""" import pylab as pl btq = btquality pl.figure() pl.plot(btq.index, (btq.N - btq.N.ix[0]) / float(btq.N.ix[0]), "bo") pl.ylabel("$(N - N_0) / N_0$", color="b") pl.xlabel("Frame") pl.twinx() pl.plot(btq.index, -(btq.Nconserved - btq.N.ix[0]) / float(btq.N.ix[0]), "r^") pl.ylabel("Fraction dropped", color="r")
def optimize_lbfgsb(self, hessian_terms=10, plotfn=None): XX = [] OO = [] def objective(x, tractor, stepsizes, lnp0): res = lnp0 - tractor(x * stepsizes) print 'LBFGSB objective:', res if plotfn: XX.append(x.copy()) OO.append(res) return res from scipy.optimize import fmin_l_bfgs_b stepsizes = np.array(self.getStepSizes()) p0 = np.array(self.getParams()) lnp0 = self.getLogProb() print 'Active parameters:', len(p0) print 'Calling L-BFGS-B ...' X = fmin_l_bfgs_b(objective, p0 / stepsizes, fprime=None, args=(self, stepsizes, lnp0), approx_grad=True, bounds=None, m=hessian_terms, epsilon=1e-8, iprint=0) p1,lnp1,d = X print d print 'lnp0:', lnp0 self.setParams(p1 * stepsizes) print 'lnp1:', self.getLogProb() if plotfn: import pylab as plt plt.clf() XX = np.array(XX) OO = np.array(OO) print 'XX shape', XX.shape (N,D) = XX.shape for i in range(D): OO[np.abs(OO) < 1e-8] = 1e-8 neg = (OO < 0) plt.semilogy(XX[neg,i], -OO[neg], 'bx', ms=12, mew=2) pos = np.logical_not(neg) plt.semilogy(XX[pos,i], OO[pos], 'rx', ms=12, mew=2) I = np.argsort(XX[:,i]) plt.plot(XX[I,i], np.abs(OO[I]), 'k-', alpha=0.5) plt.ylabel('Objective value') plt.xlabel('Parameter') plt.twinx() for i in range(D): plt.plot(XX[:,i], np.arange(N), 'r-') plt.ylabel('L-BFGS-B iteration number') plt.savefig(plotfn)
def plot_quality(btquality): """Make diagnostic plot of output of computeBTQuality().""" import pylab as pl btq = btquality pl.figure() pl.plot(btq.index, (btq.N - btq.N.ix[0]) / float(btq.N.ix[0]), 'bo') pl.ylabel('$(N - N_0) / N_0$', color='b') pl.xlabel('Frame') pl.twinx() pl.plot(btq.index, -(btq.Nconserved - btq.N.ix[0]) / float(btq.N.ix[0]), 'r^') pl.ylabel('Fraction dropped', color='r')
def doPlotting(y, y2, d, d2, LOD, mu_MLE, mu_pstr, mu_pstr2, V_pstr, V_pstr2, left, right, bins, plotFile=None): import pylab X = bins[:-1] + 0.5*res # bin mid-points if y2 is not None: old = numpy.seterr(all="ignore") for curr_y2, curr_d2, curr_mu_pstr2, in zip(y2, d2, mu_pstr2): pylab.plot(X, curr_y2/curr_d2 , "+", alpha=0.6) pylab.plot(X, curr_mu_pstr2/N, lw=2) numpy.seterr(**old) old = numpy.seterr(all="ignore") pylab.plot(X, y/d, "r+", alpha=0.6) numpy.seterr(**old) pylab.xlabel("bp (%d bp loci)" % res) pylab.ylabel("Allele frequency") if y2 is not None: for val, alpha in [(0.025, 0.3), (0.005, 0.1), (0.0005, 0.05)]: for curr_mu_pstr2, curr_V_pstr2 in zip(mu_pstr2, V_pstr2): CI = scipy.stats.norm.isf(val, 0, numpy.sqrt(curr_V_pstr2)) # pylab.fill_between(X, (curr_mu_pstr2 - CI)/N, (curr_mu_pstr2 + CI)/N, alpha=alpha) pylab.fill_between(X, (curr_mu_pstr2 - CI)/N, (curr_mu_pstr2 + CI)/N, color='r', alpha=alpha) else: for val, alpha in [(0.025, 0.3), (0.005, 0.1), (0.0005, 0.05)]: CI = scipy.stats.norm.isf(val, 0, numpy.sqrt(V_pstr)) # pylab.fill_between(X, (mu_MLE - CI)/N, (mu_MLE + CI)/N, color='r', alpha=alpha) pylab.fill_between(X, (mu_pstr - CI)/N, (mu_pstr + CI)/N, color='r', alpha=alpha) pylab.axhline(0.5, color='k', ls=':') pylab.fill_between([bins[left], bins[right]], 0, 1, color="k", alpha=0.2) pylab.axis([bins[0],bins[-1],0,1]) pylab.twinx() pylab.ylabel("LOD score") pylab.plot(X, LOD, 'g-', lw=2) if N < 10000: posteriors = numpy.zeros((N,T)) for c in xrange(T): posteriors[:,c] = scipy.stats.norm.pdf(numpy.arange(0,1.0,1.0/N), mu_pstr[c]/N, numpy.sqrt(V_pstr[c])/N) posteriors[:,c] /= numpy.sum(posteriors[:,c]) pylab.axis([bins[0],bins[-1],LOD.min(),LOD.max()+3]) if plotFile is not None: pylab.savefig(plotFile) else: pylab.show()
def fit(self, X, n_epochs=100, plot=True): p = self.p q = self.q w_ma = np.random.randn(p) w_ar = np.random.randn(q) k = max(p, q) n = X.shape[0] p_offset = k - p q_offset = k - q Y = np.random.randn(n) ma_changes = [] ar_changes = [] errors = [] learning_rate = self.learning_rate for i in xrange(n_epochs): if self.verbose: print "Epoch ", i old_ma = w_ma.copy() old_ar = w_ar.copy() for j in np.random.permutation(n - k): curr_idx = j + k x_prev = X[j + p_offset:curr_idx] y_prev = Y[j + q_offset:curr_idx] pred = np.dot(x_prev, w_ma) + np.dot(y_prev, w_ar) Y[curr_idx] = pred err = X[curr_idx] - pred w_ma += err * x_prev * learning_rate w_ar += err * y_prev * learning_rate ma_change = np.linalg.norm(old_ma - w_ma) ma_changes.append(ma_change) ar_change = np.linalg.norm(old_ar - w_ar) ar_changes.append(ar_change) mean_abs_error = np.mean(np.abs(Y[k:] - X[k:])) errors.append(mean_abs_error) if self.verbose: print "MA weight change", ma_change print "AR weight change", ar_change print "Mean abs. error:", mean_abs_error if ar_change < self.tol and ma_change < self.tol: break if plot: import pylab pylab.plot(ma_changes) pylab.plot(ar_changes) pylab.legend(['MA', 'AR']) pylab.twinx() pylab.plot(errors, 'r') self.w_ma = w_ma self.w_ar = w_ar
def fit(self, X, n_epochs = 100, plot=True): p = self.p q = self.q w_ma = np.random.randn(p) w_ar = np.random.randn(q) k = max(p,q) n = X.shape[0] p_offset = k - p q_offset = k - q Y = np.random.randn(n) ma_changes = [] ar_changes = [] errors = [] learning_rate = self.learning_rate for i in xrange(n_epochs): if self.verbose: print "Epoch ", i old_ma = w_ma.copy() old_ar = w_ar.copy() for j in np.random.permutation(n - k): curr_idx = j+k x_prev = X[j+p_offset : curr_idx] y_prev = Y[j+q_offset : curr_idx] pred = np.dot(x_prev, w_ma) + np.dot(y_prev, w_ar) Y[curr_idx] = pred err = X[curr_idx] - pred w_ma += err * x_prev * learning_rate w_ar += err * y_prev * learning_rate ma_change = np.linalg.norm(old_ma - w_ma) ma_changes.append(ma_change) ar_change = np.linalg.norm(old_ar - w_ar) ar_changes.append(ar_change) mean_abs_error = np.mean(np.abs(Y[k:] - X[k:])) errors.append(mean_abs_error) if self.verbose: print "MA weight change", ma_change print "AR weight change", ar_change print "Mean abs. error:", mean_abs_error if ar_change < self.tol and ma_change < self.tol: break if plot: import pylab pylab.plot(ma_changes) pylab.plot(ar_changes) pylab.legend(['MA', 'AR']) pylab.twinx() pylab.plot(errors, 'r') self.w_ma = w_ma self.w_ar = w_ar
def yaxissfr(ax1): #when plotting lir, but on log scale y1, y2 = ax1.get_ylim() #print y1,y2 ax2 = pl.twinx() ax2.set_ylim(getsfrfromlir(y1), getsfrfromlir(y2)) #print 'y limit in SFR =',getsfrfromlir(y1),getsfrfromlir(y2) ax2.set_yscale('log')
def plotSubHistogram(self, candidate_data_ls, non_candidate_data_ls, which_figure, sub_title, xlabel, \ no_of_rows=2, max_no_of_bins=60, legend_loc='upper right', no_of_cols=2): """ 2009-2-19 add argument no_of_cols 2009-1-11 reduce max_no_of_bins from 100 to 60 2008-10-16 add option max_no_of_bins=200 2008-10-01 reduce the handle length in the legend 2008-09-28 """ pylab.subplot(no_of_rows, no_of_cols, which_figure, frameon=False) pylab.title(sub_title) pylab.xlabel(xlabel) pylab.grid(True, alpha=0.3) hist_patch_ls = [] legend_ls = [] no_of_bins = min(2*max_no_of_bins, int(len(non_candidate_data_ls)/30)) h1 = pylab.hist(non_candidate_data_ls, no_of_bins, alpha=0.3, linewidth=0) hist_patch_ls.append(h1[2][0]) legend_ls.append('non-candidate (%s)'%(len(non_candidate_data_ls))) pylab.ylabel('non-candidate count') no_of_bins = min(max_no_of_bins, int(len(candidate_data_ls)/30)) if no_of_bins>0: ax2 = pylab.twinx() h2 = ax2.hist(candidate_data_ls, no_of_bins, alpha=0.3, facecolor='r', linewidth=0) hist_patch_ls.append(h2[2][0]) legend_ls.append('candidate (%s)'%(len(candidate_data_ls))) pylab.ylabel('candidate count') pylab.legend(hist_patch_ls, legend_ls, loc=legend_loc, handlelen=0.02)
def plot(self, derivative=0, xmin="auto", xmax="auto", steps=500, smooth=0, simple='auto', clear=True, yaxis='left'): if simple=='auto': simple = self.simple # get the min and max if xmin=="auto": xmin = self.xmin if xmax=="auto": xmax = self.xmax # get and clear the figure and axes f = _pylab.gcf() if clear and yaxis=='left': f.clf() # setup the right-hand axis if yaxis=='right': a = _pylab.twinx() else: a = _pylab.gca() # define a new simple function to plot, then plot it def f(x): return self.evaluate(x, derivative, smooth, simple) _pylab_help.plot_function(f, xmin, xmax, steps, clear, axes=a) # label it th = "th" if derivative == 1: th = "st" if derivative == 2: th = "nd" if derivative == 3: th = "rd" if derivative: self.ylabel = str(derivative)+th+" derivative of "+self.ylabel+" spline" a.set_xlabel(self.xlabel) a.set_ylabel(self.ylabel) a.figure.canvas.Refresh()
def plot_two_values(X, Y1, Y2, xlabel, y1label, y2label, suffix): output_filename = constants.CHARTS_FOLDER_NAME + constants.DATASET + '_' + suffix pylab.figure(figsize=(15, 7)) pylab.rcParams.update({'font.size': 20}) pylab.xlabel(xlabel) ax1 = pylab.gca() ax1.plot(X, Y1, 'b') ax1.plot(X, [0.0 for x in X], 'b--') ax1.set_ylabel(y1label, color='b') for tl in ax1.get_yticklabels(): tl.set_color('b') ax2 = pylab.twinx() ax2.plot(X, Y2, 'r') ax2.plot(X, [0.0 for x in X], 'r--') ax2.set_ylabel(y2label, color='r') for tl in ax2.get_yticklabels(): tl.set_color('r') pylab.savefig(output_filename + '.pdf')
def plot_props(xlab, props, magbins, delta, flags_to_use,plot_info): magbinctr = (magbins[1:]+magbins[0:-1])/2 ax1 = pl.gca() pl.xlabel(xlab) ax2 = pl.twinx() for flag in flags_to_use: ax2.plot(magbinctr, props[flag], marker = 'o', ms = plot_info[flag]['ms'], ls = '-', color = plot_info[flag]['color'], label = plot_info[flag]['label']) ax2.set_ylabel('fraction of galaxies', fontsize=8) ax1.set_ylabel('Total galaxies', fontsize=8) ax1.yaxis.tick_right() ax1.yaxis.set_label_position("right") ax2.yaxis.tick_left() ax2.yaxis.set_label_position("left") ax2.set_ylim(0,1.0) ax1.bar(magbins[:-1], props['total'], width = delta, color = plot_info['total']['color'], log = False, zorder = -100) #for tick in ax1.yaxis.get_major_ticks(): # tick.set_label('%2.1e' %float(tick.get_label())) #ticklabs = ax1.get_yticklabels() #print ticklabs #print ['%2.1e' %float(x.get_text()) for x in ticklabs] #ax1.set_yticklabels( ['%2.1e' %float(x) for x in ticklabs] ) return ax1, ax2
def plottao(): f = pl.figure(2) pl.clf() pl.pcolor(Rar, Rmr, tao_e) #pl.contourf(Rar,Rmr,tao_e,10) cb = pl.colorbar() pl.contour(Rar, Rmr, tao_e, 10, colors='r') pl.ylim(Rms[0], Rms[1]) cb.set_label('tao_e at x = 0 [ms]') pl.xlabel('Ra [Ohm*cm]') pl.ylabel('Rm [Ohm*cm^2]') pl.twinx() #Show real tao equivalent values right pl.ylim(Rms[0] * 1e-3, Rms[1] * 1e-3) pl.ylabel('tao [ms]')
def plottao(): f = pl.figure(2) pl.clf() pl.pcolor(Rar,Rmr,tao_e) #pl.contourf(Rar,Rmr,tao_e,10) cb = pl.colorbar() pl.contour(Rar,Rmr,tao_e,10,colors='r') pl.ylim(Rms[0],Rms[1]) cb.set_label('tao_e at x = 0 [ms]') pl.xlabel('Ra [Ohm*cm]') pl.ylabel('Rm [Ohm*cm^2]') pl.twinx() #Show real tao equivalent values right pl.ylim(Rms[0]*1e-3,Rms[1]*1e-3) pl.ylabel('tao [ms]')
def drawplot(self, dates, hrs, observability): """Generate the observability figure. """ if self.dt == 0: ylabel = 'UTC Time' else: ylabel = 'UTC +{}'.format(self.dt) observer = ephem.Observer() ddates = [] for d in dates: observer.date = str(d) ddates.append(observer.date.datetime()) fig = py.figure() axpos = [.1, .12, .77, .76] ax = py.subplot(111, position=axpos) py.contourf(ddates, hrs, observability, cmap=py.cm.Greens) py.clim(0, 1.5) months = mdates.MonthLocator() # every month ax.xaxis.set_major_locator(months) hfmt = ddates.DateFormatter('%b ') ax.xaxis.set_major_formatter(hfmt) yt = np.array([0, 4, 8, 12, 16, 20, 24]) title = '%s: RA = %s, DEC = %s\nalt > %1.1f, sun < -%1.1f' % \ (self.obs, str(self.ra), str(self.dec), self.minElev, self.twilight) ax.set_title(title, fontsize=self.fs * 1.2) ax.set_yticks(yt) ax.yaxis.set_ticks(range(25), minor=True) ax.set_yticklabels(yt % 24) ax.set_ylabel(ylabel, fontsize=self.fs) ax.grid(axis='x') ax2 = py.twinx() ax2.set_position(axpos) yt2 = np.arange(-24, 24, 3) yt2 = yt2[(yt2 >= dt) * (yt2 <= (24 + dt))] ax2.set_ylim(dt, 24 + dt) ax2.set_yticks(yt2) ax2.set_ylabel('Local Time: UTC %+1.1f' % dt, fontsize=fs) ax2.grid(axis='y') tlabs = yt2 % 12 tlabs = [] for yt in yt2: if (yt % 24) == 12: lab = 'noon' elif (yt % 24) == 0: lab = 'mdnt' elif (yt % 24) >= 12: lab = '%i pm' % (yt % 12) else: lab = '%i am' % (yt % 12) tlabs.append(lab) ax2.set_yticklabels(tlabs) ax2.yaxis.set_ticks(range(dt, dt + 25), minor=True) self.fig = fig
def plot_profile(self, plot_shift=None): import pylab from bumps.plotutil import auto_shift plot_shift = plot_shift if plot_shift is not None else Experiment.profile_shift trans = auto_shift(plot_shift) if self.ismagnetic: z,rho,irho,rhoM,thetaM = self.magnetic_profile() #rhoM_net = rhoM*numpy.cos(numpy.radians(thetaM)) pylab.plot(z,rho,transform=trans) pylab.plot(z,irho,hold=True,transform=trans) pylab.plot(z,rhoM,hold=True,transform=trans) pylab.xlabel('depth (A)') pylab.ylabel('SLD (10^6 / A**2)') pylab.legend(['rho','irho','rhoM']) if (abs(thetaM-thetaM[0])>1e-3).any(): ax = pylab.twinx() pylab.plot(z,thetaM,':k',hold=True,axes=ax,transform=trans) pylab.ylabel('magnetic angle (degrees)') else: z,rho,irho = self.step_profile() pylab.plot(z,rho,':g',z,irho,':b',transform=trans) z,rho,irho = self.smooth_profile() pylab.plot(z,rho,'-g',z,irho,'-b', hold=True,transform=trans) pylab.legend(['rho','irho']) pylab.xlabel('depth (A)') pylab.ylabel('SLD (10^6 / A**2)')
def postProcess(self): coreName = self.study.cacheDir + os.sep + "hz-" + self.name f = open(coreName) vals = {} for l in f: toks = l.split("\t") vals[toks[0], toks[1]] = toks[2:] f.close() for pop in self.pops: pylab.clf() pylab.title(pop) labels = [] ehzs = [] ohzs = [] ns = [] for indiv in self.study.pops.getIndivs(pop): labels.append("\n".join(list(indiv))) o, e, n, f = vals[indiv] ehz = 1 - float(e) / int(n) ohz = 1 - float(o) / int(n) ehzs.append(ehz) ohzs.append(ohz) ns.append(int(n)) pylab.xticks(rotation=90, fontsize="x-small") pylab.legend() pylab.plot(ehzs, "+", label="ExpHe") pylab.plot(ohzs, "+", label="ObsHe") a2 = pylab.twinx() a2.plot(ns, ".") pylab.xticks(list(range(len(labels))), labels) xmin, xmax = pylab.xlim() pylab.xlim(xmin - 1, xmax + 1) pylab.savefig(coreName + "-" + pop + ".png")
def UserPlot(what_is_this, sim): ax = pylab.subplot(121) ax.hold(False) y = sim['weights'][0].ravel() pylab.plot(y, '-o') pylab.ylabel('weights') num_moments = sim['moments_mat'].shape[0] ax = pylab.subplot(122) ax.hold(False) if num_moments == 1: pylab.plot(sim['t_mat'], sim['moments_mat'][0, 0, :], '-o') pylab.ylabel('theta') elif num_moments == 2: pylab.plot(sim['t_mat'], sim['moments_mat'][0, 0, :], 'b-o') ax2 = pylab.twinx(ax) pylab.plot(sim['t_mat'], sim['moments_mat'][1, 0, :], 'g-o') ax2.yaxis.tick_right() else: for i in range(num_moments): pylab.plot(sim['t_mat'], sim['moments_mat'][i, 0, :], '-o') ax.hold(True)
def plot_props(xlab, props, magbins, delta, flags_to_use,plot_info,do_ci=False): magbinctr = (magbins[1:]+magbins[0:-1])/2 ax1 = pl.gca() pl.xlabel(xlab) ax2 = pl.twinx() max_yticksl = 6 max_yticksr = 5 max_xticks = 5 ylocl = plt.MaxNLocator(max_yticksl,prune='lower') ylocr = plt.MaxNLocator(max_yticksr,prune='lower') xloc = plt.MaxNLocator(max_xticks) for flag in flags_to_use: if do_ci: ax2.errorbar(magbinctr, np.array(props[flag]), yerr=np.array(props[str(flag)+'_err']).T, ecolor=plot_info[flag]['color'], elinewidth=1, capsize=3, marker = plot_info[flag]['marker'], ms = plot_info[flag]['ms'], ls = plot_info[flag]['ls'], color = plot_info[flag]['color'], label = plot_info[flag]['label']) else: ax2.plot(magbinctr, np.array(props[flag]), marker = plot_info[flag]['marker'], ms = plot_info[flag]['ms'], ls = plot_info[flag]['ls'], color = plot_info[flag]['color'], label = plot_info[flag]['label']) ax2.set_ylabel('fraction of galaxies', fontsize=8) ax1.set_ylabel('Total galaxies', fontsize=8) ax1.yaxis.tick_right() ax1.yaxis.set_label_position("right") ax2.yaxis.tick_left() ax2.yaxis.set_label_position("left") ax1.bar(magbins[:-1], props['total'], width = delta, color = plot_info['total']['color'], log = False, zorder = -100) ax1.xaxis.set_major_locator(xloc) ax2.xaxis.set_major_locator(xloc) ax1.yaxis.set_major_locator(ylocr) ax2.yaxis.set_major_locator(ylocl) ax2.set_ylim(0,1.0) #for tick in ax1.yaxis.get_major_ticks(): # tick.set_label('%2.1e' %float(tick.get_label())) #ticklabs = ax1.get_yticklabels() #print ticklabs #print ['%2.1e' %float(x.get_text()) for x in ticklabs] #ax1.set_yticklabels( ['%2.1e' %float(x) for x in ticklabs] ) ax1.yaxis.set_tick_params(labelsize=6) ax2.yaxis.set_tick_params(labelsize=6) return ax1, ax2
def plot_results(results, ai, ylab, xlab="Time (h)"): nplot = len(results) for i, (result_mean, result_std, epsilon, lab, y2lab, y2max, y2min) in \ enumerate(results): subplot(nplot, 1, i + 1) if i == nplot - 1: xlabel(xlab) title(lab) x = arange(0.0, result_mean.shape[1], 1.0) y = result_mean[ai, :] e = result_std[ai, :] y2 = epsilon[ai, :] # plot(x, result_mean[ai, :], # color=clr[ai % nc], # linestyle=ls[ai % ns], # label=lab) errorbar(x, y, yerr=e, fmt='ko', linestyle="None", label=ylab, capsize=0, markersize=3) #, linewidth=0.2) ylabel(ylab) l = legend(loc="upper right") l.get_frame().set_linewidth(0.5) # Exploration rate plot. twinx() plot(x, y2, color="black", label=y2lab) ylabel(y2lab) if y2max is not None: ylim(ymax=y2max) if y2min is not None: ylim(ymin=y2min) l = legend(loc="lower right") l.get_frame().set_linewidth(0.5)
def handler(signum, frame): try: fd.close() # might not be open yet except: pass a=inspect.stack() stacklevel=0 for k in range(len(a)): if (string.find(a[k][1], 'profileplot.py') > 0): stacklevel=k break myf=sys._getframe(stacklevel).f_globals # myf=frame.f_globals t=myf['t'] y11=myf['y11'] y22=myf['y22'] numfile=myf['numfile'] pl.plot(t,y11,lw=2) pl.plot(t,y22,lw=2) if max(y11)>=max(y22): pl.axis([0.9*min(t),1.1*max(t),0.9*min(y11),1.1*max(y11)]) else: pl.axis([0.9*min(t),1.1*max(t),0.9*min(y22),1.1*max(y22)]) pl.xlabel('time (sec)') pl.ylabel('memory footprint') #note virtual vs. resident font=FontProperties(size='small') pl.legend(('virtual','resident'),loc=[0.7,0.85], prop=font) ax2 = pl.twinx() pl.ylabel('No of open File Descriptors') ax2.yaxis.tick_right() pl.plot(t,numfile, 'r-.',lw=2) pl.legend(['No. of Open FDs'],loc=[0.7,0.8], prop=font) pl.title('memory usage of casapy for '+testname) #s="test-plot.ps" change to PNG for web browser compatibility #s="test-plot.png" #set up special images directory? if os.path.basename(myf['RESULT_DIR']) == myf['testname']: png_path=myf['RESULT_DIR'] else: png_path=myf['RESULT_DIR']+time.strftime('/%Y_%m_%d') png_filename=png_path +'/'+myf['testname']+'_profile.png' if not os.path.isdir(png_path): os.mkdir(png_path) pl.savefig(png_filename); ht=htmlPub(myf['webpage'], 'Memory profile of '+myf['testname']) body1=['<pre>Memory profile of run of test %s at %s </pre>'%(myf['testname'],time.strftime('%Y/%m/%d/%H:%M:%S'))] body2=[''] ht.doBlk(body1, body2,myf['testname']+'_profile.png', 'Profile') ht.doFooter() sys.stdout.flush() sys.exit() return
def plot_derivatives(x,y,subpl,xmax, sm=20): x,y = x[:-sm/2],Util.smooth(y,sm)[:-sm/2] x0,y0 = derivative(x,y,False) x0,y0 = x0[:-sm/2],Util.smooth(y0,sm)[:-sm/2] x1,y1 = derivative(x0,y0,False) x1,y1 = x1[:-sm/2],Util.smooth(y1,sm)[:-sm/2] pylab.subplot(*subpl) #pylab.cla() pylab.plot(x,y,'b',label='fn') pylab.twinx() pylab.plot(x0,y0,'g',label='d0') pylab.yticks([]) pylab.twinx() pylab.plot(x1,y1,'r',label='d1') pylab.yticks([]) pylab.plot([x1[0],x1[-1]],[0,0],'k:') pylab.xlim(0,xmax)
def _plotResults(self, path): ''' Power and Incoming ''' fig = pylab.figure() fields = getColumns(MONITOR_NAME) data = file2data(fields, MONITOR_NAME) pylab.grid(True) ax1 = pylab.subplot(111) l1 = pylab.plot(data[4], color='red') ax2 = pylab.twinx() l2 = pylab.plot(data[1], color='blue') ax2.legend((l1,l2), ('Incoming', 'Power'), 'best') ax1.set_ylabel("Incoming (req/s)") ax2.set_ylabel("Power (W)") ax1.set_xlabel("Time (s)") ax2.set_yticks(range(0, 600, 100)) pylab.ylim(-300, 600) fig.savefig(path + 'power.eps') ''' Sat and Incoming ''' fig = pylab.figure() fields = getColumns(MONITOR_NAME) data = file2data(fields, MONITOR_NAME) pylab.grid(True) ax1 = pylab.subplot(111) l1 = pylab.plot(data[4], color='blue') ax2 = pylab.twinx() l2 = pylab.plot(data[10], color='red') qos_target = self._perfRegulator.controller._setPoint pylab.axhline(qos_target, color='orange') ax2.legend((l1,l2), ('Incoming', 'Saturation'), 'best') ax1.set_ylabel("Incoming (req/s)") ax2.set_ylabel("Saturation") ax1.set_xlabel("Time (s)") ax2.set_yticks([x/10.0 for x in range(0, 20, 2)]) pylab.ylim(-2.5, 2) fig.savefig(path + 'sat.eps')
def flow_plot(ax1,expt_points,data_points, regime): plt.figure(j) ax1.plot(expt_points,data_points,'k-') #ax1.set_xlabel('z (microm)') ax1.set_ylabel(regime) ax2 = twinx() ax2.plot(expt_points,radius_points, 'r-') ax2.axvline(x=0, ymin=0.01, ymax=0.99, color='b',linestyle=':') ax2.axvline(x=(d/1e-6), ymin=0.01, ymax=0.99, color='b',linestyle=':') plt.show
def plot_results(results, ai, ylab, xlab="Time (h)"): nplot = len(results) for i, (result_mean, result_std, epsilon, lab, y2lab, y2max, y2min) in \ enumerate(results): subplot(nplot, 1, i + 1) if i == nplot-1: xlabel(xlab) title(lab) x = arange(0.0, result_mean.shape[1], 1.0) y = result_mean[ai, :] e = result_std[ai, :] y2 = epsilon[ai, :] # plot(x, result_mean[ai, :], # color=clr[ai % nc], # linestyle=ls[ai % ns], # label=lab) errorbar(x, y, yerr=e, fmt='ko', linestyle="None", label=ylab, capsize=0, markersize=3)#, linewidth=0.2) ylabel(ylab) l = legend(loc="upper right") l.get_frame().set_linewidth(0.5) # Exploration rate plot. twinx() plot(x, y2, color="black", label=y2lab) ylabel(y2lab) if y2max is not None: ylim(ymax=y2max) if y2min is not None: ylim(ymin=y2min) l = legend(loc="lower right") l.get_frame().set_linewidth(0.5)
def plotStatsForClusterBased(x, y1,y2,y3 ,outputFile, ylabel, title=""): 'Uses pylab to produce a plot of cumulative statistics.' xlen=len(y1) pylab.ylabel('Mean LV and Mv Lengths(meter)', fontsize='x-large') pylab.xlabel("Number of transformers connected", fontsize='x-large') MV=pylab.plot(x, y2, 'b--', linewidth=5) LV=pylab.plot(x, y3, 'y.-', linewidth=5) pylab.ylim(0,100) pylab.twinx() meanCost=pylab.plot(x, y1, 'm-', linewidth=5) if x[0]==1: pylab.xlabel("Number of transformers connected", fontsize='x-large') ticks=[] for i in range(0,xlen/20+1): ticks.append(i*20) ticks.append(xlen) if title=="Ruhiira": pylab.xticks(ticks, ('0/%i'%(xlen), '20/%i'%(xlen), '40/%i'%(xlen),'49/%i'%(xlen) ), fontsize='xlarge') if title=="Pampaida": pylab.xticks(ticks, ('0/%i'%(xlen), '20/%i'%(xlen), '40/%i'%(xlen), '60/%i'%(xlen), '80/%i'%(xlen),'100/%i'%(xlen),'115/%i'%(xlen)), fontsize='x-large') if title=="Mbola": pylab.xticks(ticks, ('0/%i'%(xlen), '20/%i'%(xlen), '40/%i'%(xlen), '60/%i'%(xlen), '80/%i'%(xlen),'100/%i'%(xlen),'120/%i' %(xlen),'139/%i' %(xlen)), fontsize='large') if title=="Tiby": #tick leri de degistir pylab.xticks(ticks, ('0/%i'%(xlen), '5/%i'%(xlen), '10/%i'%(xlen),'15/%i'%(xlen)),fontsize='large') else: pylab.xlabel("Transformers connected (%)", fontsize='xlarge') pylab.xticks([0, 20, 40, 60, 80, 100], ('0%', '20%', '40%', '60%', '80%', '100%'), fontsize='x-large') pylab.xlim(0,100) pylab.ylabel(ylabel, fontsize='x-large') pylab.ylim(min(min(y1),min(y2),min(y3)), max(max(y1),max(y2),max(y3))+100) pylab.xlabel("Number of transformers connected", fontsize='x-large') pylab.yticks(fontsize='large') pylab.title(title, fontsize='x-large') pylab.legend((MV,LV,meanCost),('MeanMV','MeanLV','MeanCost'),loc="upper left") pylab.savefig(outputFile, dpi=300) pylab.clf() return 0
def plot_all(self, show=True): plt.figure("S-parameters", figsize=(12, 9)) ii = 1 for sid, sdata in [('S11', self.s11), ('S21', self.s21), ('S12', self.s12), ('S22', self.s22)]: plt.subplot(2, 2, ii) plt.title(sid) plt.plot(self.freq, 10 * np.log10(np.abs(sdata)), c='#cc0000') plt.xlabel("Frequency [GHz]") plt.ylabel("Magnitude [dB]") plt.twinx() plt.plot(self.freq, np.rad2deg(np.angle(sdata)), c='#555555') plt.ylabel("Phase [deg]") plt.ylim(-185, 185) ii += 1 plt.tight_layout() if show: plt.show()
def plot_Z(state, data=None): x = range(len(data['Z'])) pl.plot(x, data['Z'], label='Z') if state.do_parallel_AIS: # parallel AIS estimate std = numpy.sqrt(numpy.array(data['pAIS_var'])) #pl.errorbar(x, data['pAIS'], yerr=3*std, label='pAIS') pl.plot(x, data['pAIS'], label='pAIS') if state.rbm.serial_AIS_type: # serial AIS estimate std = numpy.sqrt(numpy.array(data['sAIS_var'])) #pl.errorbar(x, data['sAIS'], yerr=3*std, label='sAIS') pl.plot(x, data['sAIS'], label='sAIS') if state.do_parallel_AIS and state.rbm.serial_AIS_type: # kalman filtered serial/parallel AIS estimate std = numpy.sqrt(numpy.array(data['fAIS_var'])) #pl.errorbar(x, data['fAIS'], yerr=3*std, label='fAIS') pl.plot(x, data['fAIS'], label='fAIS') pl.legend() # plot log-likelihood on separate y-axis if state.compute_nll.vals!=-1: pl.twinx() x = range(len(data['ll'])) pl.plot(x, data['ll'], label='NLL') pl.legend() title = 'nhid=%i lr=%.6f nbsize=%i sAIS=%s extraAIS=%i' %\ (state.rbm.n_hid, state.rbm_init.lr, state.rbm_init.nbsize, state.rbm.serial_AIS_type, state.extra_AIS_sample) if hasattr(state.rbm_init, 'nbeta'): title += ' nbeta=%i' % state.rbm_init.nbeta pl.title(title) pl.savefig('AIS_' + title.replace(' ','_')+'.pdf') pl.close()
def test_accuracy(): N = 200 p_inh = 0.2 sparsity = 0.5 tols = [None, 1e-80, 1e-40, 1e-30, 1e-12, 1e-10, 1e-8, 1e-6, 1e-4, 1e-2] model = nengo.Network(seed=0) with model: a = nengo.Ensemble(n_neurons=N, dimensions=3, seed=1) b = nengo.Ensemble(n_neurons=N, dimensions=3, seed=2) cs = [nengo.Connection(a, b, solver=nengo_solver_dales.DalesL2(reg=0.1, p_inh=p_inh, sparsity=sparsity, tol=tol)) for tol in tols] sim = nengo.Simulator(model) import pylab x, a = nengo.utils.ensemble.tuning_curves(a, sim, inputs=sim.data[a].eval_points) enc = sim.data[b].scaled_encoders target = np.dot(x, enc.T) ws = [sim.data[c].weights for c in cs] ts = [sim.data[c].solver_info['time'] for c in cs] actuals = [np.dot(a, w.T) for w in ws] rms = [np.mean(rmses(a, w.T, target)) for w in ws] print(rms) print(ts) for i in range(len(tols)): pylab.subplot(1, len(tols), i+1) pylab.scatter(target, actuals[i], s=1) pylab.title(rms[i]) pylab.figure() pylab.plot(rms) pylab.twinx() pylab.plot(ts) pylab.xticks(range(len(tols)), tols) pylab.show()
def wswd_test(): import pylab as P x=np.arange(0,2*np.pi,0.001) u=np.cos(x) v=np.sin(x) w=2.*np.sin(x*2.)*np.cos(x*2.) hws,vws,wd=wswd(u,v,w) ax1 = P.subplot(1,1,1) P.plot(x,u,'r') P.plot(x,v,'b') ax2 = P.twinx() P.plot(x,wd,'g') ax2.yaxis.tick_right() P.show()
def plot_w_hist(self): font = {'family' : 'times new roman', # 'weight' : 'bold', 'size' : 20 } p.rc('font', **font) # pass in the font dict as kwargs p.hist(self.crack_arr_w, normed=True, range=(0, 0.25), bins=40, histtype='bar', color='gray') p.xlabel('w [mm]') p.ylabel('frequency [%]') p.twinx() p.hist(self.crack_arr_w, normed=True, range=(0, 0.25), histtype='step', color='black', cumulative=True, linewidth=3, bins=40) p.ylim(0, 1) p.ylabel('fraction [-]') # figure title # uses directory path by default # if plot_title == 'true': m.title(os.path.join(self.data_dir, self.basename)) p.show()
def TwoSetPlot(ds1, ds2, ylim1=None, ylim2=None, autoscale=False, interactive=False): import pylab from matplotlib.font_manager import FontProperties if not interactive: pylab.ioff() font = FontProperties(size="x-small") ds1.NormalizeTime() ds2.NormalizeTime() ax1 = pylab.subplot(111) x_time1, datacols1, labels1 = ds1.GetColumns(1) x_time2, datacols2, labels2 = ds2.GetColumns(1) if not autoscale: _SetYLimit(ax1, ylim1, ds1.unit) pylab.plot(x_time1, datacols1[0], color=color_cycler.next(), label=labels1[0], ls="None", marker=",") pylab.xlabel("Time (s)") pylab.ylabel(ds1.unit) ax2 = pylab.twinx() if not autoscale: _SetYLimit(ax2, ylim2, ds2.unit) pylab.plot(x_time2, datacols2[0], color=color_cycler.next(), label=labels2[0], ls="None", marker=",") pylab.ylabel(ds2.unit) ax2.yaxis.tick_right() pylab.legend(prop=font) pylab.setp(pylab.gcf(), dpi=100, size_inches=(9, 6)) title = "plot-%s-%s-%s" % (ds1.metadata.timestamp.strftime("%m%d%H%M%S"), ds1.unit, ds2.unit) pylab.title(title, fontsize="x-small") if interactive: pylab.show() fname = None else: fname = "%s.%s" % (title, "png") pylab.savefig(fname, format="png") pylab.cla() return fname
def plot2d(self): p.subplot(2, 2, 1) p.plot(self.x_idx_arr, self.d_ux_avg_w, color='black') y_max_lim = p.gca().get_ylim()[-1] p.plot(self.x_idx_arr[:-1], self.crack_filter_avg * y_max_lim, color='magenta', linewidth=1) p.subplot(2, 2, 2) p.plot(self.x_idx_arr, self.ux_w, color='green') p.plot(self.x_idx_arr, self.ux_w_avg, color='red') p.subplot(2, 2, 3) p.plot(self.x_idx_arr, self.dd_ux_avg_w, color='black') p.plot(self.x_idx_arr, self.ddd_ux_avg_w, color='blue') y_max_lim = p.gca().get_ylim()[-1] p.plot(self.x_idx_arr[:-1], self.crack_filter_avg * y_max_lim, color='magenta', linewidth=2) p.subplot(2, 2, 4) p.hist(self.crack_arr_w, bins=40, normed=True) p.twinx() p.hist(self.crack_arr_w, normed=True, histtype='step', color='black', cumulative=True, bins=40) # figure title # uses directory path by default # if plot_title == 'true': m.title(os.path.join(self.data_dir, self.basename)) try: p.tight_layout() except: pass p.show()
def plot_dH_ds(self, mean=0): # self.mu = mean x = np.linspace(1E-2, 5, 1000) def h(s): self.sigma = np.sqrt(s) self.sigma2 = s self.compute_Z() return self.H() def dh(s): self.sigma = np.sqrt(s) self.sigma2 = s self.compute_Z() return self.dH_dvar() def dmean_dvar(s): self.sigma = np.sqrt(s) self.sigma2 = s self.compute_Z() return self.dmean_dvar() H = np.vectorize(h) dH = np.vectorize(dh) # MV = np.vectorize(dmean_dvar) for m in range(1): # self.mu = m self.compute_Z() pb.figure("mu:{:.4f} var:{:.4f} side:{:s}".format( self.mu, self.sigma, self.side)) pb.clf() pb.plot(x, dH(x), label='dH', lw=1.5) #pb.plot(x,MV(x), label='dMV', lw=1.5) pb.plot(x[:-1], np.diff(H(x)) / np.diff(x), label='numdH', lw=1.5) pb.legend() pb.twinx() pb.plot(x, H(x), label='H')
def comp_plot(rng, phi, z, az): fig = P.figure() line1 = P.plot(rng, phi * 180.0/N.pi, 'b') P.ylabel('Differential Phase (deg)') P.ylim(-180.0, 180.0) ax2 = P.twinx() line2 = ax2.plot(rng, 10.0*N.log10(z), 'g') P.xlabel('Range (km)') P.ylabel('Reflectivity Factor (dBZ)') P.xlim(0, 300) P.ylim(0, 60) P.title('Data Along Radial (%.1f deg)' % az) P.legend((line1, line2), ('Differential Phase', 'Reflectivity Factor'), loc='upper center') return fig
def _draw(self): N = range(len(_ref['pot'])) pl.gcf().clear() pl.figure(figsize=(7, 4)) pl.xlabel('Time', fontsize=12) pl.ylabel('Potential (mV)', fontsize=12) pl.grid(True) pl.title('Most fit individual at final iteration', fontsize=14) pl.plot(N, _ref['pot'], color='black', label='Reference spike train') pl.plot(N, self._best_pot, color='red', label='Evolved spike train') #pl.tight_layout() leg = pl.legend(loc=3, shadow=True, fancybox=True, prop={'size':12}) leg.get_frame().set_alpha(0.6) pl.savefig(_file_name[0]) N = len(self._maxs) X = range(N) pl.gcf().clear() pl.figure(figsize=(8, 5)) ax1 = pl.subplot(111) pl.axis([0, N, self._means[1], max(self._stddevs)+.1*(max(self._stddevs)-self._means[1])]) pl.xlabel('Generation', fontsize=12) pl.ylabel('Absolute fitness', fontsize=12) pl.grid(True) pl.title('Fitness development', fontsize=14) pl.plot(X, self._means, c='blue', linewidth=2, label='Mean fitness') pl.plot(X, self._stddevs, c='purple', linewidth=2, label='Standard deviation') leg = pl.legend(loc=3, shadow=True, fancybox=True, prop={'size':12}) leg.get_frame().set_alpha(0.6) ax2 = pl.twinx() pl.axis([0, N, self._maxs[5], max(self._maxs)+.1*(max(self._maxs)-self._maxs[5])]) pl.plot(X, self._maxs, c='red', linewidth=2, label='Maximum fitness') pl.ylabel('Absolute fitness', fontsize=12) leg = pl.legend(loc=4, shadow=True, fancybox=True, prop={'size':12}) leg.get_frame().set_alpha(0.6) pl.savefig(_file_name[0].replace('.png', '.dev.png'))
def plotSubHistogram(self, candidate_data_ls, non_candidate_data_ls, which_figure, sub_title, xlabel, \ no_of_rows=2, max_no_of_bins=60, legend_loc='upper right', no_of_cols=2): """ 2009-2-19 add argument no_of_cols 2009-1-11 reduce max_no_of_bins from 100 to 60 2008-10-16 add option max_no_of_bins=200 2008-10-01 reduce the handle length in the legend 2008-09-28 """ pylab.subplot(no_of_rows, no_of_cols, which_figure, frameon=False) pylab.title(sub_title) pylab.xlabel(xlabel) pylab.grid(True, alpha=0.3) hist_patch_ls = [] legend_ls = [] no_of_bins = min(2 * max_no_of_bins, int(len(non_candidate_data_ls) / 30)) h1 = pylab.hist(non_candidate_data_ls, no_of_bins, alpha=0.3, linewidth=0) hist_patch_ls.append(h1[2][0]) legend_ls.append('non-candidate (%s)' % (len(non_candidate_data_ls))) pylab.ylabel('non-candidate count') no_of_bins = min(max_no_of_bins, int(len(candidate_data_ls) / 30)) if no_of_bins > 0: ax2 = pylab.twinx() h2 = ax2.hist(candidate_data_ls, no_of_bins, alpha=0.3, facecolor='r', linewidth=0) hist_patch_ls.append(h2[2][0]) legend_ls.append('candidate (%s)' % (len(candidate_data_ls))) pylab.ylabel('candidate count') pylab.legend(hist_patch_ls, legend_ls, loc=legend_loc, handlelen=0.02)
def plot(self, derivative=0, xmin="auto", xmax="auto", steps=500, smooth=0, simple='auto', clear=True, yaxis='left'): if simple == 'auto': simple = self.simple # get the min and max if xmin == "auto": xmin = self.xmin if xmax == "auto": xmax = self.xmax # get and clear the figure and axes f = _pylab.gcf() if clear and yaxis == 'left': f.clf() # setup the right-hand axis if yaxis == 'right': a = _pylab.twinx() else: a = _pylab.gca() # define a new simple function to plot, then plot it def f(x): return self.evaluate(x, derivative, smooth, simple) _pylab_help.plot_function(f, xmin, xmax, steps, clear, axes=a) # label it th = "th" if derivative == 1: th = "st" if derivative == 2: th = "nd" if derivative == 3: th = "rd" if derivative: self.ylabel = str( derivative) + th + " derivative of " + self.ylabel + " spline" a.set_xlabel(self.xlabel) a.set_ylabel(self.ylabel) a.figure.canvas.Refresh()
def plot_yield_burden_curves(learner, x_labels, num_steps, all_runs, yields_and_burdens, out_dir): pylab.clf() total_N = max(x_labels) plot_em_all_for_learner(all_runs[learner], total_N, x_labels, num_steps, color="b") # # Now plot the averages # plt.plot(x_labels, yields_and_burdens[learner]["yield"], linewidth=2.0, color="b") plt.axis([0, total_N, -.05, 1.05]) plt.ylabel("Yield", {'color': 'b'}) ax_left = pylab.subplot(111) ax_right = pylab.twinx() plot_em_all_for_learner(all_runs[learner], total_N, x_labels, num_steps, color="r", metric="burden") plt.plot(x_labels, yields_and_burdens[learner]["burden"], linewidth=2.0, color="r") plt.ylabel("Burden", {'color': 'r'}) plt.axis([0, total_N, -.05, 1.05]) pylab.savefig(os.path.join(out_dir, "%s.pdf" % learner), format="pdf")
def plot(self, colour=True, Fbars=False, xsize=3, ysize=3): assert self.X.shape[1] == 1, "Can only plot 1D GPs, sorry!" ndlutil.Tango.reset() xmin, xmax = self.X.min(), self.X.max() xmin, xmax = xmin - 0.2 * (xmax - xmin), xmax + 0.2 * (xmax - xmin) ymin, ymax = self.Y.min(), self.Y.max() ymin, ymax = ymin - 0.2 * (ymax - ymin), ymax + 0.2 * (ymax - ymin) xx = np.linspace(xmin, xmax, 100)[:, None] if isinstance(self.kerny, kern.hierarchical): ncol = self.kerny.connections.shape[1] - 1 nrow = self.Y.shape[1] + 1 pb.figure(figsize=(ncol * ysize, nrow * xsize)) for i, y in enumerate(self.Y.T): if colour: c = ndlutil.Tango.coloursHex['mediumRed'] cf = ndlutil.Tango.coloursHex['lightRed'] cp = 'k' #ndlutil.Tango.coloursHex['Aluminium6'] else: c = ndlutil.Tango.coloursHex['Aluminium6'] cf = ndlutil.Tango.coloursHex['Aluminium1'] cp = ndlutil.Tango.coloursHex['Aluminium6'] #prediction for the mean of each gene. bit of a hack I'm afraid con = np.hstack( (np.ones((100, 2)), np.zeros((100, self.kerny.connections.shape[1] - 2)))) tmp1 = self.kerny.compute_new tmp2 = self.kerny.cross_compute self.kerny.compute_new = lambda x: tmp1(x, con) self.kerny.cross_compute = lambda x: tmp2(x, con) pb.subplot(nrow, ncol, 1 + i * ncol) ndlutil.utilities.gpplot(xx, *self.predict_y(xx, i), edgecol=c, fillcol=cf, alpha=0.3) self.kerny.compute_new = tmp1 self.kerny.cross_compute = tmp2 #plot config pb.xlim(xmin, xmax) pb.ylim(ymin, ymax) pb.xticks([]) ndlutil.Tango.removeRightTicks() #colours for the subsequent plots if colour: c = ndlutil.Tango.coloursHex['mediumBlue'] cf = ndlutil.Tango.coloursHex['lightBlue'] #get prediction for each replicate and plot for j in range(self.kerny.connections.shape[1] - 2): pb.subplot(nrow, ncol, 2 + i * ncol + j) #prediction for the mean of each replicate. Hacked as above con = np.hstack( (np.ones((100, 2)), np.zeros((100, self.kerny.connections.shape[1] - 2)))) con[:, j + 2] = 1 tmp1 = self.kerny.compute_new tmp2 = self.kerny.cross_compute self.kerny.compute_new = lambda x: tmp1(x, con) self.kerny.cross_compute = lambda x: tmp2(x, con) ndlutil.utilities.gpplot(xx, *self.predict_y(xx, i), edgecol=c, fillcol=cf, alpha=0.3) self.kerny.compute_new = tmp1 self.kerny.cross_compute = tmp2 #plot actual data index = np.nonzero(self.kerny.connections[:, j + 2])[0] pb.plot(self.X[index, 0], y[index], color=cp, marker='x', linewidth=0, mew=2) #plot config. pb.xlim(xmin, xmax) pb.ylim(ymin, ymax) pb.xticks([]) pb.yticks([]) #annotate genenames if hasattr(self, 'genenames'): pb.twinx() pb.ylabel(self.genenames[i], rotation=0) pb.xticks([]) pb.yticks([]) #get prediction for underlying function if colour: c = ndlutil.Tango.coloursHex['mediumOrange'] cf = ndlutil.Tango.coloursHex['lightOrange'] pb.subplot(nrow, ncol, self.Y.shape[1] * ncol + 1) ndlutil.utilities.gpplot(xx, *self.predict_f(xx), edgecol=c, fillcol=cf, alpha=0.3) if Fbars: fhat = np.dot(self.Li, np.dot(self.Kyi, self.Y.sum(1))) fcov = self.Li pb.errorbar(self.X[:, 0], fhat, color=c, yerr=2 * np.sqrt(np.diag(fcov)), elinewidth=2, linewidth=0) pb.xlim(xmin, xmax) pb.ylim(ymin, ymax) ndlutil.Tango.removeUpperTicks() ndlutil.Tango.removeRightTicks() #prediction for new functions if colour: c = ndlutil.Tango.coloursHex['mediumGreen'] cf = ndlutil.Tango.coloursHex['lightGreen'] for i in range(1, ncol): pb.subplot(nrow, ncol, self.Y.shape[1] * ncol + 1 + i) mu, var = self.predict_f(xx) var += np.sum([k.alpha for k in self.kerny.kerns]) ndlutil.utilities.gpplot(xx, mu, var, edgecol=c, fillcol=cf, alpha=0.3) pb.xlim(xmin, xmax) pb.ylim(ymin, ymax) pb.yticks([]) ndlutil.Tango.removeUpperTicks() else: if colour: c = ndlutil.Tango.coloursHex['mediumRed'] cf = ndlutil.Tango.coloursHex['lightRed'] cp = 'k' #ndlutil.Tango.coloursHex['Aluminium6'] else: c = ndlutil.Tango.coloursHex['Aluminium6'] cf = ndlutil.Tango.coloursHex['Aluminium1'] cp = ndlutil.Tango.coloursHex['Aluminium6'] ncol = self.Y.shape[1] + 1 nrow = 1 pb.figure(figsize=(ncol * ysize, nrow * xsize)) pb.subplot(nrow, ncol, 1) ndlutil.utilities.gpplot(xx, *self.predict_f(xx), edgecol=c, fillcol=cf, alpha=0.3) fhat = np.dot(self.Li, np.dot(self.Kyi, self.Y.sum(1))) fcov = self.Li if Fbars: pb.errorbar(self.X[:, 0], fhat, color=cp, yerr=2 * np.sqrt(np.diag(fcov)), elinewidth=2, linewidth=0) pb.xlim(xmin, xmax) pb.ylim(ymin, ymax) ndlutil.Tango.removeUpperTicks() ndlutil.Tango.removeRightTicks() #colours for the subsequent plots if colour: c = ndlutil.Tango.coloursHex['mediumBlue'] cf = ndlutil.Tango.coloursHex['lightBlue'] for i, y in enumerate(self.Y.T): pb.subplot(nrow, ncol, i + 2) pb.plot(self.X, y[:, None], color=cp, marker='x', linewidth=0, mew=2) ndlutil.utilities.gpplot(xx, *self.predict_y(xx, i), edgecol=c, fillcol=cf, alpha=0.3) pb.xlim(xmin, xmax) pb.ylim(ymin, ymax) pb.yticks([]) ndlutil.Tango.removeUpperTicks()
def BarometerLightningGraph(source, days, delay): print("BarometerLightningGraph source:%s days:%s" % (source, days)) print("sleeping seconds:", delay) time.sleep(delay) print("BarometerLightningGraph running now") # blink GPIO LED when it's run GPIO.setup(18, GPIO.OUT) GPIO.output(18, True) time.sleep(0.2) GPIO.output(18, False) # now we have get the data, stuff it in the graph try: print("trying database") db = mdb.connect('localhost', 'root', config.MySQL_Password, 'ProjectCuracao2') cursor = db.cursor() query = "SELECT TimeStamp, bmp180SeaLevel, as3935LastInterrupt, as3935LastDistance FROM WeatherData where now() - interval %i hour < TimeStamp" % ( days * 24) print "query=", query cursor.execute(query) result = cursor.fetchall() t = [] s = [] u = [] v = [] for record in result: t.append(record[0]) s.append(record[1]) u.append(record[2]) v.append(record[3]) fig = pyplot.figure() print("count of t=", len(t)) if (len(t) == 0): return #dts = map(datetime.datetime.fromtimestamp, s) #fds = dates.date2num(t) # converted # matplotlib date format object hfmt = dates.DateFormatter('%m/%d-%H') ax = fig.add_subplot(111) for i in range(len(s)): s[i] = s[i] * 10 #ax.vlines(fds, -200.0, 1000.0,colors='w') ax.xaxis.set_major_locator(dates.HourLocator(interval=6)) ax.xaxis.set_major_formatter(hfmt) pylab.xticks(rotation='vertical') pyplot.subplots_adjust(bottom=.3) pylab.plot(t, s, color='b', label="Barometric Pressure (mb) ", linestyle="-", marker=".") pylab.xlabel("Hours") pylab.ylabel("millibars") pylab.legend(loc='upper left') pylab.axis([min(t), max(t), 900, 1100]) ax2 = pylab.twinx() pylab.ylabel("Last Interrupt / Distance ") # scale array for i in range(len(v)): v[i] = v[i] * 10 for i in range(len(u)): u[i] = u[i] * 10 pylab.plot(t, u, color='y', label="as3935 Last Interrupt", linestyle="-", marker=".") pylab.plot(t, v, color='r', label="as3935 Last Distance", linestyle="-", marker=".") pylab.axis([min(t), max(t), 0, max(u)]) pylab.legend(loc='lower left') pylab.figtext( .5, .05, ("Barometer and Lightning Statistics Last %i Days" % days), fontsize=18, ha='center') #pylab.grid(True) pyplot.setp(ax.xaxis.get_majorticklabels(), rotation=70) ax.xaxis.set_major_formatter(dates.DateFormatter('%m/%d-%H')) pyplot.show() try: pyplot.savefig( "/home/pi/RasPiConnectServer/static/BarometerLightningGraph.png" ) except: pyplot.savefig( "/home/pi/SDL_Pi_ProjectCuracao2/static/BarometerLightningGraph.png" ) except mdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1])
def drawAnnualChart(dates, hrs, visibility, title='', fs=16, dt=0): """ Draw charts computed by :func:`makeAnnualChart`. :INPUTS: dates, hrs, visibility Inputs suitable for pylab.contourf(dates, hrs, visibility) fs : scalar Font size """ # 2015-03-19 22:38 IJMC: Created import matplotlib.dates as mdates if True: #dt==0: ylabel = 'UTC Time' else: ylabel = '(UTC %+1.1f)' % dt obs = ephem.Observer() ddates = [] for d in dates: obs.date = str(d) ddates.append(obs.date.datetime()) fig = py.figure() #ax = py.gca() axpos = [.1, .12, .77, .76] ax = py.subplot(111, position=axpos) py.contourf(ddates, hrs, visibility, cmap=py.cm.Greens) py.clim(0, 1.5) months = mdates.MonthLocator() # every month ax.xaxis.set_major_locator(months) #ax.format_xdata = mdates.DateFormatter('%Y-%m-%d') hfmt = mdates.DateFormatter('%b ') ax.xaxis.set_major_formatter(hfmt) #yt = (np.array([0, 4, 8, 12, 16, 20, 24]) - 12) + dt yt = np.array([0, 4, 8, 12, 16, 20, 24]) ax.set_yticks(yt) ax.yaxis.set_ticks(range(25), minor=True) ax.set_yticklabels(yt % 24) #[tt.set_rotation(30) for tt in ax.get_xticklabels()] #ax.set_xlabel('Date', fontsize=fs) ax.set_ylabel(ylabel, fontsize=fs) ax.set_title(title, fontsize=fs * 1.2) ax.grid(axis='x') ax2 = py.twinx() ax2.set_position(axpos) yt2 = np.arange(-24, 24, 3) yt2 = yt2[(yt2 >= dt) * (yt2 <= (24 + dt))] ax2.set_ylim(dt, 24 + dt) ax2.set_yticks(yt2) ax2.set_ylabel('Local Time: UTC %+1.1f' % dt, fontsize=fs) ax2.grid(axis='y') tlabs = yt2 % 12 tlabs = [] for yt in yt2: if (yt % 24) == 12: lab = 'noon' elif (yt % 24) == 0: lab = 'mdnt' elif (yt % 24) >= 12: lab = '%i pm' % (yt % 12) else: lab = '%i am' % (yt % 12) tlabs.append(lab) ax2.set_yticklabels(tlabs) ax2.yaxis.set_ticks(range(dt, dt + 25), minor=True) #fig.autofmt_xdate() #ax.set_position([.15, .2, .8, .68]) return fig