我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用matplotlib.pyplot.quiver()。
def normvectorfield(xs,ys,fs,**kw): """ plot normalized vector field kwargs ====== - length is a desired length of the lines (default: 1) - the rest of kwards are passed to plot """ length = kw.pop('length') if 'length' in kw else 1 x, y = np.meshgrid(xs, ys) # calculate vector field vx,vy = fs(x,y) # plot vecor field norm = length /np.sqrt(vx**2+vy**2) plt.quiver(x, y, vx * norm, vy * norm, angles='xy',**kw)
def vectorfield(xs,ys,fs,**kw): """ plot vector field (no normalization!) args ==== fs is a function that returns tuple (vx,vy) kwargs ====== - length is a desired length of the lines (default: 1) - the rest of kwards are passed to plot """ length= kw.pop('length') if 'length' in kw else 1 x, y=np.meshgrid(xs, ys) # calculate vector field vx,vy=fs(x,y) # plot vecor field norm = length plt.quiver(x, y, vx * norm, vy * norm, angles='xy',**kw)
def plot_quiver(pt, uv, title, masks=None, norm=-1, outpath='.'): if plt is None: return plt.ioff() if masks is None: masks = [np.ones(pt.shape[0])>0,] if norm > 0: uvlen = np.sqrt((uv**2).sum(axis=1)) uv[uvlen<norm,:] /= (1.0/norm) * uvlen[uvlen<norm][:,np.newaxis] colors = ['r','b','g','c','y'] plt.figure() for i,m in enumerate(masks): plt.quiver(pt[m,0], pt[m,1], uv[m,0], uv[m,1], color=colors[i%len(colors)], angles='xy', scale_units='xy', scale=1) plt.axis('equal') plt.title(title) plt.ylim([pt[:,1].max(),0]) save_figure(title, outpath)
def plot_samples(S, axis_list=None): plt.scatter(S[:, 0], S[:, 1], s=2, marker='o', zorder=10, color='steelblue', alpha=0.5) if axis_list is not None: colors = ['orange', 'red'] for color, axis in zip(colors, axis_list): axis /= axis.std() x_axis, y_axis = axis # Trick to get legend to work plt.plot(0.1 * x_axis, 0.1 * y_axis, linewidth=2, color=color) plt.quiver(0, 0, x_axis, y_axis, zorder=11, width=0.01, scale=6, color=color) plt.hlines(0, -3, 3) plt.vlines(0, -3, 3) plt.xlim(-3, 3) plt.ylim(-3, 3) plt.xlabel('x') plt.ylabel('y')
def mplot_function(f, vmin, vmax, logscale): mesh = f.function_space().mesh() if (mesh.geometry().dim() != 2): raise AttributeError('Mesh must be 2D') # DG0 cellwise function if f.vector().size() == mesh.num_cells(): C = f.vector().get_local() if logscale: return plt.tripcolor(mesh2triang(mesh), C, vmin=vmin, vmax=vmax, norm=cls.LogNorm() ) else: return plt.tripcolor(mesh2triang(mesh), C, vmin=vmin, vmax=vmax) # Scalar function, interpolated to vertices elif f.value_rank() == 0: C = f.compute_vertex_values(mesh) if logscale: return plt.tripcolor(mesh2triang(mesh), C, vmin=vmin, vmax=vmax, norm=cls.LogNorm() ) else: return plt.tripcolor(mesh2triang(mesh), C, shading='gouraud', vmin=vmin, vmax=vmax) # Vector function, interpolated to vertices elif f.value_rank() == 1: w0 = f.compute_vertex_values(mesh) if (len(w0) != 2*mesh.num_vertices()): raise AttributeError('Vector field must be 2D') X = mesh.coordinates()[:, 0] Y = mesh.coordinates()[:, 1] U = w0[:mesh.num_vertices()] V = w0[mesh.num_vertices():] C = np.sqrt(U*U+V*V) return plt.quiver(X,Y,U,V, C, units='x', headaxislength=7, headwidth=7, headlength=7, scale=4, pivot='middle') # Plot a generic dolfin object (if supported)
def mquiver(xs, ys, v, **kw): """wrapper function for quiver xs and ys are arrays of x's and y's v is a function R^2 -> R^2, representing vector field kw are passed to quiver verbatim""" X,Y = np.meshgrid(xs, ys) V = [[v(x,y) for x in xs] for y in ys] VX = [[w[0] for w in q] for q in V] VY = [[w[1] for w in q] for q in V] plt.quiver(X, Y, VX, VY, **kw)
def dirfield(xs, ys, f, **kw): """ wrapper function of mquiver that plots the direction field xs and ys are arrays of x's and y's f is a function R^2->R kw are passed to quiver verbatim """ xs, ys = list(xs), list(ys) #in case something wrong was given mquiver(xs, ys, lambda x,y: (1,f(x,y)), scale=90, headwidth=0.0, headlength=0.0, headaxislength=0.0,pivot='middle',angles='xy',**kw)
def plot_policy_learned(data_unpickle, color, fig_dir=None): # recover the policy poli = data_unpickle['policy'] # range to plot it X = np.arange(-2, 2, 0.5) Y = np.arange(-2, 2, 0.5) X, Y = np.meshgrid(X, Y) X_flat = X.reshape((-1, 1)) Y_flat = Y.reshape((-1, 1)) XY = np.concatenate((X_flat, Y_flat), axis=1) means_1 = np.zeros((np.size(X_flat), 1)) means_2 = np.zeros((np.size(Y_flat), 1)) logstd = np.zeros((np.size(X_flat), 2)) for i, xy in enumerate(XY): means_1[i], means_2[i] = poli.get_action(xy)[1]['mean'] logstd[i] = poli.get_action(xy)[1]['log_std'] means_1 = means_1.reshape(np.shape(X)) means_2 = means_2.reshape(np.shape(Y)) means_norm = np.sqrt(means_1 ** 2 + means_2 ** 2) plt.quiver(X, Y, means_1, means_2, scale=1, scale_units='x') plt.title('Final policy') # plt.show() if fig_dir: plt.savefig(os.path.join(fig_dir, 'policy_learned')) else: print("No directory for saving plots") ## estimate by MC the policy at 0!
def draw_traj(w_t, g_t, dw_t): plt.quiver(w_t[:,0], w_t[:,1], dw_t[:,0], dw_t[:,1], color='k') #plt.plot(w_t[:,0], w_t[:,1], '-*') # Parameters for the intelligent synapse model
def quiver(*args): if plt is None: return plt.ion() plt.figure() plt.quiver(*args) plt.show() plt.pause(3)
def plot_field(self): self.electric_field() X, Y = np.meshgrid(np.arange(-1.00, 1.01, 2./(len(self.lattice_in) - 1)), np.arange(-1.00, 1.01, 2./(len(self.lattice_in) - 1))) plt.figure(figsize = (8,8)) plt.quiver(X, Y, self.ex, self.ey, pivot = 'mid', units='width') plt.title('Electric field near two metal plates') # plt.xlim(-1.00, 1.01) # plt.ylim(-1.00, 1.01) # plt.show() return 0
def plot_instcat_offsets(df, visit_name, component, fontsize='x-small', field=None, arrow_scale=150.): """ Make a matplotlib.quiver plot of measured position offsets relative to the instance catalog values. Parameters ---------- df : pandas.DataFrame Data frame containing the true and measured coordinates and magnitudes and position offsets. visit_name : str Visit name combining the visit number and filter, e.g., 'v230-fr'. component : str Name of the component, e.g., 'R2:2' (for the full center raft), 'R:2,2 S:1,1' (for the central chip). fontsize : str or int, optional Font size to use in plots. Default: 'x-small' field : (float, float, float, float), optional Figure x- and y-dimensions in data units. Typically set to the plt.axis() value from the instcat_overlay plot. Default: None (i.e., use default axis range derived from plotted data.) arrow_scale : float Scaling factor for the quiver key arrow. Default: 150. """ X, Y = df['coord_ra_true'], df['coord_dec_true'] Xp, Yp = df['coord_ra'], df['coord_dec'] xhat = Xp - X yhat = Yp - Y # Set arrow lengths in degrees and apply arrow_scale magnification # normalized relative to the nominal x-axis range. scale_factor = arrow_scale/3600. length = scale_factor*df['offset'].values/np.sqrt(xhat**2 + yhat**2) q = plt.quiver(X, Y, length*xhat, length*yhat, units='xy', angles='xy', scale_units='xy', scale=1) plt.quiverkey(q, 0.9, 0.9, scale_factor, 'offset (1")', labelpos='N', fontproperties={'size': fontsize}) if field is not None: plt.axis(field) plt.xlabel('RA (deg)', fontsize=fontsize) plt.ylabel('Dec (deg)', fontsize=fontsize) plt.title('%(visit_name)s, %(component)s' % locals(), fontsize=fontsize)
def demo(): # Issue on mac os x: # Run using 'frameworkpython' instead of 'python' # # Generate points from true # underly distribution # Class 1 mean = np.array([3., 5.]) cov = np.array([[3., 0.], [0., 3.]]) N1 = 100 x1, y1 = np.random.multivariate_normal(mean, cov, N1).T plt.plot(x1, y1, 'o', color='blue') # Class 2 mean = np.array([5., 0.]) cov = np.array([[3., 0.], [0., 3.]]) N2 = 100 x2, y2 = np.random.multivariate_normal(mean, cov, N2).T plt.plot(x2, y2, 'o', color='red') # Run LDA lda = LDAProjection() for i in xrange(N1): x = np.array([x1[i], y1[i]]) lda.observe(x, 'c1') for i in xrange(N2): x = np.array([x2[i], y2[i]]) lda.observe(x, 'c2') y = lda.get_dimensions() # Get first eigenvector e1 = y[:, 0] plt.quiver(e1[0], e1[1], color="black") plt.quiver(1.0, 0.0, color="red") plt.xlim([-20.0, 20.0]) plt.ylim([-20.0, 20.0]) # Project points for i in range(N1): r = np.sqrt(x1[i]**2 + y1[i]**2) x = r*e1[0] y = r*e1[1] plt.plot(x, y, 'o', color="darkblue") # Project points for i in range(N2): r = np.sqrt(x2[i]**2 + y2[i]**2) x = r*e1[0] y = r*e1[1] plt.plot(x, y, 'o', color="darkred") plt.show()