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 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
def draw_intensity(cal: Task, cmap='inferno', norm=None, field_axis='x', vmin=0.98, vmax=1.02, ax=None, colorbar=True, cell_length=100, cell_diameter=60): if norm is None: norm = Normalize() if ax is None: f, ax = plt.subplots() else: f = ax.figure for source in cal.sources: draw_source(ax, source) if field_axis == 'x': field = cal.x_field elif field_axis == 'y': field = cal.y_field else: raise ValueError( "Intensity plot: only x or y accepted for field axis, got %s " % field_axis) norm.vmin = cal.center_field[0] * vmin norm.vmax = cal.center_field[0] * vmax color_plot = ax.pcolor(cal.x_mesh, cal.y_mesh, field, norm=norm, cmap=cmap) ax.axis('equal') draw_cell_boundary(ax, cell_length, cell_diameter) draw_mesh_boundary(cal.mesh, ax) if colorbar: color_bar = f.colorbar(color_plot, ax=ax) color_bar.ax.set_ylabel('%s field/ Tesla' % field_axis) # labels ax.set_xlabel('Position / mm, axial') ax.set_ylabel('Position / mm, radial') ax.autoscale() return color_plot, f, ax
def show_matrix( mat: np.ndarray, label: str, map: str = "clustermap", sort: bool = False, norm: Normalize = LogNorm(), cmap: str = "Greys", fig: Figure = None, ax: Axes = None, title: str = "matrix", **kwargs, ) -> Tuple[Union[Figure, ClusterGrid], Axes]: """ Plot matrix where x and y are the indices of the matrix and z (or c) is the value. :param mat: Matrix to plot. :param label: The data represented by the matrix. E.g. Number of interactions. :param map: How to plot the matrix. * 'clustermap' - `sns.clustermap` * 'heatmap' - `sns.heatmap` * 'mesh' - `matplotlib.pcolormesh` * callable - calls the function using the (potentially generated) ax, norm, and keywords. :param sort: Sort the matrix by most interactions. :param norm: The scale of the plot (normal, log, etc.). :param cmap: Colormap to use. :param ax: Axes to use for plot. Created if none passed. :param fig: Figure to use for colorbar. Created if none passed. :param title: Include title in the figure. :keyword cbar_ax: Axes to use for plotting the colorbar. :return: Tuple[Figure, Axes] used. """ if isinstance(mat, np.ndarray): N, M = mat.shape agent_mat = pd.DataFrame( mat, columns=pd.Index(np.arange(M), name="i"), index=pd.Index(np.arange(N), name="j"), ) elif isinstance(mat, pd.DataFrame): N, M = mat.shape agent_mat = mat else: raise ValueError( f"wrong type of matrix passed to `show_matrix`. Expected `np.ndarray` or `pd.DataFrame` but got {type(mat)}" ) if sort: if map == "mesh": logger.warning( "'mesh' loses agent index information when sorting adjacency matrix" ) agent_mat = agent_mat.sort_values(by=list(agent_mat.index), axis="index").sort_values( by=list(agent_mat.columns), axis="columns") show_matrix.sorted_mat = agent_mat # default label for colorbar cbar_kws = {"label": label, **kwargs.pop("cbar_kws", {})} if "vmin" in kwargs: norm.vmin = kwargs.pop("vmin") if "vmax" in kwargs: norm.vmax = kwargs.pop("vmax") if map == "clustermap": if fig: plt.close(fig) fig = sns.clustermap(agent_mat, norm=norm, cmap=cmap, cbar_kws=cbar_kws, **kwargs) ax = fig.ax_heatmap elif map == "heatmap": sns.heatmap( agent_mat, norm=norm, cmap=cmap, ax=ax, cbar_kws=cbar_kws, **kwargs, ) ax.invert_yaxis() elif map == "mesh": mesh = ax.pcolormesh(agent_mat, norm=norm, cmap=cmap, **kwargs) ax.set_xlim(0, N) ax.set_ylim(0, M) cax = cbar_kws.pop("cbar_ax", None) or cbar_kws.pop("cax", None) if cax is None: colorbar_inset( ScalarMappable(norm=norm, cmap=cmap), "outer right", size="5%", ax=ax, cmap=cmap, **cbar_kws, ) elif isinstance(cax, Axes): # using existing cax fig.colorbar( mesh, cax=cax, **cbar_kws, ) elif cax: # steal space from ax if cax is anything else (i.e. unless None, False, or an Axes) fig.colorbar(mesh, ax=ax, **cbar_kws) elif isinstance(map, Callable): map(agent_mat, ax=ax, norm=norm, **kwargs) else: raise NotImplementedError( f"Method {map} not implemented. Try one of 'clustermap' 'heatmap' 'mesh' or a " f"function.") ax.set_xlabel("Agent $i$") ax.set_ylabel("Agent $j$") if title: if map == "clustermap": fig.fig.suptitle(title) else: ax.set_title(title) # default to borders sns.despine(ax=ax, top=False, right=False, left=False, bottom=False) return fig, ax