def residual_map_special_deltapsi_add_on( reflections,experiments,matches,hkllist, predicted,plot,eta_deg,deff ): detector = experiments[0].detector crystal = experiments[0].crystal unit_cell = crystal.get_unit_cell() pxlsz = detector[0].get_pixel_size() model_millers = reflections["miller_index"] dpsi = flex.double() for match in matches: obs_miller = hkllist[match["pred"]] model_index= model_millers.first_index(obs_miller) raw_delta_psi = reflections["delpsical.rad"][model_index] deltapsi_envelope = (unit_cell.d(obs_miller)/deff) + math.pi*eta_deg/180. normalized_delta_psi = raw_delta_psi/deltapsi_envelope dpsi.append( normalized_delta_psi ) from matplotlib.colors import Normalize dnorm = Normalize() dnorm.autoscale(dpsi.as_numpy_array()) CMAP = plot.get_cmap("bwr") for match,dcolor in zip(matches,dpsi): #print dcolor, dnorm(dcolor), CMAP(dnorm(dcolor)) #blue represents negative delta psi: outside Ewald sphere; red, positive, inside Ewald sphere plot.plot([predicted[match["pred"]][1]/pxlsz[1]],[-predicted[match["pred"]][0]/pxlsz[0]],color=CMAP(dnorm(dcolor)), marker=".", markersize=5)
def visualize(U, V, savefile=False, stt=0): # im = plt.imshow(U) # plt.show() # im = plt.imshow(V) # plt.show() n, m = U.shape fig = plt.figure(num=None, figsize=(10, 10), facecolor='w', edgecolor='k') X, Y = np.mgrid[0:n, 0:m] EE = np.sqrt(U * U + V * V) cax = plt.axis('equal') plt.quiver(X, Y, U, V, alpha=.5) normalize = Normalize() cmap = normalize(EE.flatten()) normalize.autoscale(EE.flatten()) im = plt.quiver(X[::4, ::4], Y[::4, ::4], U[::4, ::4], V[::4, ::4], EE[::4, ::4], scale=20, headwidth=4, pivot='tail', angles='uv') if savefile == True: fig.colorbar(im) plt.savefig('Outputs/TanChau/' + 'vector_field_' + str(stt) + '.png') plt.show()
def plot_arrows_colors(U_array, GAMMA_array, ax, **kwargs): x = GAMMA_array[:-1] y = U_array[:-1] u = GAMMA_array[1:] - GAMMA_array[:-1] v = U_array[1:] - U_array[:-1] x_scaled = x / 0.76 y_scaled = y / 2.75 colors = (1 - y_scaled) * np.sign(y_scaled + x / 0.4 - 1) norm = Normalize() norm.autoscale(np.array([-1, 1])) colormap = cm.brg plt.quiver(x, y, u, v, scale_units='xy', angles='xy', scale=1, width=0.005, color=colormap(norm(colors))) ax.set_xlabel('$ \Gamma_{eff} $') ax.set_ylabel("$ U_{eff} $") ax.set_xlim([-0.025, 0.8]) ax.set_ylim([-0.05, 3.0]) ax.set_xticks(np.arange(0, 2.1, 0.2)) ax.set_yticks(np.arange(0, 4.1, 0.5)) custom_lines = [ Line2D([0], [0], color=colormap(0.), lw=2), Line2D([0], [0], color=colormap(.5), lw=2), Line2D([0], [0], color=colormap(1.), lw=2) ] ax.legend(custom_lines, ['FO', 'LM', 'SC'], \ loc="upper right",frameon=True,framealpha=0.7,facecolor='white',edgecolor='white') if 'fixedpoints' in kwargs and kwargs['fixedpoints'] == True: include_fixedpoints(ax, colors=True)
def graph(self): ''' Plots the positions and directions of the bar magnetisations as a quiver graph ''' grid = self.lattice X = grid[:, :, 0].flatten() Y = grid[:, :, 1].flatten() U = grid[:, :, 2].flatten() V = grid[:, :, 3].flatten() Z = grid[:, :, 4].flatten() norm = Normalize() norm.autoscale(Z) colormap = cm.inferno plt.figure() ax = plt.gca() ax.quiver(X, Y, U, V, color=colormap(norm(Z)), angles='xy', scale_units='xy', scale=1, pivot='mid') ax.set_xlim([-1, self.side_len_x]) ax.set_ylim([-1, self.side_len_y]) plt.draw() plt.show()
def plot_optical_flow(velocities, background=None): xs, ys, us, vs = velocities['xs'], velocities['ys'], velocities[ 'vel_xs'], velocities['vel_ys'] plt.figure() if background is not None: plt.imshow(background) ax = plt.gca() colors = np.arctan2(us, vs) norm = Normalize() if colors.size > 0: norm.autoscale(colors) colormap = cm.inferno ax.quiver(xs, ys, us, vs, angles='xy', scale_units='xy', scale=1, color=colormap(norm(colors))) plt.draw() plt.show()
def graph(self): ''' Plots the positions and directions of the bar magnetisations as a quiver graph ''' grid = self.lattice X = grid[:, :, 0].flatten() Y = grid[:, :, 1].flatten() Mx = grid[:, :, 2].flatten() My = grid[:, :, 3].flatten() Hc = grid[:, :, 4].flatten() C = grid[:, :, 5].flatten() norm = Normalize() norm.autoscale(Hc) colormap = cm.jet plt.figure() ax = plt.gca() ax.quiver(X, Y, Mx, My, color=colormap(norm(C)), linewidth=norm(Hc), angles='xy', scale_units='xy', scale=1, pivot='mid') ax.set_xlim([-1, self.side_len_x]) ax.set_ylim([-1, self.side_len_y]) plt.draw() plt.show()
def plot_column_vectors_2d(matrix): """ Plots column vectors from the supplied matrix in the 2D plane. The matrix must have shape (2,X), where X >= 1. :param matrix: a (2,X) matrix; x >= 1 :return: None. Displays 2D plot. """ if matrix.shape[0] != 2: raise ValueError("Matrix must have 2d column space") origin = np.zeros_like(matrix) fig, ax = plt.subplots() xmin, xmax = min(np.min(matrix[0]), 0), max(np.max(matrix[0]), 0) ymin, ymax = min(np.min(matrix[1]), 0), max(np.max(matrix[1]), 0) ax.axis(list(map(int, [xmin - 1, xmax + 1, ymin - 1, ymax + 1]))) ax.grid(True) colors = np.linalg.norm(matrix, axis=0) colormap = plt.get_cmap('jet') norm = Normalize() norm.autoscale(colors) ax.quiver(origin[0], origin[1], matrix[0], matrix[1], scale=1, color=colormap(norm(colors)), angles='xy', scale_units='xy')
def make_circ_hist(hist): # make circular histogram t = np.linspace(0, 1.75 * np.pi, 8) x = .1 * np.cos(t) y = .1 * np.sin(t) colors = np.arctan2(x, y) norm = Normalize() norm.autoscale(colors) colormap = cm.viridis hist = 100 * hist**2 plt.quiver(x, y, hist * x, hist * y, color=colormap(norm(colors)), angles='xy', scale_units='xy', scale=1, width=.013) circle = plt.Circle((0, 0), .1, color='k', fill=False) ax = plt.gca() ax.add_artist(circle) #ax.set_facecolor((250/256, 250/256, 250/256)) ax.axis('equal') ax.set_aspect('equal') plt.axis([-.6, .6, -.6, .6]) plt.xticks([]), plt.yticks([]) plt.axis('off') plt.show()
def flow_legend(): """ show quiver plot to indicate how arrows are colored in the flow() method. https://stackoverflow.com/questions/40026718/different-colours-for-arrows-in-quiver-plot """ ph = np.linspace(0, 2 * np.pi, 13) x = np.cos(ph) y = np.sin(ph) u = np.cos(ph) v = np.sin(ph) colors = np.arctan2(u, v) norm = Normalize() norm.autoscale(colors) # we need to normalize our colors array to match it colormap domain # which is [0, 1] colormap = cm.winter plt.figure(figsize=(6, 6)) plt.xlim(-2, 2) plt.ylim(-2, 2) plt.quiver(x, y, u, v, color=colormap(norm(colors)), angles='xy', scale_units='xy', scale=1) plt.show()
def rand_plot_2d_vec_GP(n_plots=4,min_x=-2,max_x=2,n_grid_points=10,l_scale=1,sigma_var=1, kernel_type="rbf",B=None,Ker_project=False,obs_noise=1e-4): ''' Inputs: n_plots: int number of samples and plot min_x,max_x,n_grid_points: see vec_gp_sampler_2dim l_scale,sigma_var,kernel_type,B,Ker_project: See mat_kernel obs_noise: float - variance of noise of observations Outputs: fig,ax of plots (matplotlib objects) ''' #Function hyperparameter for scaling size of function and colors (only for notebook): size_scale=2 colormap = cm.hot norm = Normalize() #Define figure and subplots, adjust space and title: fig, ax = plt.subplots(nrows=n_plots//2,ncols=2,figsize=(size_scale*10,size_scale*5)) fig.subplots_adjust(hspace=0.5) fig.suptitle('Vector field GP samples',fontsize=size_scale*10) for i in range(n_plots): #Create sample: X,Y=vec_gp_sampler_2dim(min_x,max_x,n_grid_points,l_scale,sigma_var, kernel_type,B) #Scale the color of the vectors based on the length C=-torch.norm(Y,dim=1) #Scale colors: norm.autoscale(C) #Scatter plot of locations: ax[i//2,i%2].scatter(X[:,0],X[:,1], color='black', s=2*size_scale) #Plots arrows: Q = ax[i//2,i%2].quiver(X[:,0],X[:,1],Y[:,0], Y[:,1],color=colormap(norm(C)),units='x', pivot='mid') #Subtitle: ax[i//2,i%2].set(title="Sample "+str(i)) return(fig,ax)
def model_to_pc2(model, x_start, y_start, resolution, width, height): """ Creates a PointCloud2 by sampling a regular grid of points from the given model. """ pc = PointCloud2() pc.header.stamp = rospy.get_rostime() pc.header.frame_id = 'map' xy_points = [] for x in map_range(x_start, x_start + width, resolution): for y in map_range(y_start, y_start + height, resolution): xy_points.append([x, y]) probs = model.score_samples(xy_points) # and normalise to range to make the visualisation prettier normaliser = Normalize() normaliser.autoscale(probs) probs = normaliser(probs) colour_map = plt.get_cmap('jet') colours = colour_map(probs, bytes=True) cloud = [] for i in range(len(probs)): cloud.append([xy_points[i][0], xy_points[i][1], 2*probs[i], pack_rgb(colours[i][0], colours[i][1], colours[i][2])]) return create_cloud_xyzrgb(pc.header, cloud)
def plot(self, dano_summation): from matplotlib import pyplot as plt if self.params.use_weights: wt = 1. / (self.diffs.sigmas() * self.diffs.sigmas()) order = flex.sort_permutation(wt) wt = wt.select(order) df = self.diffs.data().select(order) dano = dano_summation.select(self.sel0).select(order) from matplotlib.colors import Normalize dnorm = Normalize() dnorm.autoscale(wt.as_numpy_array()) CMAP = plt.get_cmap("rainbow") for ij in xrange(len(self.diffs.data())): #blue represents zero weight: red, large weight plt.plot([df[ij]], [dano[ij]], color=CMAP(dnorm(wt[ij])), marker=".", markersize=4) else: plt.plot(self.diffs.data(), dano_summation.select(self.sel0), "r,") plt.axes().set_aspect("equal") plt.axes().set_xlabel("Observed Dano") plt.axes().set_ylabel("Model Dano") plt.show()
def boxes(result, *, ax=None, scale_val=None, plot_undefined=False, cmap=None, **kwargs): """ Plots the phase diagram as a collection of boxes, which are colored according to the estimate of the phase in a given box. Parameters ---------- result: .Result Result of the :func:`.run` phase diagram calculation. ax: :py:mod:`matplotlib <matplotlib.pyplot>` ax Axes where the plot is drawn. add_cbar: bool Determines whether a colorbar is added to the figure. scale_val: list Values to which the colormap is scaled. By default, the colormap is scaled to the set of values which occur in the boxes. plot_undefined: bool Specifies whether the boxes of undefined phase should be plotted (in white). cmap: The colormap which is used to plot the phases. The colormap should take values normalized to [0, 1] and return a 4-tuple specifying the RGBA value (again normalized to [0, 1]. kwargs: Keyword arguments passed to :py:class:`matplotlib.patches.Rectangle`. """ if cmap is None: # don't do this in the signature, otherwise it gets set at import time cmap = plt.get_cmap() all_vals = sorted(set(result.points.values())) or [0] sqrs = [s for s in result.boxes if s.phase not in (None, PHASE_UNDEFINED)] vals = [s.phase for s in sqrs] norm = Normalize() if scale_val is None: norm.autoscale(all_vals) else: norm.autoscale(scale_val) box_colors = cmap([norm(v) for v in vals]) rect_properties = ChainMap(kwargs, dict(lw=0)) for color, box in zip(box_colors, sqrs): ax.add_patch( Rectangle(xy=box.corner, width=box.size[0], height=box.size[1], **ChainMap(rect_properties, dict(facecolor=color, edgecolor=color)))) if plot_undefined: for box in [b for b in result.boxes if b.phase is PHASE_UNDEFINED]: ax.add_patch( Rectangle(xy=box.corner, width=box.size[0], height=box.size[1], **ChainMap(rect_properties, dict(facecolor='white')))) return ax, cmap, norm, all_vals
def plot_column_vectors_with_transform_2d(matrix, transform): """ Displays a side-by-side plot of the column vectors in the supplied matrix and the column vectors in the transformed matrix matrix * transform. The matrix must have shape (2,X), where X >= 1. The transform must have shape (2,2) :param matrix: a (2,X) matrix; x >= 1 :param transform: a (2,2) transformation matrix. :return: None. Displays 2 2D subplots. """ if matrix.shape[0] != 2: raise ValueError("Matrix must have 2d column space") if transform.shape != (2, 2): raise ValueError("Transform matrix must have shape (2,2)") origin = np.zeros_like(matrix) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6)) colors = np.linalg.norm(matrix, axis=0) colormap = plt.get_cmap('jet') norm = Normalize() norm.autoscale(colors) trans_matrix = np.dot(transform, matrix) xmin, xmax = min(np.min(matrix[0]), 0), max(np.max(matrix[0]), 0) ymin, ymax = min(np.min(matrix[1]), 0), max(np.max(matrix[1]), 0) ax1.axis(list(map(int, [xmin - 1, xmax + 1, ymin - 1, ymax + 1]))) ax1.set_title("$A$") ax1.grid(True) ax1.quiver(origin[0], origin[1], matrix[0], matrix[1], color=colormap(norm(colors)), scale=1, angles='xy', scale_units='xy') xmin, xmax = min(np.min(trans_matrix[0]), 0), max(np.max(trans_matrix[0]), 0) ymin, ymax = min(np.min(trans_matrix[1]), 0), max(np.max(trans_matrix[1]), 0) ax2.axis(list(map(int, [xmin - 1, xmax + 1, ymin - 1, ymax + 1]))) ax2.set_title("$TA$") ax2.grid(True) ax2.quiver(origin[0], origin[1], trans_matrix[0], trans_matrix[1], color=colormap(norm(colors)), scale=1, angles='xy', scale_units='xy')
def opyfQuiverFieldColoredScaled(grid_x, grid_y, gridVx, gridVy, fig=None, ax=None, res=32, **args): fig, ax = getax(fig=fig, ax=ax) import opyf from matplotlib.colors import Normalize if 'cmap' not in args: args['cmap'] = mpl.cm.coolwarm cmap = args.get('cmap', mpl.cm.coolwarm) del args['cmap'] # one over N # Select randomly N vectors l, c = grid_x.shape resx = np.absolute(grid_x[0, 1]-grid_x[0, 0]) resy = np.absolute(grid_y[1, 0]-grid_y[0, 0]) densx = int(np.round(res/resx)) densy = int(np.round(res/resy)) lvec = np.arange(densy/2, l-densy/2, densy, dtype=int)+(l % densy)//2 cvec = np.arange(densx/2, c-densx/2, densx, dtype=int)+(l % densx)//2 new_grid_x = np.zeros(len(lvec)) size = (len(lvec), len(cvec)) temp_grid_x = grid_x[lvec, :] new_grid_x = temp_grid_x[:, cvec] temp_grid_y = grid_y[lvec, :] new_grid_y = temp_grid_y[:, cvec] new_gridVx = np.zeros(size) new_gridVy = np.zeros(size) for i in range(size[0]): for j in range(size[1]): new_gridVx[i, j] = np.mean( gridVx[lvec[i]-densy//2:lvec[i]+densy//2+1, cvec[j]-densx//2:cvec[j]+densx//2+1]) new_gridVy[i, j] = np.mean( gridVy[lvec[i]-densy//2:lvec[i]+densy//2+1, cvec[j]-densx//2:cvec[j]+densx//2+1]) TargetPoints = opyf.Interpolate.npGrid2TargetPoint2D( new_grid_x, new_grid_y) Velocities = opyf.Interpolate.npGrid2TargetPoint2D(new_gridVx, new_gridVy) Norme = (Velocities[:, 0]**2+Velocities[:, 1]**2)**0.5 if 'vlim' in args: vlim = args.get('vlim', [Norme.min(), Norme.max()]) if vlim is None: vlim = [Norme.min(), Norme.max()] del args['vlim'] else: vlim = [Norme.min(), Norme.max()] norm = Normalize() norm.autoscale(Norme) norm.vmin = vlim[0] norm.vmax = vlim[1] sm = mpl.cm.ScalarMappable(cmap=cmap, norm=norm) sm.set_array([]) qv = ax.quiver(TargetPoints[:, 0], TargetPoints[:, 1], Velocities[:, 0] / Norme[:], Velocities[:, 1]/Norme[:], color=cmap(norm(colors)), **args) return fig, ax, qv, sm
def opyfQuiverFieldColored(self, grid_x, grid_y, gridVx, gridVy, res=32, normalize=False, **args): from matplotlib.colors import Normalize cmap = self.cmap # one over N # Select randomly N vectors l, c = grid_x.shape resx = np.absolute(grid_x[0, 1]-grid_x[0, 0]) resy = np.absolute(grid_y[1, 0]-grid_y[0, 0]) densx = int(np.round(res/resx)) densy = int(np.round(res/resy)) lvec = np.arange(densy/2, l-densy/2, densy, dtype=int)+(l % densy)//2 cvec = np.arange(densx/2, c-densx/2, densx, dtype=int)+(c % densx)//2 new_grid_x = np.zeros(len(lvec)) size = (len(lvec), len(cvec)) temp_grid_x = grid_x[lvec, :] new_grid_x = temp_grid_x[:, cvec] temp_grid_y = grid_y[lvec, :] new_grid_y = temp_grid_y[:, cvec] new_gridVx = np.zeros(size) new_gridVy = np.zeros(size) for i in range(size[0]): for j in range(size[1]): new_gridVx[i, j] = np.mean( gridVx[lvec[i]-densy//2:lvec[i]+densy//2+1, cvec[j]-densx//2:cvec[j]+densx//2+1]) new_gridVy[i, j] = np.mean( gridVy[lvec[i]-densy//2:lvec[i]+densy//2+1, cvec[j]-densx//2:cvec[j]+densx//2+1]) TargetPoints = Interpolate.npGrid2TargetPoint2D( new_grid_x, new_grid_y) Velocities = Interpolate.npGrid2TargetPoint2D(new_gridVx, new_gridVy) Norme = (Velocities[:, 0]**2+Velocities[:, 1]**2)**0.5 if 'vlim' in args: vlim = args.get('vlim', [Norme.min(), Norme.max()]) if vlim is None: vlim = [Norme.min(), Norme.max()] del args['vlim'] else: vlim = [Norme.min(), Norme.max()] norm = Normalize() norm.autoscale(Norme) norm.vmin = vlim[0] norm.vmax = vlim[1] self.im = mpl.cm.ScalarMappable(cmap=cmap, norm=norm) self.im.set_array([]) if self.ax.get_ylim()[0] > self.ax.get_ylim()[1]: Velocities[:, 1] = -Velocities[:, 1] if normalize == False: qv = self.ax.quiver(TargetPoints[:, 0], TargetPoints[:, 1], Velocities[:, 0], Velocities[:, 1], color=cmap(norm(Norme)), **args) else: qv = self.ax.quiver(TargetPoints[:, 0], TargetPoints[:, 1], Velocities[:, 0] / Norme[:], Velocities[:, 1]/Norme[:], color=cmap(norm(Norme)), **args)
def plot_grid_map_hmm(transitions, mode, grid_res=1.0, grid_origin=None, map_=None, map_origin=None, map_res=1.0): """ Plot quiver plots which indicates traffic on different directions. Mode has to be either 'counts' or 'probs'. """ if grid_origin is None: grid_origin = [0.0, 0.0] if mode == 'counts': up, right, down, left = get_quiver_from_counts(transitions) #TODO: should not normalize over all values, should normalize over "to" dimension # we need to normalize our colors array to match it colormap domain # which is [0, 1] values = np.array([up, right, down, left]) norm = Normalize() norm.autoscale(values) values = norm(values) elif mode == 'probs': up, right, down, left = get_quiver_from_probs(transitions) values = np.array([up, right, down, left]) else: return # calculate x ans y axis x, y = \ [(np.arange(up.shape[ix]) + 0.5) * grid_res + \ grid_origin[ix] for ix in [0, 1]] x, y = np.meshgrid(x, y) quiveropts = \ dict( width=0.005, scale=1/0.15, headaxislength=0, headlength=0, zorder=9) # colormap = cm.magma # pick your colormap here, refer to # http://matplotlib.org/examples/color/colormaps_reference.html # and # http://matplotlib.org/users/colormaps.html # for details plt.rcParams['image.cmap'] = 'Greens' # plot up down left right lines # right #plt.quiver(x, y, np.ones_like(right) * 0.1, np.zeros_like(right), color=colormap(values[0, ...]), linewidths=np.digitize(right.flatten(), bins)*3, **quiveropts) plt.quiver(x, y, np.ones_like(right) * 0.1, np.zeros_like(right), values[1, ...], **quiveropts) # left plt.quiver(x, y, -np.ones_like(left)* 0.1, np.zeros_like(left), values[3,...], **quiveropts) # # up plt.quiver(x, y, np.zeros_like(up), np.ones_like(up)* 0.1, values[0,...], **quiveropts) # # down axes = plt.quiver(x, y, np.zeros_like(down), -np.ones_like(down)* 0.1, values[2,...], **quiveropts) # plot map if map_ is not None: show_map(map_, resolution=map_res, origin=map_origin) return axes
def plot(d, sphere=False): """ Plot directivity `d`. :param d: Directivity :type d: :class:`Directivity` :returns: Figure """ #phi = np.linspace(-np.pi, +np.pi, 50) #theta = np.linspace(0.0, np.pi, 50) phi = np.linspace(0.0, +2.0 * np.pi, 50) theta = np.linspace(0.0, np.pi, 50) THETA, PHI = np.meshgrid(theta, phi) # Directivity strength. Real-valued. Can be positive and negative. dr = d.using_spherical(THETA, PHI) if sphere: x, y, z = spherical_to_cartesian(1.0, THETA, PHI) else: x, y, z = spherical_to_cartesian(np.abs(dr), THETA, PHI) #R, THETA, PHI = cartesian_to_spherical(x, y, z) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') #p = ax.plot_surface(x, y, z, cmap=plt.cm.jet, rstride=1, cstride=1, linewidth=0) norm = Normalize() norm.autoscale(dr) colors = cm.jet(norm(dr)) m = cm.ScalarMappable(cmap=cm.jet, norm=norm) m.set_array(dr) p = ax.plot_surface(x, y, z, facecolors=colors, rstride=1, cstride=1, linewidth=0) plt.colorbar(m, ax=ax) ax.set_xlabel('$x$') ax.set_ylabel('$y$') ax.set_zlabel('$z$') return fig
def opyfQuiverPointCloudColored(X, V, fig=None, ax=None, nvec=3000, normalize=False, **args): from matplotlib.colors import Normalize if 'cmap' not in args: args['cmap'] = mpl.cm.coolwarm cmap = args.get('cmap', mpl.cm.coolwarm) del args['cmap'] fig, ax = getax(fig=fig, ax=ax) # one over N # Select randomly N vectors if len(X) < nvec: N = len(X) else: N = nvec print('only '+str(N)+'vectors ave been plotted because the number of velocity vectors is >' + str(nvec)) # print('use the *nvec* parameter to change the number of vecors displayed') ind = np.random.choice(np.arange(len(X)), N, replace=False) Xc = X[ind, :] Vc = V[ind, :] colors = (Vc[:, 0]**2+Vc[:, 1]**2)**0.5 if len(colors) == 0: colors = np.array([0]) if 'vlim' in args: vlim = args.get('vlim', [colors.min(), colors.max()]) if vlim is None: vlim = [colors.min(), colors.max()] del args['vlim'] else: vlim = [colors.min(), colors.max()] norm = Normalize() norm.autoscale(colors) norm.vmin = vlim[0] norm.vmax = vlim[1] sm = mpl.cm.ScalarMappable(cmap=cmap, norm=norm) sm.set_array([]) if ax.get_ylim()[0] > ax.get_ylim()[1]: Vc[:, 1] = -Vc[:, 1] if normalize == False: qv = ax.quiver(Xc[:, 0], Xc[:, 1], Vc[:, 0], Vc[:, 1], color=cmap(norm(colors)), **args) else: qv = ax.quiver(Xc[:, 0], Xc[:, 1], Vc[:, 0]/colors, Vc[:, 1]/colors, color=cmap(norm(colors)), **args) return fig, ax, qv, sm
class ArrayImage: """Dynamic pyglet image of a 2d numpy array using matplotlib colormaps.""" def __init__(self, array, cmap=cmaps.binary, norm=None, rescale=True): self.array = array self.cmap = cmap self.norm = Normalize() if norm is None else norm self.rescale = rescale self._array_normed = np.zeros(array.shape + (4, ), dtype=np.uint8) # self._array_normed = np.zeros(array.shape, dtype=np.uint8) # noinspection PyTypeChecker self._tex_data = (pyglet.gl.GLubyte * self._array_normed.size).from_buffer( self._array_normed) # self._tex_data = (pyglet.gl.GLubyte * self._array_normed.size).from_buffer(self._array_normed) self._update_array() format_size = 4 # format_size = 1 bytes_per_channel = 1 self.pitch = array.shape[1] * format_size * bytes_per_channel self.image = pyglet.image.ImageData(array.shape[0], array.shape[1], "RGBA", self._tex_data) # self.image = pyglet.image.ImageData(array.shape[0], array.shape[1], "L", self._tex_data) self._update_image() def set_array(self, data): self.array = data self.update() def _update_array(self): if self.rescale: self.norm.autoscale(self.array) self._array_normed[:] = self.cmap(self.norm(self.array), bytes=True) # self._array_normed[:] = self.cmap(self.norm(self.array), bytes=True)[:,:,0] def _update_image(self): self.image.set_data("RGBA", self.pitch, self._tex_data) # self.image.set_data("L", self.pitch, self._tex_data) def update(self): self._update_array() self._update_image()
def plot(d, sphere=False): """ Plot directivity `d`. :param d: Directivity :type d: :class:`Directivity` :returns: Figure """ #phi = np.linspace(-np.pi, +np.pi, 50) #theta = np.linspace(0.0, np.pi, 50) phi = np.linspace(0.0, +2.0*np.pi, 50) theta = np.linspace(0.0, np.pi, 50) THETA, PHI = np.meshgrid(theta, phi) # Directivity strength. Real-valued. Can be positive and negative. dr = d.using_spherical(THETA, PHI) if sphere: x, y, z = spherical_to_cartesian(1.0, THETA, PHI) else: x, y, z = spherical_to_cartesian( np.abs(dr), THETA, PHI ) #R, THETA, PHI = cartesian_to_spherical(x, y, z) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') #p = ax.plot_surface(x, y, z, cmap=plt.cm.jet, rstride=1, cstride=1, linewidth=0) norm = Normalize() norm.autoscale(dr) colors = cm.jet(norm(dr)) m = cm.ScalarMappable(cmap=cm.jet, norm=norm) m.set_array(dr) p = ax.plot_surface(x, y, z, facecolors=colors, rstride=1, cstride=1, linewidth=0) plt.colorbar(m, ax=ax) ax.set_xlabel('$x$') ax.set_ylabel('$y$') ax.set_zlabel('$z$') return fig
def opyfPointCloudColoredScatter(self, X, V, **args): from matplotlib.colors import Normalize norme = (V[:, 0]**2+V[:, 1]**2)**0.5 norm = Normalize() norm.autoscale(norme) vlim = args.get('vlim', [np.min(norme), np.max(norme)]) if vlim is None: vlim = [np.min(norme), np.max(norme)] args['vmin'] = vlim[0] args['vmax'] = vlim[1] if 'vlim' in args: del args['vlim'] if 'markersize' in args: del args['markersize'] # sc=ax.scatter(X[:,0], X[:,1],c=norme,color=cmapCS(norm(norme)),**args) self.im = self.ax.scatter(X[:, 0], X[:, 1], c=norme, cmap=self.cmap, **args)
def plot_diphthong_movement(): import matplotlib.pyplot as plt from matplotlib.colors import Normalize import matplotlib.cm as cm plt.gca().invert_yaxis() plt.gca().invert_xaxis() plt.xlabel("F2") plt.ylabel("F1") vec_start_x = [] vec_start_y = [] vec_comp_x = [] vec_comp_y = [] phones = [] for phone, first_point, second_point in diphthong_data(): phones.append(phone) vec_start_x.append(first_point[1]) vec_start_y.append(first_point[0]) vec_comp_x.append(second_point[1] - first_point[1]) vec_comp_y.append(second_point[0] - first_point[0]) phone_set = sorted(list(set(phones))) phone_dict = {p: i for i, p in enumerate(phone_set)} colors = [phone_dict[p] for p in phones] norm = Normalize() norm.autoscale(colors) colormap = cm.cool plt.quiver(vec_start_x, vec_start_y, vec_comp_x, vec_comp_y, color=colormap(norm(colors)), angles='xy', scale_units='xy', scale=1) for i, phone in enumerate(phones): plt.annotate(phone, (vec_start_x[i] + 0.5 * vec_comp_x[i], vec_start_y[i] + 0.5 * vec_comp_y[i])) plt.show()
def auto_scale_cross_plot(self, event): norm = Normalize() for hl in self.h_cross_slice_plot.get_lines(): d = hl.get_ydata() norm.autoscale(d) hl.set_ydata(norm(d)) for vl in self.v_cross_slice_plot.get_lines(): d = vl.get_ydata() norm.autoscale(d) vl.set_ydata(norm(d)) self.v_cross_slice_plot.relim() self.h_cross_slice_plot.relim() self.v_cross_slice_plot.autoscale_view(True,True,True) self.h_cross_slice_plot.autoscale_view(True,True,True) self.cross_slice_canvas.draw()
def points(result, *, ax=None, scale_val=None, cmap=None, **kwargs): """ Plots the phase diagram as a collection of boxes, which are colored according to the estimate of the phase in a given box. Parameters ---------- result: Result Result of the :func:`.run` phase diagram calculation. ax: :py:mod:`matplotlib <matplotlib.pyplot>` ax Axes where the plot is drawn. add_cbar: bool Determines whether a colorbar is added to the figure. scale_val: list Values to which the colormap is scaled. By default, the colormap is scaled to the set of values which occur in the boxes. cmap: The colormap which is used to plot the phases. The colormap should take values normalized to [0, 1] and return a 4-tuple specifying the RGBA value (again normalized to [0, 1]. kwargs: Keyword arguments passed to :py:meth:`scatter <matplotlib.axes.Axes.scatter>`. """ if cmap is None: # don't do this in the signature, otherwise it gets set at import time cmap = plt.get_cmap() pts = result.points all_vals = sorted(set(pts.values())) or [0] norm = Normalize() if scale_val is None: norm.autoscale(all_vals) else: norm.autoscale(scale_val) point_colors = defaultdict(list) for coord, phase in pts.items(): point_colors[cmap(norm(phase))].append(coord) for color, coordinates in point_colors.items(): ax.scatter(*np.array(coordinates).T, color=color, **kwargs) return ax, cmap, norm, all_vals
def vectors(vectors): print(vectors) soa = np.array(vectors) #https://stackoverflow.com/questions/40026718/different-colours-for-arrows-in-quiver-plot ph = np.linspace(0, 2 * np.pi, 13) x = np.cos(ph) y = np.sin(ph) u = np.cos(ph) v = np.sin(ph) colors = np.arctan2(u, v) norm = Normalize() norm.autoscale(colors) colormap = cm.inferno # xyz: pt1, uvw: pt2 # coordinates are behaving strange when plotted, so reverse Z and X, and W and U, even though we'll input vectors in the form # xyz and uvw X, Y, Z, U, V, W = zip(*soa) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.quiver(X, Y, Z, U, V, W, arrow_length_ratio=0.0000001, color=colormap(norm(colors))) #headwidth=1) # ax.set_xlim([-5, max([i[5] for i in vectors]) + 1]) # this logic needs to be changed # ax.set_ylim([-5, max([i[4] for i in vectors]) + 1]) # ax.set_zlim([-5, max([i[3] for i in vectors]) + 1]) ax.set_xlim([-5, 20]) # this logic needs to be changed ax.set_ylim([-5, 20]) ax.set_zlim([-5, 20]) plt.show() # if __name__ == "__main__": # main()
def init(): fig, (ax, cbar_ax) = plt.subplots(ncols=2, gridspec_kw=dict(width_ratios=(0.95, 0.05))) ax.set_aspect(1.) fig.subplots_adjust(right=0.9) norm = Normalize() norm.autoscale(VALS) color_vals = [norm(c) for c in VALS] c_bar = ColorbarBase( cbar_ax, values=VALS, cmap=plt.get_cmap(), norm=norm, boundaries=range(5), ticklocation='right', ticks=[x + 0.5 for x in range(4)], ) c_bar.solids.set_edgecolor("k") c_bar.set_ticklabels(VALS) return fig, ax
def opyfPointCloudColoredScatter(X, V, fig=None, ax=None, cmapCS=mpl.cm.coolwarm, **args): from matplotlib.colors import Normalize fig, ax = getax(fig=fig, ax=ax) if 'cmap' in args: del args['cmap'] norme = (V[:, 0]**2+V[:, 1]**2)**0.5 norm = Normalize() norm.autoscale(norme) vlim = args.get('vlim', [np.min(norme), np.max(norme)]) if vlim is None: vlim = [np.min(norme), np.max(norme)] args['vmin'] = vlim[0] args['vmax'] = vlim[1] if 'vlim' in args: del args['vlim'] if 'markersize' in args: del args['markersize'] # sc=ax.scatter(X[:,0], X[:,1],c=norme,color=cmapCS(norm(norme)),**args) sc = ax.scatter(X[:, 0], X[:, 1], c=norme, cmap=cmapCS, **args) fig.show() return fig, ax, sc
def plot2D(X, filename=None, last_column_color=False): x1 = X[:, 0] x2 = X[:, 1] m = X.shape[0] if last_column_color: c = X[:, -1] c_map = get_cmap('jet') c_norm = Normalize() c_norm.autoscale(c) scalar_map = ScalarMappable(norm=c_norm, cmap=c_map) color_val = scalar_map.to_rgba(c) else: color_val = 'b' * m fig = figure() ax = fig.add_subplot(111) for i in range(m): ax.plot(x1[i], x2[i], 'o', color=color_val[i]) if filename is None: fig.show() else: fig.savefig(filename + ".png") fig.clf() close()
def plot(self,dano_summation): from matplotlib import pyplot as plt if self.params.use_weights: wt = 1./(self.diffs.sigmas()*self.diffs.sigmas()) order = flex.sort_permutation(wt) wt = wt.select(order) df = self.diffs.data().select(order) dano = dano_summation.select(self.sel0).select(order) from matplotlib.colors import Normalize dnorm = Normalize() dnorm.autoscale(wt.as_numpy_array()) CMAP = plt.get_cmap("rainbow") for ij in xrange(len(self.diffs.data())): #blue represents zero weight: red, large weight plt.plot([df[ij]],[dano[ij]],color=CMAP(dnorm(wt[ij])),marker=".", markersize=4) else: plt.plot(self.diffs.data(),dano_summation.select(self.sel0),"r,") plt.axes().set_aspect("equal") plt.axes().set_xlabel("Observed Dano") plt.axes().set_ylabel("Model Dano") plt.show()
def residual_map_special_deltapsi_add_on(reflections, experiments, matches, hkllist, predicted, plot, eta_deg, deff): detector = experiments[0].detector crystal = experiments[0].crystal unit_cell = crystal.get_unit_cell() pxlsz = detector[0].get_pixel_size() model_millers = reflections["miller_index"] dpsi = flex.double() for match in matches: obs_miller = hkllist[match["pred"]] model_index = model_millers.first_index(obs_miller) raw_delta_psi = reflections["delpsical.rad"][model_index] deltapsi_envelope = (unit_cell.d(obs_miller) / deff) + math.pi * eta_deg / 180. normalized_delta_psi = raw_delta_psi / deltapsi_envelope dpsi.append(normalized_delta_psi) from matplotlib.colors import Normalize dnorm = Normalize() dnorm.autoscale(dpsi.as_numpy_array()) CMAP = plot.get_cmap("bwr") for match, dcolor in zip(matches, dpsi): #print dcolor, dnorm(dcolor), CMAP(dnorm(dcolor)) #blue represents negative delta psi: outside Ewald sphere; red, positive, inside Ewald sphere plot.plot([predicted[match["pred"]][1] / pxlsz[1]], [-predicted[match["pred"]][0] / pxlsz[0]], color=CMAP(dnorm(dcolor)), marker=".", markersize=5)
def ImagePlot(image): if str(image.colorscale)=='n': remap = Normalize() remap.autoscale(image.data) ax.imshow(image.data, cmap='gray', norm=remap, origin='lower') elif str(image.colorscale) == 'yg': remap = LogNorm() remap.autoscale(image.data) ax.imshow(image.data, cmap='gray', norm=remap, origin='lower') elif str(image.colorscale) == 'ys': remap = LogNorm() remap.autoscale(image.data) ax.imshow(image.data, cmap='seismic', norm=remap, origin='lower')
def ImagePlot(image): if str(image.colorscale) == 'n': remap = Normalize() remap.autoscale(image.data) ax.imshow(image.data, cmap='gray', norm=remap, origin='lower') elif str(image.colorscale) == 'yg': remap = LogNorm() remap.autoscale(image.data) ax.imshow(image.data, cmap='gray', norm=remap, origin='lower') elif str(image.colorscale) == 'ys': remap = LogNorm() remap.autoscale(image.data) ax.imshow(image.data, cmap='seismic', norm=remap, origin='lower')
def flow( slices_in, # the 2D slices titles=None, # list of titles cmaps=None, # list of colormaps width=15, # width in in img_indexing=True, # whether to match the image view, i.e. flip y axis grid=False, # option to plot the images in a grid or a single row show=True, # option to actually show the plot (plt.show()) quiver_width=None, scale=1): # note quiver essentially draws quiver length = 1/scale ''' plot a grid of flows (2d+2 images) ''' # input processing nb_plots = len(slices_in) for slice_in in slices_in: assert len( slice_in.shape) == 3, 'each slice has to be 3d: 2d+2 channels' assert slice_in.shape[ -1] == 2, 'each slice has to be 3d: 2d+2 channels' def input_check(inputs, nb_plots, name): ''' change input from None/single-link ''' if not isinstance(inputs, (list, tuple)): inputs = [inputs] assert (inputs is None) or (len(inputs) == nb_plots) or (len(inputs) == 1), \ 'number of %s is incorrect' % name if inputs is None: inputs = [None] if len(inputs) == 1: inputs = [inputs[0] for i in range(nb_plots)] return inputs if img_indexing: for si, slc in enumerate(slices_in): slices_in[si] = np.flipud(slc) titles = input_check(titles, nb_plots, 'titles') cmaps = input_check(cmaps, nb_plots, 'cmaps') scale = input_check(scale, nb_plots, 'scale') # figure out the number of rows and columns if grid: if isinstance(grid, bool): rows = np.floor(np.sqrt(nb_plots)).astype(int) cols = np.ceil(nb_plots / rows).astype(int) else: assert isinstance(grid, (list, tuple)), \ "grid should either be bool or [rows,cols]" rows, cols = grid else: rows = 1 cols = nb_plots # prepare the subplot fig, axs = plt.subplots(rows, cols) if rows == 1 and cols == 1: axs = [axs] for i in range(nb_plots): col = np.remainder(i, cols) row = np.floor(i / cols).astype(int) # get row and column axes row_axs = axs if rows == 1 else axs[row] ax = row_axs[col] # turn off axis ax.axis('off') # add titles if titles is not None and titles[i] is not None: ax.title.set_text(titles[i]) u, v = slices_in[i][..., 0], slices_in[i][..., 1] colors = np.arctan2(u, v) colors[np.isnan(colors)] = 0 norm = Normalize() norm.autoscale(colors) if cmaps[i] is None: colormap = cm.winter else: raise Exception( "custom cmaps not currently implemented for plt.flow()") # show figure ax.quiver(u, v, color=colormap(norm(colors).flatten()), angles='xy', units='xy', width=quiver_width, scale=scale[i]) ax.axis('equal') # clear axes that are unnecessary for i in range(nb_plots, col * row): col = np.remainder(i, cols) row = np.floor(i / cols).astype(int) # get row and column axes row_axs = axs if rows == 1 else axs[row] ax = row_axs[col] ax.axis('off') # show the plots fig.set_size_inches(width, rows / cols * width) plt.tight_layout() if show: plt.show() return (fig, axs)
def plot_one_model(self,nrow,out): fig = plt.subplot(self.gs[nrow*self.ncols]) two_thetas = self.reduction.get_two_theta_deg() degrees = self.reduction.get_delta_psi_deg() if self.color_encoding=="conventional": positive = (self.reduction.i_sigi>=0.) fig.plot(two_thetas.select(positive), degrees.select(positive), "bo") fig.plot(two_thetas.select(~positive), degrees.select(~positive), "r+") elif self.color_encoding=="I/sigma": positive = (self.reduction.i_sigi>=0.) tt_selected = two_thetas.select(positive) dp_selected = degrees.select(positive) i_sigi_select = self.reduction.i_sigi.select(positive) order = flex.sort_permutation(i_sigi_select) tt_selected = tt_selected.select(order) dp_selected = dp_selected.select(order) i_sigi_selected = i_sigi_select.select(order) from matplotlib.colors import Normalize dnorm = Normalize() dcolors = i_sigi_selected.as_numpy_array() dnorm.autoscale(dcolors) N = len(dcolors) CMAP = plt.get_cmap("rainbow") if self.refined.get("partiality_array",None) is None: for n in xrange(N): fig.plot([tt_selected[n]],[dp_selected[n]], color=CMAP(dnorm(dcolors[n])),marker=".", markersize=10) else: partials = self.refined.get("partiality_array") partials_select = partials.select(positive) partials_selected = partials_select.select(order) assert len(partials)==len(positive) for n in xrange(N): fig.plot([tt_selected[n]],[dp_selected[n]], color=CMAP(dnorm(dcolors[n])),marker=".", markersize=20*partials_selected[n]) # change the markersize to indicate partiality. negative = (self.reduction.i_sigi<0.) fig.plot(two_thetas.select(negative), degrees.select(negative), "r+", linewidth=1) else: strong = (self.reduction.i_sigi>=10.) positive = ((~strong) & (self.reduction.i_sigi>=0.)) negative = (self.reduction.i_sigi<0.) assert (strong.count(True)+positive.count(True)+negative.count(True) == len(self.reduction.i_sigi)) fig.plot(two_thetas.select(positive), degrees.select(positive), "bo") fig.plot(two_thetas.select(strong), degrees.select(strong), marker='.',linestyle='None', markerfacecolor='#00ee00', markersize=10) fig.plot(two_thetas.select(negative), degrees.select(negative), "r+") # indicate the imposed resolution filter wavelength = self.reduction.experiment.beam.get_wavelength() imposed_res_filter = self.reduction.get_imposed_res_filter(out) resolution_markers = [ a for a in [imposed_res_filter,self.reduction.measurements.d_min()] if a is not None] for RM in resolution_markers: two_th = (180./math.pi)*2.*math.asin(wavelength/(2.*RM)) plt.plot([two_th, two_th],[self.AD1TF7B_MAXDP*-0.8,self.AD1TF7B_MAXDP*0.8],'k-') plt.text(two_th,self.AD1TF7B_MAXDP*-0.9,"%4.2f"%RM) #indicate the linefit mean = flex.mean(degrees) minplot = flex.min(two_thetas) plt.plot([0,minplot],[mean,mean],"k-") LR = flex.linear_regression(two_thetas, degrees) model_y = LR.slope()*two_thetas + LR.y_intercept() plt.plot(two_thetas, model_y, "k-") #Now let's take care of the red and green lines. half_mosaic_rotation_deg = self.refined["half_mosaic_rotation_deg"] mosaic_domain_size_ang = self.refined["mosaic_domain_size_ang"] red_curve_domain_size_ang = self.refined.get("red_curve_domain_size_ang",mosaic_domain_size_ang) a_step = self.AD1TF7B_MAX2T / 50. a_range = flex.double([a_step*x for x in xrange(1,50)]) # domain two-theta array #Bragg law [d=L/2sinTH] d_spacing = (wavelength/(2.*flex.sin(math.pi*a_range/360.))) # convert two_theta to a delta-psi. Formula for Deffective [Dpsi=d/2Deff] inner_phi_deg = flex.asin((d_spacing / (2.*red_curve_domain_size_ang)) )*(180./math.pi) outer_phi_deg = flex.asin((d_spacing / (2.*mosaic_domain_size_ang)) + \ half_mosaic_rotation_deg*math.pi/180. )*(180./math.pi) plt.title("ML: mosaicity FW=%4.2f deg, Dsize=%5.0fA on %d spots\n%s"%( 2.*half_mosaic_rotation_deg, mosaic_domain_size_ang, len(two_thetas), os.path.basename(self.reduction.filename))) plt.plot(a_range, inner_phi_deg, "r-") plt.plot(a_range,-inner_phi_deg, "r-") plt.plot(a_range, outer_phi_deg, "g-") plt.plot(a_range, -outer_phi_deg, "g-") plt.xlim([0,self.AD1TF7B_MAX2T]) plt.ylim([-self.AD1TF7B_MAXDP,self.AD1TF7B_MAXDP]) #second plot shows histogram fig = plt.subplot(self.gs[1+nrow*self.ncols]) plt.xlim([-self.AD1TF7B_MAXDP,self.AD1TF7B_MAXDP]) nbins = 50 n,bins,patches = plt.hist(dp_selected, nbins, range=(-self.AD1TF7B_MAXDP,self.AD1TF7B_MAXDP), weights=self.reduction.i_sigi.select(positive), normed=0, facecolor="orange", alpha=0.75) #ersatz determine the median i_sigi point: isi_positive = self.reduction.i_sigi.select(positive) isi_order = flex.sort_permutation(isi_positive) reordered = isi_positive.select(isi_order) isi_median = reordered[int(len(isi_positive)*0.9)] isi_top_half_selection = (isi_positive>isi_median) n,bins,patches = plt.hist(dp_selected.select(isi_top_half_selection), nbins, range=(-self.AD1TF7B_MAXDP,self.AD1TF7B_MAXDP), weights=isi_positive.select(isi_top_half_selection), normed=0, facecolor="#ff0000", alpha=0.75) plt.xlabel("(degrees)") plt.title("Weighted histogram of Delta-psi")
trainX = input_labels_np[0:30000] trainY = output_labels_np[0:30000] testX = input_labels_np[30000:] testY = output_labels_np[30000:] np.save('trainX.npy', trainX) np.save('trainY.npy', trainY) np.save('testX.npy', testX) np.save('testY.npy', testY) fig = plt.figure() ax = fig.gca(projection='3d') colormap = cm.inferno colors = output_labels_np norm = Normalize() norm.autoscale(colors) ax.quiver(input_labels_np[:, 0], input_labels_np[:, 1], input_labels_np[:, 2], input_labels_np[:, 3] - input_labels_np[:, 0], input_labels_np[:, 4] - input_labels_np[:, 1], input_labels_np[:, 5] - input_labels_np[:, 2], color=colormap(norm(output_labels_np)), linewidth=0.7, arrow_length_ratio=0) plt.show()
def main(): if len(sys.argv) < 3: sys.stderr.write( "USAGE: " + sys.argv[0] + " [path to road network GeoJSON file] [path to snapshot data]\n") sys.exit(1) # Set up figure and axes: fig = plt.figure() ax = fig.add_subplot(121, aspect="equal") # Load traces and count # of frames per link: with open(sys.argv[2], "r", encoding="utf-8") as f: snapshot = Snapshot.load(f, ordered=False) link_counts = Counter(frame.link for frame in snapshot.iter_time()) # print("most common links: ", link_counts.most_common(10)) with open(sys.argv[1], "r", encoding="utf-8") as f: network = RoadNetwork(f) counts = np.zeros(len(network.links)) for road in network.links: counts[road.id] = link_counts.get(road.id, 0) # Filter outliers in count data: q1 = np.percentile(counts, 25) q3 = np.percentile(counts, 75) iqr = q3 - q1 f1 = q1 - (1.5 * iqr) f2 = q3 + (1.5 * iqr) plotted = {} for road in network.links: v = counts[road.id] if v < f1 or v > f2: continue plotted[road.id] = v # Plot roads: cmap = plt.get_cmap("viridis") nm = Normalize() nm.autoscale([v for v in plotted.values()]) for road in network.links: if road.id in plotted: color = cmap(nm(plotted[road.id])) else: color = (0, 0, 0, 0) ax.add_line(plot_road(road, color)) ax.autoscale_view() ax.set_xlabel("Position (m)") ax.set_ylabel("Position (m)") ax.set_title("Link Density") print("nonzero links: ", np.count_nonzero(counts)) ax2 = fig.add_subplot(122) ax2.hist(counts, bins="auto") ax2.axvline(f1, linestyle='--', color='k') ax2.axvline(f2, linestyle='--', color='k') ax2.axvline(q1, linestyle='--', color='r') ax2.axvline(q3, linestyle='--', color='r') ax2.set_xlabel("Density") ax2.set_ylabel("Frequency") ax2.set_title("Densities") plt.show()
def quiver_draw(self, x, y, ws1, ws2, interval, quiver_width, quiver_scale, quiver_color, quiver_headwidth, alpha, quiverkey_opt, quiverkey_x, quiverkey_y, quiverkey_ws, quiverkey_text, quiverkey_size, color_quiver=0, color_maps=None, ws_map=None): x, y, ws1, ws2 = x[::interval, :: interval], y[::interval, :: interval], ws1[::interval, :: interval], ws2[:: interval, :: interval] if color_quiver == 0: quiver = self.axe.quiver(x, y, ws1, ws2, pivot='mid', width=quiver_width, scale=quiver_scale, color=quiver_color, headwidth=quiver_headwidth, alpha=alpha, transform=ccrs.PlateCarree()) if quiverkey_opt == 0: # 绘制矢量箭头的图例 self.axe.quiverkey(quiver, quiverkey_x, quiverkey_y, quiverkey_ws, Fontprocess.zhSimsun_enTNR(quiverkey_text), labelpos='E', coordinates='axes', fontproperties={ 'size': quiverkey_size, 'family': 'Times New Roman' }) if color_quiver == 1: color_map = np.zeros_like(ws1, dtype=float) windspeed = np.sqrt(ws1**2 + ws2**2) ws1 = ws1 / windspeed ws2 = ws2 / windspeed for i in range(len(ws_map)): color_map[np.where((windspeed > ws_map[i][0]) & (windspeed <= ws_map[i][1]))] = i norm = Normalize() norm.autoscale(color_map) self.quiver = self.axe.quiver(x, y, ws1, ws2, norm(color_map), cmap=color_maps, pivot='mid', width=quiver_width, scale=quiver_scale, headwidth=quiver_headwidth, alpha=alpha, transform=ccrs.PlateCarree())