def plot_contour(mesh, field, plot_boundary=False, plot_fill=False, plot_patch=False): if plot_fill: plt.subplot(2, 1, 1) x1 = np.min(mesh[:, :, 0]) x2 = np.max(mesh[:, :, 0]) y1 = np.min(mesh[:, :, 1]) y2 = np.max(mesh[:, :, 1]) plt.imshow(field.T, cmap='Greys', extent=[x1, x2, y1, y2]) #, zorder=2) if plot_boundary: length_x = mesh[-1, 0, 0] length_y = mesh[0, -1, 1] plt.subplot(2, 1, 2) plt.contour(mesh[:, ::-1, 0], mesh[:, ::-1, 1], field, levels=[0]) #, zorder=3) plt.plot([0] * 2, [0, length_y], 'k', linewidth=0.4) #, zorder=1) plt.plot([length_x] * 2, [0, length_y], 'k', linewidth=0.4) #, zorder=1) plt.plot([0, length_x], [0] * 2, 'k', linewidth=0.4) #, zorder=1) plt.plot([0, length_x], [length_y] * 2, 'k', linewidth=0.4) #, zorder=1) plt.axis('equal') if plot_patch: pass
def zsview(im, cmap=pl.cm.gray, figsize=(8,5), contours=False, ccolor='r'): z1, z2 = zscale(im) pl.figure(figsize=figsize) pl.imshow(im, vmin=z1, vmax=z2, origin='lower', cmap=cmap, interpolation='none') if contours: pl.contour(im, levels=[z2], origin='lower', colors=ccolor) pl.tight_layout()
def plot_svc(X, y, mysvc, bounds=None, grid=50): if bounds is None: xmin = np.min(X[:, 0], 0) xmax = np.max(X[:, 0], 0) ymin = np.min(X[:, 1], 0) ymax = np.max(X[:, 1], 0) else: xmin, ymin = bounds[0], bounds[0] xmax, ymax = bounds[1], bounds[1] aspect_ratio = (xmax - xmin) / (ymax - ymin) xgrid, ygrid = np.meshgrid(np.linspace(xmin, xmax, grid), np.linspace(ymin, ymax, grid)) plt.gca(aspect=aspect_ratio) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.xticks([]) plt.yticks([]) plt.hold(True) plt.plot(X[y == 1, 0], X[y == 1, 1], 'bo') plt.plot(X[y == -1, 0], X[y == -1, 1], 'ro') box_xy = np.append(xgrid.reshape(xgrid.size, 1), ygrid.reshape(ygrid.size, 1), 1) if mysvc is not None: scores = mysvc.decision_function(box_xy) else: print 'You must have a valid SVC object.' return None; CS=plt.contourf(xgrid, ygrid, scores.reshape(xgrid.shape), alpha=0.5, cmap='jet_r') plt.contour(xgrid, ygrid, scores.reshape(xgrid.shape), levels=[0], colors='k', linestyles='solid', linewidths=1.5) plt.contour(xgrid, ygrid, scores.reshape(xgrid.shape), levels=[-1,1], colors='k', linestyles='dashed', linewidths=1) plt.plot(mysvc.support_vectors_[:,0], mysvc.support_vectors_[:,1], 'ko', markerfacecolor='none', markersize=10) CB = plt.colorbar(CS)
def plot_solution(problem_data, solution): from numpy import linspace from matplotlib.pylab import contour, colorbar, contourf, xlabel, ylabel, title, show from matplotlib.mlab import griddata print(" * Preparing for plotting...") NN = problem_data["NN"] # Extract node coordinates seperately for plotting x, y = [0] * NN, [0] * NN for i, node in enumerate(problem_data["nodes"]): x[i] = node[0] y[i] = node[1] # Refine the contour plot mesh for a "smoother" image, by generating a # 200*200 grid xi = linspace(min(x), max(x), 200) yi = linspace(min(y), max(y), 200) # Approximate the mid values from neighbors zi = griddata(x, y, solution, xi, yi) print(" * Plotting...") # Plot the contour lines with black contour(xi, yi, zi, 15, linewidths=0.5, colors='k') # Plot the filled contour plot plot = contourf(xi, yi, zi, 15, antialiased=True) colorbar(plot, format="%.3f").set_label("T") xlabel('X') ylabel('Y') title("Contour plot of T values for {0}".format(problem_data["title"])) show()
def plot_hyperplane(X, Y, model, K, plot_id, d=500): I0 = np.where(Y == -1)[0] I1 = np.where(Y == 1)[0] plt.subplot(plot_id) plt.plot(X[I1, 0], X[I1, 1], 'og') plt.plot(X[I0, 0], X[I0, 1], 'xb') min_val = np.min(X, 0) max_val = np.max(X, 0) clf = model() clf.train(X, Y, K) x0_plot = np.linspace(min_val[0, 0], max_val[0, 0], d) x1_plot = np.linspace(min_val[0, 1], max_val[0, 1], d) [x0, x1] = plt.meshgrid(x0_plot, x1_plot) Y_all = np.matrix(np.zeros([d, d])) for i in range(d): X_all = np.matrix(np.zeros([d, 2])) X_all[:, 0] = np.matrix(x0[:, i]).T X_all[:, 1] = np.matrix(x1[:, i]).T Y_all[:, i] = clf.predict(X_all) plt.contour(np.array(x0), np.array(x1), np.array(Y_all), levels=[0.0], colors='red')
def make_2d_surface_contours(x, y, z, title='', x_axis_name='', y_axis_name='', z_axis_name='', extra_contour_line=None): fig = plt.figure() ax = plt.axes() X, Y, Z = grid(x, y, z, resX=187, resY=187) if extra_contour_line != None: contours2 = plt.contour(X, Y, Z, levels=[extra_contour_line], colors='blue', linestyles=':') # plt.plot([0], [0], ls=':',c='blue', label=entry['label']) ax.scatter(x, y, c='red', s=2, zorder=5) contours = plt.contour(X, Y, Z, colors='black', vmin=0.5, vmax=max(z)) plt.contourf(X, Y, Z, 100) ax.set_xlim([min(x), max(x)]) ax.set_ylim([min(y), max(y)]) plt.title(title) plt.xlabel(x_axis_name) plt.ylabel(y_axis_name) cbar = plt.colorbar() cbar.ax.set_ylabel(z_axis_name) plt.tight_layout() plt.show() plt.savefig('plot.png')
def plot(func, dataset, x1s, x1e, x2s, x2e, delta, levels, title=None, track=None, f_val=None): # t, a, b, c = dataset k1 = np.arange(x1s, x1e, delta) k2 = np.arange(x2s, x2e, delta) K1, K2 = np.meshgrid(k1, k2) FX = np.zeros(K1.shape) row, col = K1.shape for i in xrange(row): for j in xrange(col): FX[i, j] = func(array([K1[i, j], K2[i, j]]), *dataset) fig = plt.figure(title) subfig1 = fig.add_subplot(1, 2, 1) surf1 = plt.contour(K1, K2, FX, levels=levels, stride=0.001) if track: track = array(track) plt.plot(track[:, 0], track[:, 1]) plt.xlabel("k1") plt.ylabel("k2") subfig2 = fig.add_subplot(1, 2, 2, projection='3d') surf2 = subfig2.plot_wireframe(K1, K2, FX, rstride=10, cstride=10, color='y') plt.contour(K1, K2, FX, stride=1, levels=levels) if track != None and f_val != None: f_val = array(f_val) subfig2.scatter(track[:, 0], track[:, 1], f_val) plt.show()
def backGroundB(xk, Nk, w): prob = np.ones((100, 100)) A = np.linspace(0, 100, 100) B = np.linspace(0, 100, 100) A, B = np.meshgrid(A, B) x = [] for j in range(len(xk)): for k in range(Nk[j]): x.append(xk[j]) plt.figure(figsize=(12, 4)) plt.subplot(121) plt.hist(x, bins=len(xk)) plt.ylabel('Number of counts N') plt.xlabel('Measurement variable x') for i in range(len(xk)): Dk = (A * np.exp(-1 * (xk[i]**2) / (2 * w**2)) + B) prob *= (Nk[i] * np.log(Dk) - Dk) plt.subplot(122) plt.contour(A, B, prob) plt.ylabel('Background B') plt.xlabel('Amplitude A') plt.savefig('Background.png')
def plot_hyperplane(X, Y, model, K, plot_id, d = 500): I0 = np.where(Y==-1)[0] I1 = np.where(Y==1)[0] plt.subplot(plot_id) plt.plot(X[I1, 0], X[I1, 1], 'og') plt.plot(X[I0, 0], X[I0, 1], 'xb') min_val = np.min(X, 0) max_val = np.max(X, 0) clf = model() clf.train(X, Y, K) x0_plot = np.linspace(min_val[0, 0], max_val[0, 0], d) x1_plot = np.linspace(min_val[0, 1], max_val[0, 1], d) [x0, x1] = plt.meshgrid(x0_plot, x1_plot); Y_all = np.matrix(np.zeros([d, d])) for i in range(d): X_all = np.matrix(np.zeros([d, 2])) X_all[:, 0] = np.matrix(x0[:, i]).T X_all[:, 1] = np.matrix(x1[:, i]).T Y_all[:, i] = clf.predict(X_all) plt.contour(np.array(x0), np.array(x1), np.array(Y_all), levels = [0.0], colors = 'red')
def plot(m): col1 = '#0172B2' col2 = '#CC6600' mins, maxs, xx, yy, Xplot = gridParams() mf, vf = m.predict_f(Xplot) plt.figure() plt.plot(Xtrain[:, 0][Ytrain[:, 0] == 1], Xtrain[:, 1][Ytrain[:, 0] == 1], 'o', color=col1, mew=0, alpha=0.5) plt.plot(Xtrain[:, 0][Ytrain[:, 0] == -1], Xtrain[:, 1][Ytrain[:, 0] == -1], 'o', color=col2, mew=0, alpha=0.5) zu = m.sgp_layer.zu plt.plot(zu[:, 0], zu[:, 1], 'ro', mew=0, ms=4) plt.contour(xx, yy, mf.reshape(*xx.shape), [0], colors='k', linewidths=1.8, zorder=100)
def run_xor(): from operator import xor from scipy import special # create dataset print "generating dataset..." n = 25 Y = np.zeros((0, 3)) for i in [0, 1]: for j in [0, 1]: a = i * np.ones((n, 1)) b = j * np.ones((n, 1)) c = xor(bool(i), bool(j)) * np.ones((n, 1)) Y_ij = np.hstack((a, b, c)) Y = np.vstack((Y, Y_ij)) Y = 2 * Y - 1 # inference print "inference ..." M = 10 D = 2 lvm = aep.SGPLVM(Y, D, M, lik='Probit') lvm.optimise(method='L-BFGS-B', alpha=0.1, maxiter=200) # predict given inputs mx, vx = lvm.get_posterior_x() lims = [-1.5, 1.5] x = np.linspace(*lims, num=101) y = np.linspace(*lims, num=101) X, Y = np.meshgrid(x, y) X_ravel = X.ravel() Y_ravel = Y.ravel() inputs = np.vstack((X_ravel, Y_ravel)).T my, vy = lvm.predict_f(inputs) t = my / np.sqrt(1 + vy) Z = 0.5 * (1 + special.erf(t / np.sqrt(2))) for d in range(3): plt.figure() plt.scatter(mx[:, 0], mx[:, 1]) zu = lvm.sgp_layer.zu plt.plot(zu[:, 0], zu[:, 1], 'ko') plt.contour(X, Y, np.log(Z[:, d] + 1e-16).reshape(X.shape)) plt.xlim(*lims) plt.ylim(*lims) # Y_test = np.array([[1, -1, 1], [-1, 1, 1], [-1, -1, -1], [1, 1, -1]]) # # impute missing data # for k in range(3): # Y_test_k = Y_test # missing_mask = np.ones_like(Y_test_k) # missing_mask[:, k] = 0 # my_pred, vy_pred = lvm.impute_missing( # Y_test_k, missing_mask, # alpha=0.1, no_iters=100, add_noise=False) # print k, my_pred, vy_pred, Y_test_k plt.show()
def _plot_nullclines(self, resolution): """ Plot nullclines. Arguments resolution Resolution of plot """ x_mesh, y_mesh, ode_x, ode_y = self._get_ode_values(resolution) plt.contour( x_mesh, y_mesh, ode_x, levels=[0], linewidths=2, colors='black') plt.contour( x_mesh, y_mesh, ode_y, levels=[0], linewidths=2, colors='black', linestyles='dashed') lblx = mlines.Line2D( [], [], color='black', marker='', markersize=15, label=r'$\dot\varphi_0=0$') lbly = mlines.Line2D( [], [], color='black', linestyle='dashed', marker='', markersize=15, label=r'$\dot\varphi_1=0$') plt.legend(handles=[lblx, lbly], loc='best')
def plot(x,y,field,filename,c=200): plt.figure() # define grid. xi = np.linspace(min(x),max(x),100) yi = np.linspace(min(y),max(y),100) # grid the data. si_lin = griddata((x, y), field, (xi[None,:], yi[:,None]), method='linear') si_cub = griddata((x, y), field, (xi[None,:], yi[:,None]), method='linear') print np.min(field) print np.max(field) plt.subplot(211) # contour the gridded data, plotting dots at the randomly spaced data points. CS = plt.contour(xi,yi,si_lin,c,linewidths=0.5,colors='k') CS = plt.contourf(xi,yi,si_lin,c,cmap=plt.cm.jet) plt.colorbar() # draw colorbar # plot data points. # plt.scatter(x,y,marker='o',c='b',s=5) plt.xlim(min(x),max(x)) plt.ylim(min(y),max(y)) plt.title('Lineaarinen interpolointi') #plt.tight_layout() plt.subplot(212) # contour the gridded data, plotting dots at the randomly spaced data points. CS = plt.contour(xi,yi,si_cub,c,linewidths=0.5,colors='k') CS = plt.contourf(xi,yi,si_cub,c,cmap=plt.cm.jet) plt.colorbar() # draw colorbar # plot data points. # plt.scatter(x,y,marker='o',c='b',s=5) plt.xlim(min(x),max(x)) plt.ylim(min(y),max(y)) plt.title('Kuubinen interpolointi') plt.savefig(filename)
def draw_decision_boundary(X, y, model, title): resolution = 0.01 markers = ('o', 's', '^') colors = ('lightgreen', 'red', 'blue') cmap = mpl.colors.ListedColormap(colors) x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) mpd = model.predict(np.array([xx1.ravel(), xx2.ravel()]).T).reshape(xx1.shape) plt.contour(xx1, xx2, mpd, cmap=mpl.colors.ListedColormap(['k'])) plt.contourf(xx1, xx2, mpd, alpha=0.4, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=[cmap(idx)], marker=markers[idx], s=80, label=cl) plt.xlabel(iris.feature_names[2]) plt.ylabel(iris.feature_names[3]) plt.legend(loc='upper left') plt.title(title) return mpd
def plot_cost_function(data): x = data[:, 0] y = data[:, 1] theta_0_mesh, theta_1_mesh = np.meshgrid(np.arange(-10, 10, 0.01), np.arange(-1, 4, 0.01)) cost_all_points = np.zeros(theta_0_mesh.shape) cost_all_points = compute_costs_thetas(theta_0_mesh, theta_1_mesh, x, y) plt.contour(theta_0_mesh, theta_1_mesh, cost_all_points, 100) plt.show()
def contour(image): """ contour plot """ plt.figure() image = image.convert('L') plt.gray() plt.contour(image, origin='image') plt.axis('equal')
def visualFit(x, mu, sigma2): temp = np.arange(0, 35, 0.5) x1, x2 = np.meshgrid(temp, temp) z = multivariateGaussian( np.vstack((x1.flatten(), x2.flatten())).T, mu, sigma2) z = z.reshape(x1.shape) plt.plot(x[:, 0], x[:, 1], 'bx') plt.contour(x1, x2, z, np.power(10.0, np.arange(-20, 0, 3))) plt.xlabel('Latency (ms)') plt.ylabel('Throughput (mb/s)')
def sanity_steppar2(self): import numpy as np import matplotlib.pylab as plt from PyAstronomy import funcFit as fuf # Set up a Gaussian model # and create some "data" x = np.linspace(0,2,100) gf = fuf.GaussFit1d() gf["A"] = 0.87 gf["mu"] = 1.0 gf["sig"] = 0.2 y = gf.evaluate(x) y += np.random.normal(0.0, 0.1, len(x)) # Thaw parameters, which are to be fitted ... gf.thaw(["A", "mu", "sig"]) # ... and "disturb" starting values a little. gf["A"] = gf["A"] + np.random.normal(0.0, 0.1) gf["mu"] = gf["mu"] + np.random.normal(0.0, 0.1) gf["sig"] = gf["sig"] + np.random.normal(0.0, 0.03) # Find the best fit solution gf.fit(x, y, yerr=np.ones(len(x))*0.1) # Step the amplitude (area of the Gaussian) and the # center ("mu") of the Gaussian through the given # ranges. sp = gf.steppar(["A", "mu"], ranges={"A":[0.8, 0.95, 20], \ "mu":[0.96,1.05,15]}) # Get the values for `A`, `mu`, and chi-square # from the output of steppar. As = map(lambda x:x[0], sp) mus = map(lambda x:x[1], sp) chis = map(lambda x:x[2], sp) # Create a chi-square array using the # indices contained in the output. z = np.zeros((20, 15)) for s in sp: z[s[3]] = s[2] # Find minimum chi-square and define levels # for 68%, 90%, and 99% confidence intervals. cm = min(chis) levels = [cm+2.3, cm+4.61, cm+9.21] # Plot the contours to explore the confidence # interval and correlation. plt.xlabel("mu") plt.ylabel("A") plt.contour(np.sort(np.unique(mus)), np.sort(np.unique(As)), z, \ levels=levels) # Plot the input value plt.plot([1.0], [0.87], 'k+', markersize=20)
def contourplot(objfun, xmin, xmax, ymin, ymax, ncontours=50, fill=True): x = np.linspace(xmin, xmax, 200) y = np.linspace(ymin, ymax, 200) X, Y = np.meshgrid(x,y) Z = objfun(X,Y) if fill: plt.contourf(X,Y,Z,ncontours); # plot the contours else: plt.contour(X,Y,Z,ncontours); # plot the contours plt.scatter(1,1,marker="x",s=50,color="r"); # mark the minimum
def animate(self): plt.contour(self.X, self.Y, self.Z, colors="gray", levels=[0.4, 3, 15, 50, 150, 500, 1500, 5000]) plt.plot(1, 1, 'ro', markersize=15) plt.title(self.title, fontsize=20) plt.xlim(-4, 4) plt.ylim(-3, 3) plt.xlabel('x') plt.ylabel('y') anim = animation.FuncAnimation(self.fig, self.ani_update, init_func=self.ani_init, frames=self.frames, interval=self.interval, blit=True) return anim
def draw_grid_plot(): if not has_plt: return plt.imshow(z_sample, cmap=plt.cm.binary, origin='lower', interpolation='nearest', extent=(grid_min, grid_max, grid_min, grid_max)) plt.hold(True) # XXX: restore plt state plt.contour(np.linspace(grid_min, grid_max, grid_n), np.linspace(grid_min, grid_max, grid_n), z_actual) plt.savefig(grid_filename) plt.close()
def contour_variable(fname, varname, **kwargs): ncfname = os.path.join(ensemble_base_path, fname) try: ncf = nc.Dataset(ncfname, "r") except IOError as error: print(ncfname, "not found.") raise error plt.contour(np.squeeze(ncf.variables[varname][0:150, 0:150]), origin="lower", interpolation="nearest", **kwargs)
def plotDecisionBoundary(theta_p): u = np.linspace(-1, 1.5, 50) v = np.linspace(-1, 1.5, 50) z = np.zeros((np.size(u), np.size(v))) for i in range(np.size(u)): for j in range(np.size(v)): z[i][j] = np.dot(mapFeature(u[i], v[j]), theta_p) z = z.T plt.contour(u, v, z, [0, 0.0000001]) return
def backward(): x = tf.placeholder(tf.float32, shape=(None, 2)) y_ = tf.placeholder(tf.float32, shape=(None, 1)) X, Y_, Y_c = generateds.generateds() y = forward.forward(x, REGULARIZER) global_step = tf.Variable(0, trainable=False) learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE, global_step, 300 / BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True) #定义损失函数 loss_mse = tf.reduce_mean(tf.square(y - y_)) loss_total = loss_mse + tf.add_n(tf.get_collection('losses')) #反向传播方法 包含正则化 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total) #生成会话,训练STEPS轮 with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) for i in range(STEPS): start = (i * BATCH_SIZE) % 300 end = start + BATCH_SIZE sess.run(train_step, feed_dict={ x: X[start:end], y_: Y_[start:end] }) if i % 2000 == 0: loss_V = sess.run(loss_total, feed_dict={x: X, y_: Y_}) print("After %d step(s), loss is: %g" % (i, loss_V)) #xx在-3到3之间以步长为0.01,yy在-3到3之间以步长0.01,生成二维网格坐标点 xx, yy = np.mgrid[-3:3:.01, -3:3:.01] #将xx,yy拉直,并合成一个2列的矩阵,得到一个网格坐标点的集合 grid = np.c_[xx.ravel(), yy.ravel()] #将网格坐标点喂入神经网络,probs为输出 probs = sess.run(y, feed_dict={x: grid}) #probs的shape调整成xx的样子 probs = probs.reshape(xx.shape) plt.scatter(X[:, 0], X[:, 1], c=np.squeeze(Y_c)) plt.contour(xx, yy, probs, levels=[.5]) plt.show()
def chkimg(p, sub, title): import matplotlib.pylab as plt from numpy import mgrid plt.imshow(sub) y, x = mgrid[:60, :60] plt.contour(p(x, y)) plt.title(title) plt.show() ans = raw_input('Image Okay [y/n] ?') plt.clf() if ans.upper() == 'N': return False else: return True
def __call__(self, **params): p = ParamOverrides(self, params) name = p.plot_template.keys().pop(0) plot = make_template_plot(p.plot_template, p.sheet.views.Maps, p.sheet.xdensity, p.sheet.bounds, p.normalize, name=p.plot_template[name]) fig = plt.figure(figsize=(5, 5)) if plot: bitmap = plot.bitmap isint = plt.isinteractive( ) # Temporarily make non-interactive for plotting plt.ioff() # Turn interactive mode off plt.imshow(bitmap.image, origin='lower', interpolation='nearest') plt.axis('off') for (t, pref, sel, c) in p.overlay: v = plt.flipud(p.sheet.views.Maps[pref].view()[0]) if (t == 'contours'): plt.contour(v, [sel, sel], colors=c, linewidths=2) if (t == 'arrows'): s = plt.flipud(p.sheet.views.Maps[sel].view()[0]) scale = int(np.ceil(np.log10(len(v)))) X = np.array([x for x in xrange(len(v) / scale)]) v_sc = np.zeros((len(v) / scale, len(v) / scale)) s_sc = np.zeros((len(v) / scale, len(v) / scale)) for i in X: for j in X: v_sc[i][j] = v[scale * i][scale * j] s_sc[i][j] = s[scale * i][scale * j] plt.quiver(scale * X, scale * X, -np.cos(2 * np.pi * v_sc) * s_sc, -np.sin(2 * np.pi * v_sc) * s_sc, color=c, edgecolors=c, minshaft=3, linewidths=1) p.title = '%s overlaid with %s at time %s' % (plot.name, pref, topo.sim.timestr()) if isint: plt.ion() p.filename_suffix = "_" + p.sheet.name self._generate_figure(p) return fig
def boundary(X, y, theta): y_ = y.reshape(y.size,) classes = (0., 1.) colors = ('b', 'r') marks = ('o', '+') for i, color, mark in zip(classes, colors, marks): plt.scatter(np.array(X)[y_ == i, 0], np.array(X)[y_ == i, 1], c=color, marker=mark) def fn((ui,vj)): return map_feature(np.array(ui), np.array(vj)).dot(theta) plt.contour(*calc_contour(X, fn)) plt.legend(['y=%s' % i for i in classes] + ['Decision boundary']) plt.show()
def show(self, rootFilename): """ Plot the solution @param rootFilename a wild card expression, eg 'XXX_rk%d.txt' """ import glob from matplotlib import pylab import re import os dataWindows = {} for f in glob.glob(rootFilename): pe = int(re.search(r'_rk(\d+)\.txt', f).group(1)) dataWindows[pe] = numpy.loadtxt(f, unpack=False) nBigSizes = (self.decomp[0]*self.n, self.decomp[1]*self.n) bigData = numpy.zeros(nBigSizes, numpy.float64) for j in range(self.decomp[0]): begJ = j*self.n endJ = begJ + self.n for i in range(self.decomp[1]): pe = j*self.decomp[1] + i begI = i*self.n endI = begI + self.n minVal = min(dataWindows[pe].flat) maxVal = max(dataWindows[pe].flat) bigData[begJ:endJ, begI:endI] = dataWindows[pe] xs = self.x0s[1] + numpy.array([(i + 0.5)*self.hs[1] for i in \ range(1, self.decomp[1]*self.n-1)]) ys = self.x0s[0] + numpy.array([(j + 0.5)*self.hs[0] for j in \ range(1, self.decomp[0]*self.n-1)]) pylab.contour(xs, ys, bigData[1:-1,1:-1], 21) pylab.colorbar() # plot the domain decomp for m in range(1, self.decomp[0]): yVal = self.x0s[0] + m * self.ls[0] - self.hs[0] / 2.0 pylab.plot([xs[0], xs[-1]], [yVal, yVal], 'k--') yVal += self.hs[0] pylab.plot([xs[0], xs[-1]], [yVal, yVal], 'k--') for n in range(1, self.decomp[1]): xVal = self.x0s[1] + n * self.ls[1] - self.hs[1] / 2.0 pylab.plot([xVal, xVal], [ys[0], ys[-1]], 'k--') xVal += self.hs[1] pylab.plot([xVal, xVal], [ys[0], ys[-1]], 'k--') pylab.show() fname = re.sub(r'_rk\*.txt', '', rootFilename) + '.png' print 'saving colorplot in file ' + fname pylab.savefig(fname)
def plot(self, func, interp=True, plotter='imshow'): import matplotlib as mpl from matplotlib import pylab as pl if interp: lpi = self.interpolator(func) z = lpi[self.yrange[0]:self.yrange[1]:complex(0, self.nrange), self.xrange[0]:self.xrange[1]:complex(0, self.nrange)] else: y, x = np.mgrid[ self.yrange[0]:self.yrange[1]:complex(0, self.nrange), self.xrange[0]:self.xrange[1]:complex(0, self.nrange)] z = func(x, y) z = np.where(np.isinf(z), 0.0, z) extent = (self.xrange[0], self.xrange[1], self.yrange[0], self.yrange[1]) pl.ioff() pl.clf() pl.hot() # Some like it hot if plotter == 'imshow': pl.imshow(np.nan_to_num(z), interpolation='nearest', extent=extent, origin='lower') elif plotter == 'contour': Y, X = np.ogrid[ self.yrange[0]:self.yrange[1]:complex(0, self.nrange), self.xrange[0]:self.xrange[1]:complex(0, self.nrange)] pl.contour(np.ravel(X), np.ravel(Y), z, 20) x = self.x y = self.y lc = mpl.collections.LineCollection(np.array([ ((x[i], y[i]), (x[j], y[j])) for i, j in self.tri.edge_db ]), colors=[(0, 0, 0, 0.2)]) ax = pl.gca() ax.add_collection(lc) if interp: title = '%s Interpolant' % self.name else: title = 'Reference' if hasattr(func, 'title'): pl.title('%s: %s' % (func.title, title)) else: pl.title(title) pl.show() pl.ion()
def plot_model(data_array, mixture, axis=(0, 1), samples=20, contour_lines=20): """ Plot the scaterplot of data_array and the contour lines of the probability for the mixture. """ import matplotlib import matplotlib.pylab as plt import matplotlib.cm as cm axis = list(axis) if isinstance(mixture, GMClusterModel): mixture = mixture.norm_model if isinstance(data_array, Orange.data.Table): data_array, _, _ = data_array.to_numpy_MA() array = data_array[:, axis] weights = mixture.weights means = mixture.means[:, axis] covariances = [cov[axis, :][:, axis] for cov in mixture.covariances ] # TODO: Need the whole marginal distribution. gmm = GMModel(weights, means, covariances) min = numpy.min(array, 0) max = numpy.max(array, 0) extent = (min[0], max[0], min[1], max[1]) X = numpy.linspace(min[0], max[0], samples) Y = numpy.linspace(min[1], max[1], samples) Z = numpy.zeros((X.shape[0], Y.shape[0])) for i, x in enumerate(X): for j, y in enumerate(Y): Z[i, j] = gmm([x, y]) plt.plot(array[:, 0], array[:, 1], "ro") plt.contour(X, Y, Z.T, contour_lines, extent=extent) im = plt.imshow(Z.T, interpolation='bilinear', origin='lower', cmap=cm.gray, extent=extent) plt.plot(means[:, 0], means[:, 1], "b+") plt.show()
def show(self, rootFilename): """ Plot the solution @param rootFilename a wild card expression, eg 'XXX_rk%d.txt' """ import glob from matplotlib import pylab import re import os dataWindows = {} for f in glob.glob(rootFilename): pe = int(re.search(r'_rk(\d+)\.txt', f).group(1)) dataWindows[pe] = numpy.loadtxt(f, unpack=False) nBigSizes = (self.decomp[0] * self.n, self.decomp[1] * self.n) bigData = numpy.zeros(nBigSizes, numpy.float64) for j in range(self.decomp[0]): begJ = j * self.n endJ = begJ + self.n for i in range(self.decomp[1]): pe = j * self.decomp[1] + i begI = i * self.n endI = begI + self.n minVal = min(dataWindows[pe].flat) maxVal = max(dataWindows[pe].flat) bigData[begJ:endJ, begI:endI] = dataWindows[pe] xs = self.x0s[1] + numpy.array([(i + 0.5)*self.hs[1] for i in \ range(1, self.decomp[1]*self.n-1)]) ys = self.x0s[0] + numpy.array([(j + 0.5)*self.hs[0] for j in \ range(1, self.decomp[0]*self.n-1)]) pylab.contour(xs, ys, bigData[1:-1, 1:-1], 21) pylab.colorbar() # plot the domain decomp for m in range(1, self.decomp[0]): yVal = self.x0s[0] + m * self.ls[0] - self.hs[0] / 2.0 pylab.plot([xs[0], xs[-1]], [yVal, yVal], 'k--') yVal += self.hs[0] pylab.plot([xs[0], xs[-1]], [yVal, yVal], 'k--') for n in range(1, self.decomp[1]): xVal = self.x0s[1] + n * self.ls[1] - self.hs[1] / 2.0 pylab.plot([xVal, xVal], [ys[0], ys[-1]], 'k--') xVal += self.hs[1] pylab.plot([xVal, xVal], [ys[0], ys[-1]], 'k--') pylab.show() fname = re.sub(r'_rk\*.txt', '', rootFilename) + '.png' print 'saving colorplot in file ' + fname pylab.savefig(fname)
def plot_non_linear_boundary(theta, Xlabel='X', Ylabel='Y', plot_title='plot'): u = np.linspace(-1, 1.5, 50) v = np.linspace(-1, 1.5, 50) z = np.zeros((len(u), len(v))) for i in range(len(u)): for j in range(len(v)): z[i, j] = (map_feature(np.array(u[i]), np.array(v[j])).dot(np.array(theta))) z = z.T contour(u, v, z) title(plot_title) xlabel(Xlabel) ylabel(Ylabel) show()
def plot(self, func, interp=True, plotter='imshow'): import matplotlib as mpl from matplotlib import pylab as pl if interp: lpi = self.interpolator(func) z = lpi[self.yrange[0]:self.yrange[1]:complex(0, self.nrange), self.xrange[0]:self.xrange[1]:complex(0, self.nrange)] else: y, x = np.mgrid[ self.yrange[0]:self.yrange[1]:complex(0, self.nrange), self.xrange[0]:self.xrange[1]:complex(0, self.nrange)] z = func(x, y) z = np.where(np.isinf(z), 0.0, z) extent = (self.xrange[0], self.xrange[1], self.yrange[0], self.yrange[1]) pl.ioff() pl.clf() pl.hot() # Some like it hot if plotter == 'imshow': pl.imshow(np.nan_to_num(z), interpolation='nearest', extent=extent, origin='lower') elif plotter == 'contour': Y, X = np.ogrid[ self.yrange[0]:self.yrange[1]:complex(0, self.nrange), self.xrange[0]:self.xrange[1]:complex(0, self.nrange)] pl.contour(np.ravel(X), np.ravel(Y), z, 20) x = self.x y = self.y lc = mpl.collections.LineCollection( np.array([((x[i], y[i]), (x[j], y[j])) for i, j in self.tri.edge_db]), colors=[(0, 0, 0, 0.2)]) ax = pl.gca() ax.add_collection(lc) if interp: title = '%s Interpolant' % self.name else: title = 'Reference' if hasattr(func, 'title'): pl.title('%s: %s' % (func.title, title)) else: pl.title(title) pl.show() pl.ion()
def diffDensity(fig, F2, F3, Trange): T1 = copy.deepcopy(Trange) T2 = copy.deepcopy(Trange) X, Y = numpy.meshgrid(T1, T2) p2 = [] p3 = [] for tau in Trange: p2.append(F2.pdf(tau)) p3.append(F3.pdf(tau)) p2mat = numpy.matrix(p2) p3mat = numpy.matrix(p3) pp2 = p2mat.T * p2mat pp3 = p3mat.T * p3mat PXP = numpy.array(numpy.log(pp3) - numpy.log(pp2)) # norm = plt.cm.colors.Normalize(vmin=-0.8,vmax=0.8) levels = numpy.arange(-2.0, .1, .1) cmap = plt.cm.get_cmap("PiYG") cmap.set_under(color='red', alpha=0.3) cmap.set_over(color='red', alpha=0.3) cset = plt.contourf(X, Y, PXP, levels=numpy.array([-10.0, 0, .8]), colors=('r', 'g'), alpha=.3) #plt.cm.get_cmap(cmap,2)) matplotlib.rcParams['contour.negative_linestyle'] = 'solid' levels = numpy.arange(-10, .8, .1) cs2 = plt.contour(X, Y, PXP, levels=levels, colors='k', alpha=.2) plt.clabel(cs2, levels[91:], fontsize=9, inline=1) # plt.colorbar(cset) plt.xlabel("First Opening Time $\\tau_1$") plt.ylabel("Second Opening Time $\\tau_2$") plt.title( "Test Statistic Comparing Models as a Function of Two Observations") plt.show()
def __hist2d(self, x, y, contour=False, bins=(200, 200), cmap="Purples", interpolation='nearest', origin="lower", colors="k"): """ Parameters ---------- bins : tuple of two ints """ H, xedges, yedges = np.histogram2d(x, y, bins) extent = [xedges.min(), xedges.max(), yedges.min(), yedges.max()] if not contour: plt.imshow(H, extent=extent, interpolation=interpolation, origin=origin, cmap=cmap, aspect="auto") # plt.colorbar(fontsize=4) else: CS = plt.contour(H, extent=extent, origin=origin, colors=colors) plt.clabel(CS, inline=1, fontsize=10)
def contour(X,Y,Z, extent=None, vrange=None, levels=None, extend='both', inaxis=None, cmap=None, addcolorbar=True, clabel=None, smooth=True, smoothlen=None): '''Build a super fancy contour image''' # Build up some nice ranges and levels to be plotted XX, YY = _getmesh(X,Y,Z) extent = _getextent(extent, XX, YY) vrange = _getvrange(vrange, XX,YY,Z, inaxis=inaxis) levels = _getlevels(levels, vrange) cmap = _getcmap(cmap) # Smooth if needed if smooth: X,Y,Z = _smooth(X,Y,Z, smoothlen) cs = pylab.contourf(X, Y, Z, levels, vmin=vrange[0], vmax=vrange[1], extent=extent, extend='both', cmap=cmap) ccs = pylab.contour(X, Y, Z, levels, vmin=vrange[0], vmax=vrange[1], cmap=cmap) # setup a colorbar, add in the lines, and then return it all out. if addcolorbar: cb = colorbar(cs, ccs, levels=levels, clabel=clabel) return cs, ccs, cb return cs, ccs
def viz_data(X, mu, sigma_sq): X1, X2 = np.meshgrid(np.arange(0,35,0.5), np.arange(0,35,0.5)) X1_flattened = X1.flatten() X2_flattened = X2.flatten() new_X = np.empty((X1_flattened.size,2)) new_X[:, 0] = X1_flattened new_X[:, 1] = X2_flattened Z = multivariate_gaussian(new_X, mu, sigma_sq) Z = Z.reshape(X1.shape) plt.hold() plt.plot(X[:,0], X[:,1], 'bx') plt.contour(X1, X2, Z, levels=10.0**(np.arange(-20.0,0,3))) plt.axis([0, 30, 0, 30]) plt.xlabel('Latency ms') plt.ylabel('Tput Mbps') plt.hold()
def plots(saliency_map): """ Positive/Negative values mean that when occluding that pixel the prediction went down/up. Parameters ---------- saliency_map : np.array. shape(x,y) Saliency map to be plotted """ # Plot mask and original image fig, ax = plt.subplots(1,2, figsize=(12, 4)) cf = ax[0].imshow(saliency_map, clim=[np.amin(saliency_map), np.amax(saliency_map)]) fig.colorbar(cf, ax=ax[0], fraction=0.046, pad=0.04) ax[0].set_title('Saliency map') x,y = saliency_map.shape ori_patch = np.array(ori)[(X-x)/2:(X+x)/2, (Y-y)/2:(Y+y)/2] #central patch ax[1].imshow(ori_patch) ax[1].set_title('Original image') # Plot contour plots of the mask over the image plt.figure() plt.imshow(ori_patch) CS = plt.contour(np.arange(saliency_map.shape[0]), np.arange(saliency_map.shape[1]), saliency_map) plt.clabel(CS, inline=1, fontsize=10) plt.title('Contour plot') # Plot RGBA image (soft mask) plt.figure() saliency_map -= np.amin(saliency_map) saliency_map /= np.amax(saliency_map) alpha_channel = np.round(saliency_map*255) rgba_arr = np.dstack((ori_patch, alpha_channel)).astype(np.uint8) plt.imshow(rgba_arr) plt.title('RGBA image')
def plot_contour(z,x,y,title="TITLE",xtitle="",ytitle="",xrange=None,yrange=None,plot_points=0,contour_levels=20, cmap=None,cbar=True,fill=False,cbar_title="",show=1): fig = plt.figure() if fill: fig = plt.contourf(x, y, z.T, contour_levels, cmap=cmap, origin='lower') else: fig = plt.contour( x, y, z.T, contour_levels, cmap=cmap, origin='lower') if cbar: cbar = plt.colorbar(fig) cbar.ax.set_ylabel(cbar_title) plt.title(title) plt.xlabel(xtitle) plt.ylabel(ytitle) # the scatter plot: if plot_points: axScatter = plt.subplot(111) axScatter.scatter( np.outer(x,np.ones_like(y)), np.outer(np.ones_like(x),y)) # set axes range plt.xlim(xrange) plt.ylim(yrange) if show: plt.show() return fig
def draw_boundary(classifier): dim = np.linspace(-1, 1.5, 1000) dx, dy = np.meshgrid(dim, dim) v = map_features(dx.flatten(), dy.flatten(), order=6) z = (np.dot(classifier.coef_, v) + classifier.intercept_).reshape( 1000, 1000) CS = plt.contour(dx, dy, z, levels=[0], colors=['r'])
def plot_model(data_array, mixture, axis=(0, 1), samples=20, contour_lines=20): """ Plot the scaterplot of data_array and the contour lines of the probability for the mixture. """ import matplotlib import matplotlib.pylab as plt import matplotlib.cm as cm axis = list(axis) if isinstance(mixture, GMClusterModel): mixture = mixture.norm_model if isinstance(data_array, Orange.data.Table): data_array, _, _ = data_array.to_numpy_MA() array = data_array[:, axis] weights = mixture.weights means = mixture.means[:, axis] covariances = [cov[axis,:][:, axis] for cov in mixture.covariances] # TODO: Need the whole marginal distribution. gmm = GMModel(weights, means, covariances) min = numpy.min(array, 0) max = numpy.max(array, 0) extent = (min[0], max[0], min[1], max[1]) X = numpy.linspace(min[0], max[0], samples) Y = numpy.linspace(min[1], max[1], samples) Z = numpy.zeros((X.shape[0], Y.shape[0])) for i, x in enumerate(X): for j, y in enumerate(Y): Z[i, j] = gmm([x, y]) plt.plot(array[:,0], array[:,1], "ro") plt.contour(X, Y, Z.T, contour_lines, extent=extent) im = plt.imshow(Z.T, interpolation='bilinear', origin='lower', cmap=cm.gray, extent=extent) plt.plot(means[:, 0], means[:, 1], "b+") plt.show()
def plot_interpolated(self): plt.contourf(self.get_Xinterpolated_mesh(), self.get_Yinterpolated_mesh(), self.Z_INTERPOLATED, 50, cmap=mpl.cm.jet) plt.colorbar() plt.contour(self.get_Xinterpolated_mesh(), self.get_Yinterpolated_mesh(), self.Z_INTERPOLATED, 20, colors="k") plt.plot(self.Xdeformed(), self.Ydeformed(), "or", label="Data") plt.legend() # plt.title = "Interpolated" <---- THIS MAKES ERROR IN THE NEXT PLOT!!!!!!!!!!!!!!!!! plt.grid() plt.show()
def plot(points, col): n = 256 x = np.linspace(-100, 100, n) y = np.linspace(-100, 100, n) X, Y = np.meshgrid(x, y) xs = [] ys = [] pl.contourf(X, Y, fun([X, Y]), 8, alpha=.75, cmap='jet') pl.contour(X, Y, fun([X, Y]), 8, colors='black', linewidth=.5) for i in range(len(points)): xs.append(points[i][0]) ys.append(points[i][1]) pl.plot(xs, ys, marker='o', linestyle='--', color=str(col), label='Square')
def plotDecisonBoundary(theta, X, y): plotData() zi = np.linspace(-1.5, 1.5, 50) zj = np.linspace(-1.5, 1.5, 50) z = np.ones((zi.size, zj.size)) print(np.shape(z)) for i in range(0, zi.size): for j in range(0, zj.size): z[i][j] = np.dot(mapFeature(zi[i], zj[j]), theta) plt.contour(zi, zj, z, levels=[0], colors='black', label='Decision Boundary') plt.show()
def plot_contour_pair(xi, yi, zi): fig = plt.figure(figsize=(2 * w, golden_mean * w * 2)) ax = fig.add_subplot(1, 2, 1, projection='3d') cs = plt.contour(xi, yi, zi, 15, linewidths=0.5, color='k') ax = fig.add_subplot(1, 2, 2, projection='3d') xig, yig = np.meshgrid(xi, yi) surf = ax.plot_surface(xig, yig, zi, linewidth=0) return fig
def conto_plots(Data,DataMHD,**kwargs): Qu = jana.quantities() Cur = Qu.Current(Data) CurMHD = Qu.Current(DataMHD) Fastsp = Qu.Magspeed(Data)['fast'] Slowsp = Qu.Magspeed(Data)['slow'] Alfvsp = Qu.Magspeed(Data)['alfven'] Vpol = np.sqrt(Data.v1**2 + Data.v2**2) FastspMHD = Qu.Magspeed(DataMHD)['fast'] SlowspMHD = Qu.Magspeed(DataMHD)['slow'] AlfvspMHD = Qu.Magspeed(DataMHD)['alfven'] VpolMHD = np.sqrt(DataMHD.v1**2 + DataMHD.v2**2) fastrat = Fastsp/Vpol slowrat = Slowsp/Vpol Alfvrat = Alfvsp/Vpol fastratMHD = FastspMHD/VpolMHD slowratMHD = SlowspMHD/VpolMHD AlfvratMHD = AlfvspMHD/VpolMHD f1 = plt.figure(num=1) ax1 = f1.add_subplot(121) currcont=plt.contour(Data.x1,Data.x2,Cur.T,kwargs.get('Currents',[-0.7,-0.6,-0.5,-0.4,-0.3]),colors=kwargs.get('colors','r'),linestyles=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) plt.clabel(currcont,manual=True) currmhdcont = plt.contour(DataMHD.x1,DataMHD.x2,CurMHD.T,kwargs.get('Currents',[-0.7,-0.6,-0.5,-0.4,-0.3]),colors=kwargs.get('colors','k'),linestyles=kwargs.get('ls','-'),lw=kwargs.get('lw',2.0)) plt.clabel(currmhdcont,manual=True) plt.xlabel(r'r [AU]') plt.ylabel(r'z [AU]') plt.title(r'Total Current -- $\int\int J_{z} r dr d\phi$') ax2 = f1.add_subplot(122) plt.xlabel(r'r [AU]') #plt.ylabel(r'$z [AU]$') plt.title(r'Critical Surfaces') fcont=plt.contour(Data.x1,Data.x2,fastrat.T,[1.0],colors='r',linestyles='solid') plt.clabel(fcont,inline=1,fmt=r'Fast') scont=plt.contour(Data.x1,Data.x2,slowrat.T,[1.0],colors='r',linestyles='dashdot') plt.clabel(scont,inline=1,fmt=r'Slow') acont=plt.contour(Data.x1,Data.x2,Alfvrat.T,[1.0],colors='r',linestyles='dashed') plt.clabel(acont,inline=1,fmt=r'Alfv$\acute{e}$n') mfcont=plt.contour(DataMHD.x1,DataMHD.x2,fastratMHD.T,[1.0],colors='k',linestyles='solid') plt.clabel(mfcont,manual=1,fmt=r'Fast') mscont=plt.contour(DataMHD.x1,DataMHD.x2,slowratMHD.T,[1.0],colors='k',linestyles='dashdot') plt.clabel(mscont,manual=1,fmt=r'Slow') macont=plt.contour(DataMHD.x1,DataMHD.x2,AlfvratMHD.T,[1.0],colors='k',linestyles='dashed') plt.clabel(macont,manual=1,fmt=r'Alfv$\acute{e}$n')
def visualize_GD(): ''' Created on Oct 28, 2010 @author: Peter ''' import matplotlib import numpy as np import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as plt leafNode = dict(boxstyle="round4", fc="0.8") arrow_args = dict(arrowstyle="<-") matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'out' delta = 0.025 x = np.arange(-2.0, 2.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = -((X-1)**2) Z2 = -(Y**2) #Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) #Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) # difference of Gaussians Z = 1.0 * (Z2 + Z1)+5.0 # Create a simple contour plot with labels using default colors. The # inline argument to clabel will control whether the labels are draw # over the line segments of the contour, removing the lines beneath # the label plt.figure() CS = plt.contour(X, Y, Z) plt.annotate('', xy=(0.05, 0.05), xycoords='axes fraction', xytext=(0.2,0.2), textcoords='axes fraction', va="center", ha="center", bbox=leafNode, arrowprops=arrow_args ) plt.text(-1.9, -1.8, 'P0') plt.annotate('', xy=(0.2,0.2), xycoords='axes fraction', xytext=(0.35,0.3), textcoords='axes fraction', va="center", ha="center", bbox=leafNode, arrowprops=arrow_args ) plt.text(-1.35, -1.23, 'P1') plt.annotate('', xy=(0.35,0.3), xycoords='axes fraction', xytext=(0.45,0.35), textcoords='axes fraction', va="center", ha="center", bbox=leafNode, arrowprops=arrow_args ) plt.text(-0.7, -0.8, 'P2') plt.text(-0.3, -0.6, 'P3') plt.clabel(CS, inline=True, fontsize=10) plt.title('Gradient Ascent') plt.xlabel('x') plt.ylabel('y') plt.show()
def __call__(self, **params): p=ParamOverrides(self,params) name=p.plot_template.keys().pop(0) plot=make_template_plot(p.plot_template, p.sheet.views.Maps, p.sheet.xdensity,p.sheet.bounds, p.normalize,name=p.plot_template[name]) fig = plt.figure(figsize=(5,5)) if plot: bitmap=plot.bitmap isint=plt.isinteractive() # Temporarily make non-interactive for plotting plt.ioff() # Turn interactive mode off plt.imshow(bitmap.image,origin='lower',interpolation='nearest') plt.axis('off') for (t,pref,sel,c) in p.overlay: v = plt.flipud(p.sheet.views.Maps[pref].view()[0]) if (t=='contours'): plt.contour(v,[sel,sel],colors=c,linewidths=2) if (t=='arrows'): s = plt.flipud(p.sheet.views.Maps[sel].view()[0]) scale = int(np.ceil(np.log10(len(v)))) X = np.array([x for x in xrange(len(v)/scale)]) v_sc = np.zeros((len(v)/scale,len(v)/scale)) s_sc = np.zeros((len(v)/scale,len(v)/scale)) for i in X: for j in X: v_sc[i][j] = v[scale*i][scale*j] s_sc[i][j] = s[scale*i][scale*j] plt.quiver(scale*X, scale*X, -np.cos(2*np.pi*v_sc)*s_sc, -np.sin(2*np.pi*v_sc)*s_sc, color=c, edgecolors=c, minshaft=3, linewidths=1) p.title='%s overlaid with %s at time %s' %(plot.name,pref,topo.sim.timestr()) if isint: plt.ion() p.filename_suffix="_"+p.sheet.name self._generate_figure(p) return fig
def __hist2d(self,x,y,contour=False,bins=(200,200),cmap="Purples",interpolation='nearest',origin="lower", colors="k"): """ Parameters ---------- bins : tuple of two ints """ H, xedges, yedges = np.histogram2d(x, y, bins) extent = [xedges.min(), xedges.max(), yedges.min(), yedges.max()] if not contour: plt.imshow(H, extent=extent, interpolation=interpolation,origin=origin, cmap=cmap, aspect="auto") # plt.colorbar(fontsize=4) else: CS = plt.contour(H, extent=extent,origin=origin,colors=colors) plt.clabel(CS, inline=1, fontsize=10)
def scaling_plot(df, zcol, title, zdas=None, xcol='numIsilonNodes', xlabel=None, ycol='numPhysicalComputeNodes', ylabel=None): if xlabel == None: xlabel = xcol if ylabel == None: ylabel = ycol x = df[xcol].values y = df[ycol].values z = df[zcol].values # Set up a regular grid of interpolation points xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100) xi, yi = np.meshgrid(xi, yi) # Interpolate zi = scipy.interpolate.griddata((x, y), z, (xi, yi), method='cubic') fig = plt.figure(title) fig.clf() plt.set_cmap(cm.jet) plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower', extent=[x.min(), x.max(), y.min(), y.max()], aspect='auto') # Draw circles on actual measurement points plt.scatter(x, y, c=z) plt.colorbar() CS = plt.contour(xi, yi, zi, colors='k') plt.clabel(CS, inline=1, fontsize=10, fmt='%1.0f') if zdas is not None: dasNodes = np.arange(df.numPhysicalComputeNodes.min(), 2 * df.numPhysicalComputeNodes.max() + 1) dasZ = zdas * dasNodes CS = plt.contour(xi, yi, zi, colors='k', linestyles='dashed', levels=dasZ) fmtdict = {x[1]: 'DAS ' + str(int(x[0])) for x in zip(dasNodes, dasZ)} plt.clabel(CS, inline=1, fontsize=10, fmt=fmtdict) plt.title(title) plt.ylabel(ylabel) plt.xlabel(xlabel) plt.show()
def plot(x,y,data,filename): plt.figure() # define grid. xi = np.linspace(min(x),max(x),100) yi = np.linspace(min(y),max(y),100) # grid the data. si = griddata((x, y), data, (xi[None,:], yi[:,None]), method='linear') # contour the gridded data, plotting dots at the randomly spaced data points. CS = plt.contour(xi,yi,si,30,linewidths=0.5,colors='k') CS = plt.contourf(xi,yi,si,30,cmap=plt.cm.jet) plt.colorbar() # draw colorbar # plot data points. # plt.scatter(x,y,marker='o',c='b',s=5) plt.xlim(min(x),max(x)) plt.ylim(min(y),max(y)) plt.savefig(filename)
def plot(points): """ Plotting 2D function and way search """ n = 256 x = np.linspace(-12, 12, n) y = np.linspace(-12, 12, n) X, Y = np.meshgrid(x, y) xs = [] ys = [] pl.contourf(X, Y, fun([X, Y]), 8, alpha=0.75, cmap="jet") C = pl.contour(X, Y, fun([X, Y]), 8, colors="black", linewidth=0.5) for i in range(len(points)): xs.append(points[i][0]) ys.append(points[i][1]) pl.plot(xs, ys, marker="o", linestyle="--", color="r", label="Square")
def plot(points): ''' Plotting 2D function and way search ''' n = 256 x = np.linspace(-12, 12, n) y = np.linspace(-12, 12, n) X, Y = np.meshgrid(x, y) xs = [] ys = [] pl.contourf(X, Y, fun([X, Y]), 8, alpha=.75, cmap='jet') C = pl.contour(X, Y, fun([X, Y]), 8, colors='black', linewidth=.5) for i in range(len(points)): xs.append(points[i][0]) ys.append(points[i][1]) pl.plot(xs, ys, marker='o', linestyle='--', color='r', label='Square')
def PlotDecisionBoundary(theta, X, y): if np.shape(X)[1] <= 3: # 2 points to define a line, so choose two endpoints plot_x = np.zeros(2) plot_x[0] = np.min(X[:,1])-2 plot_x[1] = np.max(X[:,1])+2 # Calculate the decision boundary line plot_y = (-1/theta[2])*(theta[1]*plot_x + theta[0]) plt.figure() PlotData.PlotData(X[:,1:3], y) plt.plot(plot_x, plot_y, label = 'Decision Boundary') plt.legend(bbox_to_anchor=(0.4, 1.35), loc = 1) plt.xlim(30, 100) plt.ylim(30, 100) plt.show() else: # grid range u = np.linspace(-1, 1.5, 50) v = np.linspace(-1, 1.5, 50) z = np.zeros((len(u), len(v))) for i in range(len(u)): for j in range(len(v)): z[i,j] = MapFeature.MapFeature(np.array([u[i]]), np.array([v[j]])).dot(theta) z = z.T plt.figure() PlotData.PlotData(X[:,1:3], y) cs = plt.contour(u, v, z, levels = [0.0, 0.0], colors = 'k') cs.collections[0].set_label('Decision Boundary') plt.legend(bbox_to_anchor=(0.4, 1.35), loc = 1) # plt.xlim(30, 100) # plt.ylim(30, 100) plt.show()
def drawPredictionSpace( model ): #plt.figure() nGridPoints = 200 predictionPoints = getGrid( nGridPoints, [-6.,6.],[-6.,6.] )[1] predictions = np.array(model.predict( predictionPoints )[0]) redChannel = predictions[:,0].reshape(nGridPoints,nGridPoints) greenChannel = predictions[:,1].reshape(nGridPoints,nGridPoints) blueChannel = predictions[:,2].reshape(nGridPoints,nGridPoints) #plt.imshow( np.flipud( np.array( [ redChannel, blueChannel, greenChannel ] ).T ) ) plt.figure() levels = [0.35, 0.97, 0.991] for level in levels: # loop helps matplotlib2tikz plt.contour(predictionPoints[:,0].reshape(nGridPoints, nGridPoints), predictionPoints[:,1].reshape(nGridPoints, nGridPoints), redChannel, levels=[level], colors='r', lw=3) plt.contour(predictionPoints[:,0].reshape(nGridPoints, nGridPoints), predictionPoints[:,1].reshape(nGridPoints, nGridPoints), blueChannel, levels=[level], colors='g', lw=3) plt.contour(predictionPoints[:,0].reshape(nGridPoints, nGridPoints), predictionPoints[:,1].reshape(nGridPoints, nGridPoints), greenChannel, levels=[level], colors='b', lw=3) plt.plot(model.Z[:,0], model.Z[:,1], 'ko', mew=0, ms=5) for i,col in enumerate('rbg'): ii = model.Y.flat==i plt.plot(model.X[ii,0], model.X[ii,1],col+'o', mew=0, ms=6, alpha=0.5) plt.xlim(-6,6) plt.ylim(-5,5)
pdf_values = np.ndarray(shape) for ix in range(shape[0]): for iy in range(shape[1]): x, y = grid_x[ix, iy], grid_y[ix, iy] theoretical_pdf = computeTheoriquePDF(x, y) u = [x, y] tic = time.time() pdf_estimate = distribution.computePDF(u) toc = time.time() pdf_values[ix, iy] = pdf_estimate dt.append(toc - tic) print "dt = %s"%(toc-tic) delta += abs((pdf_estimate - theoretical_pdf))**2 error = pdf_estimate - theoretical_pdf abs_error = abs(error) / theoretical_pdf print "pdf_estimate=%s pdf_theoretical=%s, error=%s, abs_error=%s"%(pdf_estimate, theoretical_pdf, error, abs_error) # Variation of characteristic function delta /= (shape[0] * shape[1]) print "delta of pdf=%s" %(np.sqrt(delta)) try : import matplotlib.pylab as plt fig = plt.figure() plt.contour(pdf_values, vmin=np.min(pdf_values), vmax=np.max(pdf_values), origin='lower', extent=[xmin+0.25*dx, xmax-0.25*dx, ymin+0.25*dy, ymax-0.25*dy]) plt.colorbar() plt.savefig("3Normals2d_pdf.pdf") plt.close('all') except ImportError: ot.log.Warn("Matplotlib not found. Could not create iso values graph of pdf")