我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用matplotlib.colors.Normalize()。
def plot(self, ax, color = 'rainbow', linewidth = 3) : "Simple display using a per-id color scheme." segs = self.segments() if color == 'rainbow' : # rainbow color scheme to see pointwise displacements ncycles = 5 cNorm = colors.Normalize(vmin=0, vmax=(len(segs)-1)/ncycles) scalarMap = cm.ScalarMappable(norm=cNorm, cmap=plt.get_cmap('hsv') ) seg_colors = [ scalarMap.to_rgba( i % ((len(segs)-1)/ncycles) ) for i in range(len(segs)) ] else : # uniform color seg_colors = [ color for i in range(len(segs)) ] line_segments = LineCollection(segs, linewidths=(linewidth,), colors=seg_colors, linestyle='solid') ax.add_collection(line_segments)
def plot_heatmap(ax, xpoints, ypoints, nbins, title=None, maxcount=None): ''' Plot a heatmap of the given data on on the given axes. ''' # imshow expects y,x for the image, but x,y for the extents, # so we have to manage that here... bins = np.concatenate( (np.arange(0,1.0,1.0/nbins), [1.0]) ) heatmap, yedges, xedges = np.histogram2d(ypoints, xpoints, bins=bins) extent = [xedges[0],xedges[-1], yedges[0], yedges[-1]] # make sure we always show the full extent of the tank and the full extent of the data, # whichever is wider. ax.set_xlim(min(0, xedges[0]), max(1, xedges[-1])) ax.set_ylim(min(0, yedges[0]), max(1, yedges[-1])) if title: ax.set_title(title) if maxcount is not None: norm = Normalize(0, maxcount) else: norm = None return ax.imshow(heatmap, extent=extent, cmap=plt.get_cmap('hot'), origin='lower', interpolation='nearest', norm=norm)
def colorify(data, vmin=None, vmax=None, cmap=plt.cm.Spectral): """ Associate a color map to a quantity vector """ try: from matplotlib.colors import Normalize except ImportError: # old mpl from matplotlib.colors import normalize as Normalize _vmin = vmin or min(data) _vmax = vmax or max(data) cNorm = Normalize(vmin=_vmin, vmax=_vmax) scalarMap = plt.cm.ScalarMappable(norm=cNorm, cmap=cmap) try: colors = scalarMap.to_rgba(data) except: colors = list(map(scalarMap.to_rgba, data)) return colors, scalarMap
def get_cmap(N, cmap): """Returns a function that maps each index in 0, 1, ... N-1 to a distinct RGB color. Parameters ---------- N : int cmap : colormap Returns ------- function """ color_norm = colors.Normalize(vmin=0, vmax=N-1) scalar_map = cmx.ScalarMappable(norm=color_norm, cmap=cmap) def map_index_to_rgb_color(index): return scalar_map.to_rgba(index)[:3] return map_index_to_rgb_color
def get_cmap(N): color_norm = colors.Normalize(vmin=0, vmax=N-1) scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv') def map_index_to_rgb_color(index): return scalar_map.to_rgba(index) return map_index_to_rgb_color
def view_raw_templates(file_name, n_temp=2, square=True): N_e, N_t, N_tm = templates.shape if not numpy.iterable(n_temp): if square: idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp**2] else: idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp] else: idx = n_temp import matplotlib.colors as colors my_cmap = pylab.get_cmap('winter') cNorm = colors.Normalize(vmin=0, vmax=N_e) scalarMap = pylab.cm.ScalarMappable(norm=cNorm, cmap=my_cmap) pylab.figure() for count, i in enumerate(idx): if square: pylab.subplot(n_temp, n_temp, count + 1) if (numpy.mod(count, n_temp) != 0): pylab.setp(pylab.gca(), yticks=[]) if (count < n_temp*(n_temp - 1)): pylab.setp(pylab.gca(), xticks=[]) else: pylab.subplot(len(idx), 1, count + 1) if count != (len(idx) - 1): pylab.setp(pylab.gca(), xticks=[]) for j in xrange(N_e): colorVal = scalarMap.to_rgba(j) pylab.plot(templates[j, :, i], color=colorVal) pylab.title('Template %d' %i) pylab.tight_layout() pylab.show()
def plotImage(self, I, ax=None, showIt=False, grid=False, clim=None): if self.dim == 3: raise Exception('Use plot slice?') import matplotlib.pyplot as plt import matplotlib from mpl_toolkits.mplot3d import Axes3D import matplotlib.colors as colors import matplotlib.cm as cmx if ax is None: ax = plt.subplot(111) jet = cm = plt.get_cmap('jet') cNorm = colors.Normalize( vmin=I.min() if clim is None else clim[0], vmax=I.max() if clim is None else clim[1]) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) ax.set_xlim((self.x0[0], self.h[0].sum())) ax.set_ylim((self.x0[1], self.h[1].sum())) for ii, node in enumerate(self._sortedCells): x0, sz = self._cellN(node), self._cellH(node) ax.add_patch(plt.Rectangle((x0[0], x0[1]), sz[0], sz[1], facecolor=scalarMap.to_rgba(I[ii]), edgecolor='k' if grid else 'none')) # if text: ax.text(self.center[0],self.center[1],self.num) scalarMap._A = [] # http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots ax.set_xlabel('x') ax.set_ylabel('y') if showIt: plt.show() return [scalarMap]
def plotImage( self, I, ax=None, showIt=False, grid=False, clim=None ): if self.dim == 3: raise NotImplementedError('This is not yet done!') import matplotlib.pyplot as plt import matplotlib from mpl_toolkits.mplot3d import Axes3D import matplotlib.colors as colors import matplotlib.cm as cmx if ax is None: ax = plt.subplot(111) jet = cm = plt.get_cmap('jet') cNorm = colors.Normalize( vmin=I.min() if clim is None else clim[0], vmax=I.max() if clim is None else clim[1]) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) # ax.set_xlim((self.x0[0], self.h[0].sum())) # ax.set_ylim((self.x0[1], self.h[1].sum())) Nx = self.r(self.gridN[:, 0], 'N', 'N', 'M') Ny = self.r(self.gridN[:, 1], 'N', 'N', 'M') cell = self.r(I, 'CC', 'CC', 'M') for ii in range(self.nCx): for jj in range(self.nCy): I = [ii, ii+1, ii+1, ii] J = [jj, jj, jj+1, jj+1] ax.add_patch(plt.Polygon(np.c_[Nx[I, J], Ny[I, J]], facecolor=scalarMap.to_rgba(cell[ii, jj]), edgecolor='k' if grid else 'none')) scalarMap._A = [] # http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots ax.set_xlabel('x') ax.set_ylabel('y') if showIt: plt.show() return [scalarMap]
def show_grid(grid, name, lam, norm=None, size=None): # Determine size of image. See above. size = grid.shape[0] uv_lower, uv_upper = coordinateBounds(size) uv_lower = (uv_lower-1./size/2)*lam uv_upper = (uv_upper+1./size/2)*lam extent = (uv_lower, uv_upper, uv_lower, uv_upper) # Determine normalisation for image. if norm is not None: norm = colors.Normalize(vmin=-norm, vmax=norm, clip=True) else: norm = None # Draw. for plot, comp, data in [(121, "Re", grid.real), (122, "Im", grid.imag)]: pl.subplot(plot) pl.imshow(data, extent=extent, norm=norm, interpolation='nearest', origin='lower') pl.title("$%s(%s(u,v,w))$" % (comp, name)) pl.xlabel(r"U [$\lambda$]") pl.ylabel(r"V [$\lambda$]") # Only show color bar if we don't use the standard normalisation. if norm is None: pl.colorbar(shrink=.4,pad=0.025) pl.show() # from http://stackoverflow.com/questions/22867620/putting-arrowheads-on-vectors-in-matplotlibs-3d-plot # by CT Zhu
def _get_cmap_data(data, kwargs): """Get normalized values to be used with a colormap. Parameters ---------- data : array_like cmap_min : Optional[float] or "min" By default 0. If "min", minimum value of the data. cmap_max : Optional[float] By default, maximum value of the data cmap_normalize : str or colors.Normalize Returns ------- normalizer : colors.Normalize normalized_data : array_like """ norm = kwargs.pop("cmap_normalize", None) if norm == "log": cmap_max = kwargs.pop("cmap_max", data.max()) cmap_min = kwargs.pop("cmap_min", data[data > 0].min()) norm = colors.LogNorm(cmap_min, cmap_max) elif not norm: cmap_max = kwargs.pop("cmap_max", data.max()) cmap_min = kwargs.pop("cmap_min", 0) if cmap_min == "min": cmap_min = data.min() norm = colors.Normalize(cmap_min, cmap_max, clip=True) return norm, norm(data)
def _add_colorbar(ax, cmap, cmap_data, norm): """Show a colorbar right of the plot. Parameters ---------- ax : plt.Axes cmap : colors.Colormap cmap_data : array_like norm : colors.Normalize """ fig = ax.get_figure() mappable = cm.ScalarMappable(cmap=cmap, norm=norm) mappable.set_array(cmap_data) # TODO: Or what??? fig.colorbar(mappable, ax=ax)
def explain_categorization(weights, text, colormap): """Generate decorated HTML by adding <span> tags with background color to keywords depending on word's weight. Parameters ---------- weights : dict[str, float] words as keys, weights (scores) as values text : str document's raw text colormap : matplotlib.colors.LinearSegmentedColormap color map used to decorate keywords with background color Returns ------- str HTML string representing document's text decorated with <span> tags """ try: from html import escape # python 3.x except ImportError: from cgi import escape # python 2.x from matplotlib.colors import Normalize text = escape(text) # in order to have a valid HTML output after adding <span> tags max_val = max(abs(min(weights.values())), abs(max(weights.values()))) norm = Normalize(vmin=-max_val, vmax=max_val) document_html_lines = list() for line in text.splitlines(): line_decorated = _replace_with_color_spans(line, weights, colormap, norm) document_html_lines.append(line_decorated) return "<br/>".join(document_html_lines), norm
def get_cmap(N): '''Returns a function that maps each index in 0, 1, ... N-1 to a distinct RGB color.''' color_norm = colors.Normalize(vmin=0, vmax=N-1) scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv') def map_index_to_rgb_color(index): return scalar_map.to_rgba(index) return map_index_to_rgb_color
def getNorm(self): mx = 10**self.scale if self.normScale == 'linear': mn = 0.0 norm = pltLinNorm(mn,mx) elif self.normScale == 'log': mn = 1e-10 norm = pltLogNorm(mn,mx) else: raise Exception('Invalid norm %s.' % norm) return norm
def set_norm(self, msg=(False,)): """ msg is tuple: (pause_redraw_image, ) """ if self._norm is None or self.clim != self._set_norm_old_clim: self._norm = Normalize(vmin=self.clim[0], vmax=self.clim[1]) self._set_norm_old_clim = self.clim self._need_to_recalc_normalization = True if self._scaling is None or self.scaling != self._set_norm_old_scaling: self._scaling = eval('astropy.visualization.' + self.scaling + 'Stretch()') self._set_norm_old_scaling = self.scaling self._need_to_recalc_normalization = True if not (msg[0] or self._pause_redraw_image): wx.CallAfter(pub.sendMessage, 'redraw-image', msg=False)
def cluster_scatter_plot(similarity_file): def get_cmap(N): '''Returns a function that maps each index in 0, 1, ... N-1 to a distinct RGB color.''' color_norm = colors.Normalize(vmin=0, vmax=N-1) scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv') def map_index_to_rgb_color(index): return scalar_map.to_rgba(index) return map_index_to_rgb_color with open(similarity_file, 'r', 'utf-8') as f: similarity_data = json.load(f) labels = [] point_colors = [] num_clusters = len(similarity_data['cluster2doc'].keys()) cmap = get_cmap(num_clusters) for model_name in similarity_data['model_names']: model_name = os.path.splitext(os.path.basename(model_name))[0] cluster_label = similarity_data['doc2cluster'][model_name] point_colors.append(cmap(cluster_label)) labels.append(re.compile(r"\s\([0-9]*\)-iter.*", re.IGNORECASE).split(model_name, 1)[0]) embeddings = SpectralEmbedding(affinity='precomputed').fit_transform(np.array(similarity_data['similarity_matrix'])) fig, ax = plt.subplots() x = embeddings[:, 0] y = embeddings[:, 1] annotes = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] * 10 N = 100 scatter = ax.scatter(x, y, c=point_colors[:],s=100*np.ones(shape=N)) tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels) mpld3.plugins.connect(fig, tooltip) mpld3.show() # plt.scatter(tsne_embeddings[20:40, 0], tsne_embeddings[20:40, 1], c='b') # for label, x, y in zip(labels, tsne_embeddings[:, 0], tsne_embeddings[:, 1]): # plt.annotate( # label, # xy = (x, y), # # textcoords = 'offset points', # bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5)) # plt.show()
def _proportional_y(self): ''' Return colorbar data coordinates for the boundaries of a proportional colorbar. ''' if isinstance(self.norm, colors.BoundaryNorm): y = (self._boundaries - self._boundaries[0]) y = y / (self._boundaries[-1] - self._boundaries[0]) else: y = self.norm(self._boundaries.copy()) if self.extend == 'min': # Exclude leftmost interval of y. clen = y[-1] - y[1] automin = (y[2] - y[1]) / clen automax = (y[-1] - y[-2]) / clen elif self.extend == 'max': # Exclude rightmost interval in y. clen = y[-2] - y[0] automin = (y[1] - y[0]) / clen automax = (y[-2] - y[-3]) / clen else: # Exclude leftmost and rightmost intervals in y. clen = y[-2] - y[1] automin = (y[2] - y[1]) / clen automax = (y[-2] - y[-3]) / clen extendlength = self._get_extension_lengths(self.extendfrac, automin, automax, default=0.05) if self.extend in ('both', 'min'): y[0] = 0. - extendlength[0] if self.extend in ('both', 'max'): y[-1] = 1. + extendlength[1] yi = y[self._inside] norm = colors.Normalize(yi[0], yi[-1]) y[self._inside] = norm(yi) return y
def plot_models_list(models_list,var_to_plot,return_axis=False): ''' plots 1d profiles for a list of velocity_model objects args: models_list: list of velocity_model objects var_to_plot: 'vp', 'vs', or 'rho' ''' from matplotlib.colors import Normalize plt.style.use('mystyle') fig,ax = plt.subplots() cmap = plt.get_cmap('hot') vals = np.linspace(0,1,len(models_list)*1.5) norm = Normalize() colors = cmap(norm(vals)) i = 0 if var_to_plot == 'vp': for m in models_list: ax.plot(m.vp1d,m.rad_km[::-1],label='{:4.0f} {}'.format(m.pot_T,'K'),color=colors[i]) i += 1 elif var_to_plot == 'vs': for m in models_list: ax.plot(m.vs1d,m.rad_km[::-1],label='{:4.0f} {}'.format(m.pot_T,'K'),color=colors[i]) i += 1 elif var_to_plot == 'rho': for m in models_list: ax.plot(m.rho1d,m.rad_km[::-1],label='{:4.0f} {}'.format(m.pot_T,'K'),color=colors[i]) i += 1 ax.set_ylabel('radius (km)') ax.set_xlabel('velocity (km/s)') ax.legend(loc='lower left') ax.grid() if return_axis == False: plt.show() else: return ax
def _background_gradient(s, cmap='PuBu', low=0, high=0): """Color background in a range according to the data.""" with _mpl(Styler.background_gradient) as (plt, colors): rng = s.max() - s.min() # extend lower / upper bounds, compresses color range norm = colors.Normalize(s.min() - (rng * low), s.max() + (rng * high)) # matplotlib modifies inplace? # https://github.com/matplotlib/matplotlib/issues/5427 normed = norm(s.values) c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)] return ['background-color: %s' % color for color in c]
def check_reg(fixed_img, moved_img, scale=15, norm=True, sigma=0.8, **kwargs): dim = list(moved_img.shape) resol = list(moved_img.header['pixdim'][1:4]) # Convert 4D image to 3D or raise error data = convert_to_3d(moved_img) # Check normalization if norm: data = apply_p2_98(data) # Set slice axis for mosaic grid slice_axis, cmap = check_sliceaxis_cmap(data, kwargs) cmap = 'YlOrRd' # Set grid shape data, slice_grid, size = set_mosaic_fig(data, dim, resol, slice_axis, scale) fig, axes = BrainPlot.mosaic(fixed_img, scale=scale, norm=norm, cmap='bone', **kwargs) # Applying inversion invert = check_invert(kwargs) data = apply_invert(data, *invert) # Plot image for i in range(slice_grid[1] * slice_grid[2]): ax = axes.flat[i] edge = data[:, :, i] edge = feature.canny(edge, sigma=sigma) # edge detection for second image # edge = ndimage.gaussian_filter(edge, 3) mask = np.ones(edge.shape) sx = ndimage.sobel(edge, axis=0, mode='constant') sy = ndimage.sobel(edge, axis=1, mode='constant') sob = np.hypot(sx, sy) mask[sob == False] = np.nan m_norm = colors.Normalize(vmin=0, vmax=1.5) if i < slice_grid[0] and False in np.isnan(mask.flatten()): ax.imshow(mask.T, origin='lower', interpolation='nearest', cmap=cmap, norm=m_norm, alpha=0.8) else: ax.imshow(np.zeros((dim[0], dim[1])).T, origin='lower', interpolation='nearest', cmap='bone') ax.set_axis_off() fig.set_facecolor('black') if notebook_env: display(fig) return fig, axes
def chloropleth(self, query, color = "Blues"): """shows a chloropleth map of crimes Args: query: name of sql """ self.load() data = pd.read_sql_query(con=self.con, sql=query) points = self.gen_points(data, self.data_map) self.data_map['count'] = self.data_map['poly'].map(lambda x: len(list(filter(prep(x).contains, points)))) self.data_map['density_m'] = self.data_map['count'] / self.data_map['area_m'] self.data_map['density_km'] = self.data_map['count'] / self.data_map['area_km'] self.data_map.replace(to_replace={'density_m': {0: np.nan}, 'density_km': {0: np.nan}}, inplace=True) breaks = nb( self.data_map[self.data_map['density_km'].notnull()].density_km.values, initial=300, k=5) jb = pd.DataFrame({'jenks_bins': breaks.yb}, index=self.data_map[self.data_map['density_km'].notnull()].index) self.data_map = self.data_map.join(jb) self.data_map.jenks_bins.fillna(-1, inplace=True) jenks_labels = ["<= %0.1f/km$^2$(%s communities)" % (b, c) for b, c in zip( breaks.bins, breaks.counts)] jenks_labels.insert(0, 'None (%s communities)' % len(self.data_map[self.data_map['density_km'].isnull()])) cmap = plt.get_cmap(color) self.data_map['patches'] = self.data_map['poly'].map(lambda x: PolygonPatch(x, ec='#555555', lw=.2, alpha=1., zorder=4)) pc = PatchCollection(self.data_map['patches'], match_original=True) norm = Normalize() pc.set_facecolor(cmap(norm(self.data_map['jenks_bins'].values))) self.ax.add_collection(pc) cb = self.gen_colorbar(colors=len(jenks_labels), color_map=cmap, shrink=0.5, labels=jenks_labels) cb.ax.tick_params(labelsize=6) plt.tight_layout() plt.show()
def create_ColorMap( N, maptype='jet' ): ccmap = plt.get_cmap( maptype ) cNorm = colors.Normalize(vmin=0, vmax=(N-1)) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=ccmap) plotColors = np.zeros( (N,4) ) for k in range( N ): plotColors[k,:] = scalarMap.to_rgba( k ) return plotColors
def set_cmap_synthetic(self, cmap): self._cmap = pylab.get_cmap(cmap) self._cNorm = colors.Normalize(vmin=0, vmax=self.nb_cells) self._scalarMap_synthetic = pylab.cm.ScalarMappable(norm=self._cNorm, cmap=self._cmap)
def set_cmap_circus(self, cmap): self._cmap = pylab.get_cmap(cmap) self._cNorm = colors.Normalize(vmin=0, vmax=self.nb_templates) self._scalarMap_circus = pylab.cm.ScalarMappable(norm=self._cNorm, cmap=self._cmap)
def norm_rgb_color(color): """Normalize color Parameters ---------- color : tuple of int/float Returns ------- tuple of float normalized rgb """ normed_color = (color[0]/255., color[1]/255., color[2]/255.) return normed_color
def build_map_nmf(df_map, m, coords, info, title, CrimePatterns): # plt.clf() fig = plt.figure() ax = fig.add_subplot(111, axisbg='w', frame_on=True) # draw wards with grey outlines norm = Normalize() for i in xrange(5): color = colormaps[i] cmap = plt.get_cmap(color) pc = PatchCollection(df_map[df_map['class'] == i+1]['patches'], match_original=True, alpha=0.8) pc.set_facecolor(cmap(norm(df_map.loc[(df_map['class'] == i+1), i].values))) ax.add_collection(pc) pc = PatchCollection(df_map[df_map['class'] == 0]['patches'], match_original=True, alpha=0.2) pc.set_facecolor('grey') ax.add_collection(pc) x, y = m(coords[0] + 0.02, coords[1] + 1.0) details = plt.annotate(info, xy=(x, y), size=24, color='#555555') # Draw a map scale m.drawmapscale( coords[0] + 0.2, coords[1] + 0.95, coords[0], coords[1], 20., fontsize=8, barstyle='fancy', labelstyle='simple', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', units='mi', zorder=5) legend_patches = [] for i in range(6): legend_patches.append(mpatches.Patch(color=colors[i], label=CrimePatterns[i])) plt.legend(handles=legend_patches, loc='lower right') x1, y1 = m(coords[0] + 0.05, 33.62) colorinfo = 'Color represent each cluster of community;\nBrightness represent the severities of crime in each community' plt.annotate(colorinfo, xy=(x1, y1), size=16, color='#555555') plt.tight_layout() fig.set_size_inches(12, 13) plt.savefig(title, dpi=300, alpha=True)
def plot_graph(self, am, position=None, cls=None, fig_name='graph.png'): with warnings.catch_warnings(): warnings.filterwarnings("ignore") g = nx.from_numpy_matrix(am) if position is None: position=nx.drawing.circular_layout(g) fig = plt.figure() if cls is None: cls='r' else: # Make a user-defined colormap. cm1 = mcol.LinearSegmentedColormap.from_list("MyCmapName", ["r", "b"]) # Make a normalizer that will map the time values from # [start_time,end_time+1] -> [0,1]. cnorm = mcol.Normalize(vmin=0, vmax=1) # Turn these into an object that can be used to map time values to colors and # can be passed to plt.colorbar(). cpick = cm.ScalarMappable(norm=cnorm, cmap=cm1) cpick.set_array([]) cls = cpick.to_rgba(cls) plt.colorbar(cpick, ax=fig.add_subplot(111)) nx.draw(g, pos=position, node_color=cls, ax=fig.add_subplot(111)) fig.savefig(os.path.join(self.plotdir, fig_name))
def get_cmap(N): '''Returns a function that maps each index in 0, 1, ... N-1 to a distinct RGB color.''' color_norm = colors.Normalize(vmin=0, vmax=N) scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv') def map_index_to_rgb_color(index): return scalar_map.to_rgba(index) return map_index_to_rgb_color
def _plot_zcontinuous(self): if self.parts is None: parts = [np.ones_like(self.xdata, dtype=bool)] else: parts = self.parts good = np.sum(parts, axis=0, dtype=bool) good *= np.isfinite(self.xdata) good *= np.isfinite(self.ydata) good *= np.isfinite(self.zdata) # TODO: Sem essa linha, onde não houver perfil z será plotado de ?preto? zticks = self.zlocator(np.min(self.zdata[good]), np.max(self.zdata[good])) self.zlim = [zticks[0], zticks[-1]] self.zticks = zticks[1:-1] norm = Normalize(*self.zlim) for part in parts: x = self.xdata[part*good] y = self.ydata[part*good] c = self.zdata[part*good] collection = self.crossplot_ax.scatter(x, y, c=c, cmap=self.cmap, norm=norm, zorder=-len(x), **self.collectionproperties) self.collections.append(collection) xticks = self.xlocator(np.min(self.xdata[good]), np.max(self.xdata[good])) self.set_xlim([xticks[0], xticks[-1]]) yticks = self.ylocator(np.min(self.ydata[good]), np.max(self.ydata[good])) self.set_ylim([yticks[0], yticks[-1]]) self.colorbar = ColorbarBase(self.colorbar_ax, cmap=self.cmap, norm=norm, ticks=self.zticks) #self.colorbar_ax.yaxis.set_major_formatter(NullFormatter())
def _plot_zcontinuous(self): if self.parts is None: parts = [np.ones_like(self.xdata, dtype=bool)] else: parts = self.parts good = np.sum(parts, axis=0, dtype=bool) good *= np.isfinite(self.xdata) good *= np.isfinite(self.ydata) if self.zdata is not None: good *= np.isfinite(self.zdata) # TODO: Sem essa linha, onde não houver perfil z será plotado de ?preto? zticks = self.zlocator(np.min(self.zdata[good]), np.max(self.zdata[good])) self.zlim = [zticks[0], zticks[-1]] self.zticks = zticks[1:-1] norm = Normalize(*self.zlim) # for part in parts: x = self.xdata[part*good] y = self.ydata[part*good] c = self.zdata[part*good] collection = self.crossplot_ax.scatter(x, y, c=c, cmap=self.cmap, norm=norm, zorder=-len(x), **self.collectionproperties ) self.collections.append(collection) # xticks = self.xlocator(np.min(self.xdata[good]), np.max(self.xdata[good])) self.set_xlim([xticks[0], xticks[-1]]) yticks = self.ylocator(np.min(self.ydata[good]), np.max(self.ydata[good])) self.set_ylim([yticks[0], yticks[-1]]) self.colorbar = ColorbarBase(self.colorbar_ax, cmap=self.cmap, norm=norm, ticks=self.zticks ) #self.colorbar_ax.yaxis.set_major_formatter(NullFormatter())
def _save_2d_error_plot(self, detector, xlist, ylist, elist, x_axis_label, y_axis_label, z_axis_label): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib import colors # configure logscale on X and Y axis (both for positive and negative numbers) fig, ax = plt.subplots(1, 1) if PlotAxis.x in self.axis_with_logscale: plt.xscale('symlog') if PlotAxis.y in self.axis_with_logscale: plt.yscale('symlog') if PlotAxis.z in self.axis_with_logscale: norm = colors.LogNorm(vmin=elist[elist > 0].min(), vmax=elist.max()) else: norm = colors.Normalize(vmin=elist.min(), vmax=elist.max()) plt.xlabel(x_axis_label) plt.ylabel(y_axis_label) mesh = plt.pcolormesh(xlist, ylist, elist.clip(0.0), cmap=self.colormap, norm=norm) cbar = fig.colorbar(mesh) cbar.set_label(label=z_axis_label, rotation=270, verticalalignment='bottom') base_name, _ = os.path.splitext(self.plot_filename) plt.savefig(base_name + "_error.png") plt.close()
def map(dataframe, title = "Map", colorbarName = None): fig, ax = plt.subplots(figsize=(80,40)) m = Basemap(resolution='l', # c, l, i, h, f or None projection='robin', lon_0=0) m.drawmapboundary(fill_color='#46bcec') m.fillcontinents(color='#f2f2f2',lake_color='#46bcec') # m.drawcoastlines() plt.title(title, fontsize=50, y=1.08) m.readshapefile('visualization/World/World', 'world',drawbounds=False) df_plot = pd.DataFrame({ 'shapes': [Polygon(np.array(shape), True) for shape in m.world], 'country': [country['ISO3'] for country in m.world_info] }) df_plot = df_plot.merge(dataframe, on='country', how='left') df_plot = df_plot.dropna() cmap = plt.get_cmap('RdYlGn') pc = PatchCollection(df_plot.shapes, zorder=2) norm = Normalize() pc.set_facecolor(cmap(norm(df_plot['value'].values))) ax.add_collection(pc) mapper = matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap) mapper.set_array(df_plot['value']) cbar = plt.colorbar(mapper, shrink=0.7, label = colorbarName) fig = plt.gcf() fig.savefig("Map.jpg") plt.show()
def map_metadata_coordinates(output_dir: str, alpha_diversity: pd.Series, metadata: qiime2.Metadata, category: str=None, latitude: str='Latitude', longitude: str='Longitude', image: str='StamenTerrain', color_palette: str='rainbow', discrete: bool=False): # Load metadata, attempt to convert to numeric metadata = _metadata_to_df(metadata) alpha_diversity = alpha_diversity.convert_objects(convert_numeric=True) # set up basemap ax, cmap = plot_basemap( metadata[latitude], metadata[longitude], image, color_palette) # determine whether to color by metadata or alpha_diversity if category in metadata: pass elif alpha_diversity is not None: category = alpha_diversity.name metadata = metadata.merge( pd.DataFrame(alpha_diversity), left_index=True, right_index=True) else: raise ValueError(( 'Must define metadata category or alpha diversity artifact to ' 'use for sample coloring. "category" is not found in "metadata". ' 'Please check your inputs and supply a valid "category" or alpha ' 'diversity artifact to use for coloring.')) # plot coordinates on map. If category is numeric, color points by category if np.issubdtype(metadata[category].dtype, np.number) and not discrete: metadata[category] = metadata[category].astype(float) print(metadata[category]) plt.scatter(metadata[longitude], metadata[latitude], c=list(metadata[category]), transform=ccrs.Geodetic(), cmap=cmap) # set up a colorbar normalize = mcolors.Normalize( vmin=metadata[category].min(), vmax=metadata[category].max()) scalarmappaple = cm.ScalarMappable(norm=normalize, cmap=cmap) scalarmappaple.set_array(metadata[category]) plt.colorbar(scalarmappaple).set_label(category) # if category is not numeric, color discretely else: groups = metadata[category].unique() colors = cmap(np.linspace(0, 1, len(groups))) for group, c in zip(groups, colors): # Note that this assumes this will always be metadata; alpha # diversity values should always be numeric. subset = metadata[metadata[category] == group] plt.plot(subset[longitude], subset[latitude], 'o', color=c, transform=ccrs.Geodetic()) ax.legend(groups, bbox_to_anchor=(1.05, 1)) save_map(ax, output_dir) mapviz(output_dir)
def clicks_heatmap_first_occ(): print 'loading' db = MySQLDatabase(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME) db_worker_view = db.get_work_view() coords = db_worker_view.retrieve_all_links_coords_clicks_first_occ() print 'coord loaded' links = {} x = [] y = [] values = [] for link in coords.values(): x_normed = float(link['x'])/float(1920) y_normed = float(link['y'])/float(link['page_length']) if x_normed <=1.0 and y_normed <=1.0: x.append(x_normed) y.append(y_normed) values.append(float(link['counts'])) heatmap, xedges, yedges = np.histogram2d(x, y, bins=100, weights=values) extent = [xedges[0], xedges[-1], yedges[-1], yedges[0] ] fig_size = (2.4, 2) plt.clf() plt.figure(figsize=fig_size) plt.grid(True) plt.imshow(heatmap , extent=extent, origin='upper', norm=LogNorm(), cmap=plt.get_cmap('jet')) plt.colorbar() #plt.title("Clicks Heatmap Log Normalized") plt.show() plt.savefig('output/clicks_heatmap_lognormed_self_loop_first_occ.pdf') plt.clf() plt.figure(figsize=fig_size) plt.grid(True) plt.imshow(heatmap , extent=extent, origin='upper', norm=Normalize(), cmap=plt.get_cmap('jet')) plt.colorbar() #plt.title("Clicks Heatmap Normalized") plt.show() plt.savefig('output/clicks_heatmap_normed_self_loop_first_occ.pdf') print "done"
def clicks_heatmap_total(): print 'loading' db = MySQLDatabase(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME) db_worker_view = db.get_work_view() coords = db_worker_view.retrieve_all_links_coords_clicks() print 'coord loaded' links = {} x = [] y = [] values = [] for coord in coords: x_normed = float(coord['x'])/float(1920) y_normed = float(coord['y'])/float(coord['page_length']) if x_normed <=1.0 and y_normed <=1.0: x.append(x_normed) y.append(y_normed) values.append(float(coord['counts'])) heatmap, xedges, yedges = np.histogram2d(x, y, bins=100, weights=values) extent = [xedges[0], xedges[-1], yedges[-1], yedges[0] ] fig_size = (2.4, 2) plt.clf() plt.figure(figsize=fig_size) plt.grid(True) plt.imshow(heatmap , extent=extent, origin='upper', norm=LogNorm(), cmap=plt.get_cmap('jet')) plt.colorbar() #plt.title("Clicks Heatmap Log Normalized") plt.show() plt.savefig('output/clicks_heatmap_lognormed_self_loop_total.pdf') plt.clf() plt.figure(figsize=fig_size) plt.grid(True) plt.imshow(heatmap , extent=extent, origin='upper', norm=Normalize(), cmap=plt.get_cmap('jet')) plt.colorbar() #plt.title("Clicks Heatmap Normalized") plt.show() plt.savefig('output/clicks_heatmap_normed_self_loop_total.pdf') print "done"
def links_heatmap(): #http://stackoverflow.com/questions/2369492/generate-a-heatmap-in-matplotlib-using-a-scatter-data-set # Get URLs from a text file, remove white space. print 'loading' db = MySQLDatabase(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME) db_worker_view = db.get_work_view() coords = db_worker_view.retrieve_all_links_coords() print 'coord loaded' x=[] y=[] page_lenghts = db_worker_view.retrieve_all_page_lengths() print 'lenghts loaded' for coord in coords: x_normed = float(coord['x'])/float(1920) y_normed = float(coord['y'])/float(page_lenghts[coord['source_article_id']]) if x_normed <=1.0 and y_normed <=1.0: x.append(x_normed) y.append(y_normed) heatmap, xedges, yedges = np.histogram2d(x, y, bins=100) extent = [xedges[0], xedges[-1], yedges[-1], yedges[0]] fig_size = (2.4, 2) #fig_size = (3.5, 3) plt.clf() plt.figure(figsize=fig_size) plt.grid(True) plt.imshow(heatmap, extent=extent, origin='upper', norm=LogNorm(), cmap=plt.get_cmap('jet')) plt.colorbar() #plt.title("Links Heatmap Log Normalized") plt.show() plt.savefig('output/links_heatmap_lognormed_self_loop.pdf') plt.clf() plt.figure(figsize=fig_size) plt.grid(True) plt.imshow(heatmap , extent=extent, origin='upper', norm=Normalize(),cmap=plt.get_cmap('jet')) plt.colorbar() #plt.title("Links Heatmap Normalized") plt.show() plt.savefig('output/links_heatmap_normed_self_loop.pdf') print "done"
def show_image(img, name, field_of_view, norm=None, extra_dep=None): """Visualise quadratic image in the (L,M) plane (directional cosines). We assume (0,0) to be at the image center. :param img: Data to visualise as a two-dimensional numpy array :param name: Function name to show in the visualisation header :param field_of_view: Size of the image in radians. We will assume the image to spans coordinates [field_of_view/2;field_of_view/2[ in both L and M. :param extra_dep: Extra functiona parameters to add to the title. Purely cosmetic. """ # Determine size of image. size = img.shape[0] lm_lower, lm_upper = coordinateBounds(size) lm_lower = (lm_lower-1./size/2)*field_of_view lm_upper = (lm_upper+1./size/2)*field_of_view extent = (lm_lower, lm_upper, lm_lower, lm_upper) # Format title title = "%s(l,m%s)" % (name, ','+extra_dep if extra_dep is not None else "") # Determine normalisation for image. if norm is not None: norm = colors.Normalize(vmin=-norm, vmax=norm, clip=True) else: norm = None if numpy.any(numpy.iscomplex(img)): pl.subplot(121) else: pl.subplot(111) pl.imshow(img.real, extent=extent, norm=norm, origin='lower') pl.title(r"$Re(%s)$" % title) pl.xlabel(r"L [$1$]"); pl.ylabel(r"M [$1$]") if norm is None: pl.colorbar(shrink=.4,pad=0.025) if numpy.any(numpy.iscomplex(img)): pl.subplot(122) pl.imshow(img.imag, extent=extent, norm=norm, origin='lower') pl.title(r"$Im(%s)$" % title) pl.xlabel(r"L [$1$]"); pl.ylabel(r"M [$1$]") if norm is None: pl.colorbar(shrink=.4,pad=0.025) pl.show()
def tuneplot(ax1, ax2, data, particleIDs='allIDs', integer=1, addsub=add, clipint=True, showlost=False, QQ='Qx', ms=1, clip=[0], showfit=False): particleIDs = data[particleIDs] if not showlost: lost = data['lost'][:, 0] clip = concatenate([clip, lost]) particleIDs = delete(particleIDs, clip) Q = addsub(integer, data[QQ][particleIDs]) if clipint: zeroQ = find(logical_or(logical_or(Q == 0.0, Q == 1.0), Q == 0.5)) if len(zeroQ) > 0: # trim reference particle with zero tune Q = delete(Q, zeroQ) particleIDs = delete(particleIDs, zeroQ) Qmin, Qmax = nanmin(Q), nanmax(Q) Qdif = Qmax - Qmin if Qdif == 0.0: Qmin -= Qmin/1e4 Qmax += Qmax/1e4 Qdif = Qmax - Qmin colors = cool((Q - Qmin) / Qdif) for i, ID in enumerate(particleIDs): ax1.plot(data['x'][:, ID]*1e3, data['xp'][:, ID]*1e3, '.', c=colors[i], ms=ms) if showlost: for ID in lost: ax1.plot(data['x'][:, ID]*1e3, data['xp'][:, ID]*1e3, '.', c='gray', ms=ms) sm = ScalarMappable(cmap=rainbow, norm=Normalize(vmin=Qmin, vmax=Qmax)) sm._A = [] ax1.set_xlabel(r'Position $x$ / (mm)') ax1.set_ylabel(r'Angle $x^\prime$ / (mrad)') emittance = data['A'][particleIDs]/pi action = emittance/2 # tune shift with action fitfun = lambda x, a, b: a + b*x popt, pcov = curve_fit(fitfun, action, Q) perr = sqrt(diag(pcov)) action2 = linspace(nanmin(action), nanmax(action), 1000) fit1 = fitfun(action2, *popt) print(popt[1]*1e-6*1250) for i, ID in enumerate(particleIDs): ax2.plot(action[i]*1e6, Q[i], 'o', c=colors[i], ms=ms + 1) if showfit: ax2.plot(action2*1e6, fit1, '-k', lw=1, label=r'fit with $TSWA=${:.4}$\pm${:.1} (kHz mm$^-$$^2$mrad$^-$$^2$)'.format(popt[1]*1e-6*1250, perr[1]*1e-6*1250)) # leg = ax2.legend() # leg.get_frame().set_alpha(0) ax2.set_ylim([Qmin, Qmax]) # ax2.yaxis.tick_right() ax2.set_ylabel(r'Fractional Tune $dQ$') # ax2.yaxis.set_label_position('right') ax2.set_xlabel(r'Action $J_x$ / (mm$\cdot$mrad)') tight_layout() return
def plot(self, scale_factor=1.0, plot_ax='x'): time = np.arange(self.delay, (self.n_samples*self.dt + self.delay), self.dt) # Normalize and detrend norm_traces = np.zeros( np.shape(self.timeHistories) ) for k in range(self.n_channels): current_trace = self.timeHistories[:,k] current_trace = signal.detrend(current_trace) # Linear detrend current_trace = current_trace / np.amax(current_trace) # Normalize by max value current_trace = current_trace*scale_factor + self.position[k] # Scale and shift norm_traces[:,k]= current_trace # Plotting if str.lower(plot_ax) == 'y': fig = plt.figure( figsize=(2.75,6) ) ax = fig.add_axes([0.14,0.20,0.8,0.8]) for m in range(self.n_channels): ax.plot(time, norm_traces[:,m],'b-', linewidth=0.5) ax.set_xlim( ( min(time), max(time) ) ) ax.set_ylim( (-self.position[1], self.position[1]+self.position[len(self.position)-1] ) ) ax.set_xticklabels(ax.get_xticks(), fontsize=11, fontname='arial' ) ax.set_yticklabels(ax.get_yticks(), fontsize=11, fontname='arial' ) ax.grid(axis='x', linestyle='--') ax.set_xlabel('Time (s)', fontsize=11, fontname="arial") ax.set_ylabel('Normalized Amplitude', fontsize=11, fontname="arial") ax.tick_params(labelsize=11) ax.tick_params('x', length=4, width=1, which='major') ax.tick_params('y', length=4, width=1, which='major') elif str.lower(plot_ax) == 'x': fig = plt.figure( figsize=(6,2.75) ) ax = fig.add_axes([0.14,0.20,0.8,0.75]) for m in range(self.n_channels): ax.plot(norm_traces[:,m], time, 'b-', linewidth=0.5) ax.set_ylim( ( max(time), min(time) ) ) ax.set_xlim( (-self.position[1], self.position[1]+self.position[len(self.position)-1] ) ) ax.set_yticklabels(ax.get_yticks(), fontsize=11, fontname='arial' ) ax.set_xticklabels(ax.get_xticks(), fontsize=11, fontname='arial' ) ax.grid(axis='y', linestyle='--') ax.set_ylabel('Time (s)', fontsize=11, fontname="arial") ax.set_xlabel('Normalized Amplitude', fontsize=11, fontname="arial") ax.tick_params(labelsize=11) ax.tick_params('y', length=4, width=1, which='major') ax.tick_params('x', length=4, width=1, which='major') return # Method to pad zeros to achieve desired frequency sampling
def animate(self,X,y,useTqdm=0,filename=None,return_anim=True): pos = self.getSteps(X,y) y_mapping = {i:n for n,i in enumerate(set(y))} last_iter = pos[len(pos)-1].reshape(-1, 2) lims = np.max(last_iter,axis=0),np.min(last_iter,axis=0) NCOLORS = len(y_mapping) fig = plt.figure() fig.set_tight_layout(True) ax = fig.add_subplot(111) jet = plt.get_cmap('jet') cNorm = colors.Normalize(vmin=0, vmax=NCOLORS) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) A,B = np.array(list(zip(*pos[0].reshape(-1, 2)))) dots_list = [] for i in range(NCOLORS): colorVal = scalarMap.to_rgba(i) a,b = A[y == i],B[y == i] dots, = ax.plot(b,a,'o',color=colorVal) dots_list.append(dots) def init(): ax.set_xlim([lims[0][0],lims[1][0]]) ax.set_ylim([lims[0][1],lims[1][1]]) return [i for i in dots_list] def update(i): for j in range(len(dots_list)): a,b = np.array(list(zip(*pos[i].reshape(-1, 2)))) a,b = a[y == j],b[y == j] dots_list[j].set_xdata(a) dots_list[j].set_ydata(b) return [i for i in dots_list]+[ax] if useTqdm==0: frames = np.arange(0, len(pos)-1) elif useTqdm==1: from tqdm import tqdm frames = tqdm(np.arange(0, len(pos)-1)) elif useTqdm==2: from tqdm import tqdm_notebook frames = tqdm_notebook(np.arange(0, len(pos)-1)) anim = FuncAnimation(fig, update, frames=frames, init_func=init, interval=50) if return_anim: return anim if filename==None: plt.show() else: #anim.save(filename, fps=20, codec='libx264') anim.save(filename, dpi=80, writer='imagemagick')
def data_to_image(data, is_color_data = None, clims = None, cmap = 'gray', nan_colour=None): import matplotlib.cm as cm from matplotlib.colors import Normalize """ Convert and ndarray of data into RGB pixel data. :param data: An ndarray of data. :param is_color_data: A boolean indicating whether this is colour data already. If not specified we guess. :param clims: The range of values that the colour scale should cover. Values outside this range will be clipped to fall in the range. If None, calculate range from the data. :param cmap: Colormap - Use any of the names in matplotlib - eg ('gray', 'jet', 'Paired', 'cubehelix') :return: An ndarray of unt8 colour data. Shape is: data.shape if is_color_data else data.shape+(3, ) """ if is_color_data is None: is_color_data = data.shape[-1] == 3 if is_color_data: assert data.shape[-1] == 3, 'If data is specified as being colour data, the final axis must have length 3.' if not is_color_data: # Need to apply the cmap. if cmap == 'gray': # For speed, we handle this separately scaled_data = scale_data_to_8_bit(data, in_range=clims) scaled_data = np.concatenate([scaled_data[..., None]]*3, axis = scaled_data.ndim) else: if (clims, cmap) not in mappables: mappables[clims, cmap] = cm.ScalarMappable(cmap = cmap, norm = None if clims is None else Normalize(vmin=clims[0], vmax=clims[1])) cmap = mappables[clims, cmap] old_dim = data.shape if len(old_dim)>2: data = data.reshape((data.shape[0], -1)) rgba = cmap.to_rgba(data) if len(old_dim)>2: rgba = rgba.reshape(old_dim+(4, )) scaled_data = (rgba[..., :-1]*255) else: scaled_data = scale_data_to_8_bit(data, in_range=clims).astype(np.uint8) if nan_colour is not None: scaled_data = np.where(np.any(np.isnan(data if is_color_data else data[..., None]), axis=-1)[..., None], np.array(nan_colour, dtype=np.uint8), scaled_data) return scaled_data
def plot_map(m, coords, df_map, info, savefig=False): plt.clf() fig = plt.figure() ax = fig.add_subplot(111, axisbg='w', frame_on=True) # draw wards with grey outlines norm = Normalize() for i in xrange(5): color = colormaps[i] cmap = plt.get_cmap(color) cond = (df_map['class'] == (i+1)) inx = df_map[cond].index if cond.sum() > 0: pc = PatchCollection(df_map[cond]['patches'], match_original=True, alpha=0.75) pc.set_facecolor(cmap(norm(df_map.loc[inx, 'cls_%d'%(i+1)].values))) ax.add_collection(pc) if (df_map['class'] == 0).sum() > 0: pc = PatchCollection(df_map[df_map['class'] == 0]['patches'], match_original=True, alpha=0.1 ) pc.set_facecolor('grey') ax.add_collection(pc) x, y = m(coords[0], coords[3]+0.006) details = ax.annotate(info, xy=(x, y), size=20, color='k') # Draw a map scale m.drawmapscale( coords[0]+0.02, coords[1]-0.004, coords[0], coords[1], 2, barstyle='fancy', labelstyle='simple', fillcolor1='w', fillcolor2='#555555', fontcolor='#555555', units='mi', zorder=5) legend_patches = [] for i in range(5): legend_patches.append(mpatches.Patch(color='C%d' % i, label=classes[i])) ax.legend(handles=legend_patches, loc='upper right') fig.set_size_inches(12, 12) plt.tight_layout() if savefig: plt.savefig(savefig, dpi=200, alpha=True)
def plot_data(lda, X, y, y_pred, fig_index): splot = plt.subplot(2, 2, fig_index) if fig_index == 1: plt.title('Linear Discriminant Analysis') plt.ylabel('Data with fixed covariance') elif fig_index == 2: plt.title('Quadratic Discriminant Analysis') elif fig_index == 3: plt.ylabel('Data with varying covariances') tp = (y == y_pred) # True Positive tp0, tp1 = tp[y == 0], tp[y == 1] X0, X1 = X[y == 0], X[y == 1] X0_tp, X0_fp = X0[tp0], X0[~tp0] X1_tp, X1_fp = X1[tp1], X1[~tp1] # class 0: dots plt.plot(X0_tp[:, 0], X0_tp[:, 1], 'o', color='red') plt.plot(X0_fp[:, 0], X0_fp[:, 1], '.', color='#990000') # dark red # class 1: dots plt.plot(X1_tp[:, 0], X1_tp[:, 1], 'o', color='blue') plt.plot(X1_fp[:, 0], X1_fp[:, 1], '.', color='#000099') # dark blue # class 0 and 1 : areas nx, ny = 200, 100 x_min, x_max = plt.xlim() y_min, y_max = plt.ylim() xx, yy = np.meshgrid(np.linspace(x_min, x_max, nx), np.linspace(y_min, y_max, ny)) Z = lda.predict_proba(np.c_[xx.ravel(), yy.ravel()]) Z = Z[:, 1].reshape(xx.shape) plt.pcolormesh(xx, yy, Z, cmap='red_blue_classes', norm=colors.Normalize(0., 1.)) plt.contour(xx, yy, Z, [0.5], linewidths=2., colors='k') # means plt.plot(lda.means_[0][0], lda.means_[0][1], 'o', color='black', markersize=10) plt.plot(lda.means_[1][0], lda.means_[1][1], 'o', color='black', markersize=10) return splot
def _plot_zsolid(self): collection = self.crossplot_ax.plot(self.xdata, self.ydata, 'bo') self.collections.append(collection) # # if self.parts is None: # parts = [np.ones_like(self.xdata, dtype=bool)] # else: # parts = self.parts # ## print ## print parts # # good = np.sum(parts, axis=0, dtype=bool) # good *= np.isfinite(self.xdata) # good *= np.isfinite(self.ydata) # # #if self.zdata is not None: # # good *= np.isfinite(self.zdata) # TODO: Sem essa linha, onde não houver perfil z será plotado de ?preto? # ## zticks = self.zlocator(np.min(self.zdata[good]), np.max(self.zdata[good])) ## self.zlim = [zticks[0], zticks[-1]] ## self.zticks = zticks[1:-1] # # # # #norm = Normalize(*self.zlim) # # # ''' # for part in parts: # x = self.xdata[part * good] # y = self.ydata[part * good] # #c = self.zdata[part*good] # collection = self.crossplot_ax.scatter(x, y, #c=c, cmap=self.cmap, # zorder=-len(x), # **self.collectionproperties # ) # self.collections.append(collection) # # # ''' # xticks = self.xlocator(np.min(self.xdata), np.max(self.xdata)) # self.set_xlim([xticks[0], xticks[-1]]) # # yticks = self.ylocator(np.min(self.ydata), np.max(self.ydata)) # self.set_ylim([yticks[0], yticks[-1]]) # # self.colorbar = None # # #self.colorbar = ColorbarBase(self.colorbar_ax, cmap=self.cmap, # # norm=norm, ticks=self.zticks # #) # #self.colorbar_ax.yaxis.set_major_formatter(NullFormatter())
def __init__(self, ax, ax_colorbar, scraper, top, w3d): """ Plots density of scraped particles on conducting objects. Can evaluate density on each surface of a Box or ZPlane separately and produce shaded density plots. To run automatically: call an initialized PlotDensity object. Warning: Only Box and ZPlane are supported at this time. Other conductor shapes will not be evaluated correctly. Only for 2D XZ simulations at this time. Args: ax: Matplotlib axes object for surface density plots. ax_colorbar: Matplotlib axes object for colorbar. scraper: Warp ParticleScraper object. Only used to acquire conductor positions and dimensions. top: Warp top object. w3d: Warp w3d object. Useful attributes: ax: Matplotilb axes object for density plots ax_colorbar: Matplotlib axes object for colorbar scraper: Warp ParticleScraper object zplost: Array of z-positions of lost particles. Defaults to top.zplost. xplost: Array of x-positions of lost particles. Defaults to top.xplost. dz, dx: z and x widths used to gate on particles collected by conductor side. Defaults to w3d.dz and w3d.dx scale: Set scale of x and z units. Defaults to 1e6 (units of microns). cmap: matplotlib.cm colormap. Defaults to coolwarm. normalization: matplotlib.colors normalization function. Defaults to Normalize (linear normalization). """ self.ax = ax self.ax_colorbar = ax_colorbar self.scraper = scraper self.top = top self.w3d = w3d self.gated_ids = {} self.dx = w3d.dx self.dz = w3d.dz self.scale = 1e6 # categorize the number lost to avoid padded values at end of array self.numlost = top.npslost[0] assert self.numlost > 1, "No particles lost in simulation. Nothing to plot." self.zplost = self.top.zplost[:self.numlost] self.xplost = self.top.xplost[:self.numlost] self.cmap = cm.coolwarm self.normalization = Normalize self.cmap_normalization = None