我们从Python开源项目中,提取了以下39个代码示例,用于说明如何使用matplotlib.cm.ScalarMappable()。
def __init__(self, context, width=11.7, height=8.3, dpi=100, parent=None): """ :type context: segyviewlib.SliceViewContext """ super(SliceViewWidget, self).__init__(width, height, dpi, parent) self._assigned_slice_models = list(context.models) """ :type: list[SliceModel] """ self._slice_views = {} """ :type: dict[matplotlib.axes.Axes,SliceView] """ self._colormappable = ScalarMappable(cmap=context.colormap) self._colormappable.set_array([]) self._context = context context.context_changed.connect(self._context_changed) context.data_changed.connect(self._data_changed) context.data_source_changed.connect(self._layout_changed) self.layout_changed.connect(self._layout_changed) self.subplot_pressed.connect(self._subplot_clicked) self.subplot_scrolled.connect(self._subplot_scrolled) self.subplot_motion.connect(self._subplot_motion)
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 init_cmap_popup_menu(self): cmap_button_bitmap_height = 10 cmap_button_bitmap_width = 200 cmap_menu_bitmap_height = 20 cmap_menu_bitmap_width = 200 self.cmap_button_bitmaps = {} self.cmap_menu_bitmaps = {} for cmap in self.ztv_frame.available_cmaps: temp = cm.ScalarMappable(cmap=cmap) rgba = temp.to_rgba(np.outer(np.ones(cmap_button_bitmap_height, dtype=np.uint8), np.arange(cmap_button_bitmap_width, dtype=np.uint8))) self.cmap_button_bitmaps[cmap] = wx.BitmapFromBufferRGBA(cmap_button_bitmap_width, cmap_button_bitmap_height, np.uint8(np.round(rgba*255))) rgba = temp.to_rgba(np.outer(np.ones(cmap_menu_bitmap_height, dtype=np.uint8), np.arange(cmap_menu_bitmap_width, dtype=np.uint8))) self.cmap_menu_bitmaps[cmap] = wx.BitmapFromBufferRGBA(cmap_menu_bitmap_width, cmap_menu_bitmap_height, np.uint8(np.round(rgba*255))) menu = wx.Menu() for cmap in self.ztv_frame.available_cmaps: menu_item = menu.AppendCheckItem(self.cmap_to_eventID[cmap], cmap) wx.EVT_MENU(menu, self.cmap_to_eventID[cmap], self.on_change_cmap_event) if hasattr(menu_item, 'SetBitmap'): menu_item.SetBitmap(self.cmap_menu_bitmaps[cmap]) self.cmap_popup_menu = menu
def gen_colorbar(self, colors, color_map, labels=None, **kwargs): """Create colour scale bar on map Args: colors: colours of map color_map: chloropleth map labels: label of map, default none kwargs: arguments for colourbar Returns: a colorbar """ color_map = self.split_colormap(color_map, colors) mappable = cm.ScalarMappable(cmap=color_map) mappable.set_array([]) mappable.set_clim(-0.5, colors + 0.5) colorbar = plt.colorbar(mappable, **kwargs) colorbar.set_ticks(np.linspace(0, colors, colors)) colorbar.set_ticklabels(range(colors)) if labels: colorbar.set_ticklabels(labels) return colorbar
def colorbar_index(plot_thing, ncolors, cmap, labels, colourbar_ax): """ Source: http://sensitivecities.com/so-youd-like-to-make-a-map-using-python-EN.html """ cmap = Choroplether.cmap_discretize(cmap, ncolors) mappable = cm.ScalarMappable(cmap=cmap) mappable.set_array([]) mappable.set_clim(-0.5, ncolors+0.5) color_bar = plot_thing.colorbar( mappable, ax=colourbar_ax, drawedges=True, shrink=0.5, aspect=40, pad=0.01 ) color_bar.set_ticks(np.linspace(0, ncolors, ncolors)) color_bar.set_ticklabels(range(ncolors)) color_bar.set_ticklabels(labels) color_bar.outline.set_edgecolor(Choroplether.GREY) color_bar.outline.set_linewidth(Choroplether.LINE_WIDTH) return color_bar
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 colorbar_index(ncolors, cmap, labels=None, **kwargs): """ This is a convenience function to stop you making off-by-one errors Takes a standard colour ramp, and discretizes it, then draws a colour bar with correctly aligned labels """ cmap = cmap_discretize(cmap, ncolors) mappable = cm.ScalarMappable(cmap=cmap) mappable.set_array([]) mappable.set_clim(-0.5, ncolors+0.5) colorbar = plt.colorbar(mappable, **kwargs) colorbar.set_ticks(np.linspace(0, ncolors, ncolors)) colorbar.set_ticklabels(range(ncolors)) if labels: colorbar.set_ticklabels(labels) return colorbar
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 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 __init__(self): QMainWindow.__init__(self) self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowTitle("GUI Test") toolbar = self.addToolBar("Stuff") """:type: QToolBar""" layout_combo = LayoutCombo() toolbar.addWidget(layout_combo) layout_combo.layout_changed.connect(self._layout_changed) self._colormap_combo = ColormapCombo() toolbar.addWidget(self._colormap_combo) self._colormap_combo.currentIndexChanged[int].connect(self._colormap_changed) central_widget = QWidget() layout = QVBoxLayout() central_widget.setLayout(layout) self._layout_canvas = LayoutCanvas(width=5, height=5) self._layout_canvas.set_plot_layout(layout_combo.get_current_layout()) layout.addWidget(self._layout_canvas) colormap_name = str(self._colormap_combo.itemText(0)) self._colormap = mcm.ScalarMappable(cmap=colormap_name) self._colormap.set_array([]) self._colormap_label = QLabel() layout.addWidget(self._colormap_label) self.setCentralWidget(central_widget) self._update_axes()
def _create_icon(self, color_map_name, image, values): """" :type color_map_name: str :type image: QImage :type values: np.ndarray """ color_map = ScalarMappable(cmap=color_map_name) rgba = color_map.to_rgba(values, bytes=True) color_table = [qRgb(c[0], c[1], c[2]) for c in rgba] image.setColorTable(color_table) return QPixmap.fromImage(image).scaledToWidth(128)
def add_color_bar(ax, cmap, labels): """Add a colorbar to an axis. Args: ax (AxesSubplot) cmap (Colormap): A prepaped colormap of size n. labels (list of str): A list of strings of size n. """ norm = clr.BoundaryNorm(list(range(cmap.N+1)), cmap.N) smap = cm.ScalarMappable(norm=norm, cmap=cmap) smap.set_array([]) cbar = plt.colorbar(smap, ax=ax) cbar.set_ticks([i + 0.5 for i in range(cmap.N)]) cbar.set_ticklabels(labels)
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 colorbar_index(ncolors, cmap): # http://stackoverflow.com/a/18707445/1889400 mappable = cm.ScalarMappable(cmap=cmap) mappable.set_array([]) mappable.set_clim(-0.5, ncolors + 0.5) colorbar = plt.colorbar(mappable) colorbar.set_ticks(np.linspace(0, ncolors, ncolors)) colorbar.set_ticklabels(range(ncolors))
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 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 _colorbar_index(ncolors, cmap): cmap = _cmap_discretize(cmap, ncolors) mappable = cm.ScalarMappable(cmap=cmap) mappable.set_array([]) mappable.set_clim(-0.5, ncolors+0.5) colorbar = plt.colorbar(mappable) colorbar.set_ticks(np.linspace(0, ncolors, ncolors)) colorbar.set_ticklabels(range(ncolors))
def color_mapping(arr, cmap): sm = ScalarMappable(cmap=cmap) sm.set_array(arr) sm.autoscale() return map(rgb2hex, sm.to_rgba(arr))
def plot_with_labels(self, data_set: DataSet, embedding: np.ndarray): assert embedding.shape[0] >= len(data_set.label_map), "More labels than weights" # use pandas to get indices of instances with the same label df = pd.DataFrame({"labels_numeric": data_set.labels_numeric}) label_indices = {label: indices.tolist() for label, indices in df.groupby(df.labels_numeric).groups.items()} norm = matplotlib.colors.Normalize(vmin=min(label_indices.keys()), vmax=max(label_indices.keys()), clip=True) mapper = cm.ScalarMappable(norm=norm, cmap="jet") for label, indices in label_indices.items(): coords = embedding[indices, :] plt.plot(coords[:, 0], coords[:, 1], 'o', ms=6, color=mapper.to_rgba(label)) handles = [] # noinspection PyTypeChecker for key in data_set.label_map: handles.append(matplotlib.patches.Patch(color=mapper.to_rgba(data_set.label_map[key]), label=key)) plt.legend(handles=handles, bbox_to_anchor=(0, -0.125, 1, 0), loc=2, mode="expand", borderaxespad=0., ncol=3) plt.tight_layout() plt.subplots_adjust(bottom=0.33) 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 get_scalar_map(x_min, x_max, color_map='jet'): cm = plt.get_cmap(color_map) cNorm = matplotlib.colors.Normalize(vmin=x_min, vmax=x_max) return cmx.ScalarMappable(norm=cNorm, cmap=cm)
def colorbar(cmap="jet", cm_min=0, cm_max=1): if isinstance(cmap, str): cmap = cmget_cmap(cmap) norm = matplotlibpyplotNormalize(cm_min, cm_max) mappable = cmScalarMappable(cmap=cmap, norm=norm) mappable._A = [] return cmap, norm, mappable
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 _update_colors(self, color_spec): """ Takes a sequence of 4 color tuples, builds the color maps, if the plot data isn't none will modify the plot colors """ self._colors = color_spec self._color_maps = [visualizer_colors.PMIColormap("PMIFriend", color_spec[0]), visualizer_colors.PMIColormap("PMITryst", color_spec[1]), visualizer_colors.PMIColormap("PMIHeadToHead", color_spec[2]), visualizer_colors.PMIColormap("PMIArmsRace", color_spec[3])] self.color_mappers = [cm.ScalarMappable(norm=self._normalizer, cmap=self._color_maps[0]), cm.ScalarMappable(norm=self._normalizer, cmap=self._color_maps[1]), cm.ScalarMappable(norm=self._normalizer, cmap=self._color_maps[2]), cm.ScalarMappable(norm=self._normalizer, cmap=self._color_maps[3])] self.color_samples = dict() self._legend_proxies = [] for mapper, name in zip(self.color_mappers, self.data.relation_types): rgba = mapper.to_rgba(0.7, bytes=True) self.color_samples[name] = rgba self._legend_proxies.append(mpatches.Patch(color=[i/255 for i in rgba], label=name)) self._on_color_changed() self._mpl.redraw()
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 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_wigner_plaquette(wigner_data, max_wigner='local'): """Plots plaquette of wigner function data, the plaquette will consist of cicles each colored to match the value of the Wigner function at the given point in phase space. Args: wigner_data (matrix): array of Wigner function data where the rows are plotted along the x axis and the columns are plotted along the y axis max_wigner: - 'local' puts the maximum value to maximum of the points - 'unit' sets maximum to 1 - float for a custom maximum. Returns: none: plot is shown with matplotlib to the screen """ wigner_data = np.matrix(wigner_data) dim = wigner_data.shape if max_wigner == 'local': w_max = np.amax(wigner_data) elif max_wigner == 'unit': w_max = 1 else: w_max = max_wigner # For a float input cmap = plt.cm.get_cmap('seismic_r') xax = dim[1]-0.5 yax = dim[0]-0.5 norm = np.amax(dim) fig = plt.figure(figsize=((xax+0.5)*6/norm, (yax+0.5)*6/norm)) ax = fig.gca() for x in range(int(dim[1])): for y in range(int(dim[0])): circle = plt.Circle( (x, y), 0.49, color=cmap((wigner_data[y, x]+w_max)/(2*w_max))) ax.add_artist(circle) ax.set_xlim(-1, xax+0.5) ax.set_ylim(-1, yax+0.5) ax.set_xticks([], []) ax.set_yticks([], []) m = cm.ScalarMappable(cmap=cm.seismic_r) m.set_array([-w_max, w_max]) plt.colorbar(m, shrink=0.5, aspect=10) plt.show()
def __call__(self, plot): from matplotlib import cm x0, x1 = plot.xlim y0, y1 = plot.ylim xx0, xx1 = plot._axes.get_xlim() yy0, yy1 = plot._axes.get_ylim() bounds = [x0,x1,y0,y1] extent = [xx0,xx1,yy0,yy1] # We are feeding this size into the pixelizer, where it will properly # set it in reverse order nx = plot.image._A.shape[1] ny = plot.image._A.shape[0] pixX = plot.data.ds.coordinates.pixelize(plot.data.axis, plot.data, self.field_x, bounds, (ny,nx)) pixY = plot.data.ds.coordinates.pixelize(plot.data.axis, plot.data, self.field_y, bounds, (ny,nx)) vectors = np.concatenate((pixX[...,np.newaxis], pixY[...,np.newaxis]),axis=2) if self.texture is None: self.texture = np.random.rand(nx,ny).astype(np.double) elif self.texture.shape != (nx,ny): raise SyntaxError("'texture' must have the same shape " "with that of output image (%d, %d)" % (nx,ny)) kernel = np.sin(np.arange(self.kernellen)*np.pi/self.kernellen) kernel = kernel.astype(np.double) lic_data = line_integral_convolution_2d(vectors,self.texture,kernel) lic_data = lic_data / lic_data.max() lic_data_clip = np.clip(lic_data,self.lim[0],self.lim[1]) if self.const_alpha: plot._axes.imshow(lic_data_clip, extent=extent, cmap=self.cmap, alpha=self.alpha, origin='lower', aspect="auto") else: lic_data_rgba = cm.ScalarMappable(norm=None, cmap=self.cmap).\ to_rgba(lic_data_clip) lic_data_clip_rescale = (lic_data_clip - self.lim[0]) \ / (self.lim[1] - self.lim[0]) lic_data_rgba[...,3] = lic_data_clip_rescale * self.alpha plot._axes.imshow(lic_data_rgba, extent=extent, cmap=self.cmap, origin='lower', aspect="auto") return plot
def __init__(self, parent, dpi=None, **kwargs): wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, wx.Size(512,512), **kwargs) self.ztv_frame = self.GetTopLevelParent() self.accelerator_table = [] self.center = wx.RealPoint() self.zoom_rect = None self.eventID_to_cmap = {wx.NewId(): x for x in self.ztv_frame.available_cmaps} self.cmap_to_eventID = {self.eventID_to_cmap[x]: x for x in self.eventID_to_cmap} self.eventID_to_scaling = {wx.NewId(): x for x in self.ztv_frame.available_scalings} self.scaling_to_eventID = {self.eventID_to_scaling[x]: x for x in self.eventID_to_scaling} cmap_bitmap_height = 15 cmap_bitmap_width = 100 self.cmap_bitmaps = {} for cmap in self.ztv_frame.available_cmaps: temp = cm.ScalarMappable(cmap=cmap) rgba = temp.to_rgba(np.outer(np.ones(cmap_bitmap_height, dtype=np.uint8), np.arange(cmap_bitmap_width, dtype=np.uint8))) self.cmap_bitmaps[cmap] = wx.BitmapFromBufferRGBA(cmap_bitmap_width, cmap_bitmap_height, np.uint8(np.round(rgba*255))) self.popup_menu_cursor_modes = ['Zoom', 'Pan'] self.available_cursor_modes = {'Zoom':{'set-to-mode':self.set_cursor_to_zoom_mode}, 'Pan':{'set-to-mode':self.set_cursor_to_pan_mode}} self.available_key_presses = {} self.cursor_mode = 'Zoom' self.max_doubleclick_sec = 0.5 # needed to trap 'real' single clicks from the first click of a double click self.popup_menu_needs_rebuild = True self.popup_menu = None self.xlim = [-9e9, 9e9] self.ylim = [-9e9, 9e9] self.figure = Figure(None, dpi) self.axes = self.figure.add_axes([0., 0., 1., 1.]) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.Bind(wx.EVT_SIZE, self._onSize) self.axes_widget = AxesWidget(self.figure.gca()) self.axes_widget.connect_event('motion_notify_event', self.on_motion) self.axes_widget.connect_event('figure_leave_event', self.on_cursor_leave) self.axes_widget.connect_event('figure_enter_event', self.on_cursor_enter) self.axes_widget.connect_event('button_press_event', self.on_button_press) self.axes_widget.connect_event('button_release_event', self.on_button_release) self.axes_widget.connect_event('key_press_event', self.on_key_press) wx.EVT_RIGHT_DOWN(self.figure.canvas, self.on_right_down) # supercedes the above button_press_event pub.subscribe(self.redraw_primary_image, 'redraw-image') pub.subscribe(self.reset_zoom_and_center, 'reset-zoom-and-center') pub.subscribe(self.set_zoom_factor, 'set-zoom-factor') pub.subscribe(self.set_xy_center, 'set-xy-center')
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 scatterColor(x0, y, w): """Creates scatter plot with points colored by variable. All input arrays must have matching lengths :param x0: x values to plot :type x0: list :param y: y values to plot :type y: list :param w: z values to plot :returns: plot; slope and intercept of the RLM best fit line shown on the plot .. warning:: all input arrays must have matching lengths and scalar values .. note:: See documentation at http://statsmodels.sourceforge.net/0.6.0/generated/statsmodels.robust.robust_linear_model.RLM.html for the RLM line """ import matplotlib as mpl import matplotlib.cm as cm import statsmodels.api as sm from scipy.stats import linregress cmap = plt.cm.get_cmap('RdYlBu') norm = mpl.colors.Normalize(vmin=w.min(), vmax=w.max()) m = cm.ScalarMappable(norm=norm, cmap=cmap) m.set_array(w) sc = plt.scatter(x0, y, label='', color=m.to_rgba(w)) xa = sm.add_constant(x0) est = sm.RLM(y, xa).fit() r2 = sm.WLS(y, xa, weights=est.weights).fit().rsquared slope = est.params[1] x_prime = np.linspace(np.min(x0), np.max(x0), 100)[:, np.newaxis] x_prime = sm.add_constant(x_prime) y_hat = est.predict(x_prime) const = est.params[0] y2 = [i * slope + const for i in x0] lin = linregress(x0, y) x1 = np.arange(np.min(x0), np.max(x0), 0.1) y1 = [i * lin[0] + lin[1] for i in x1] y2 = [i * slope + const for i in x1] plt.plot(x1, y1, c='g', label='simple linear regression m = {:.2f} b = {:.0f}, r^2 = {:.2f}'.format(lin[0], lin[1], lin[2] ** 2)) plt.plot(x1, y2, c='r', label='rlm regression m = {:.2f} b = {:.0f}, r2 = {:.2f}'.format(slope, const, r2)) plt.legend() cbar = plt.colorbar(m) cbar.set_label('Julian Date') return slope, const
def nwis_heat_map(self): from scipy.interpolate import griddata import matplotlib.cm as cm import matplotlib as mpl meth = 'linear' # 'nearest' data = self.data if isinstance(data.index, pd.core.index.MultiIndex): data.index = data.index.droplevel(0) x = data.index.dayofyear y = data.index.year z = data.value.values xi = np.linspace(x.min(), x.max(), 1000) yi = np.linspace(y.min(), y.max(), 1000) zi = griddata((x, y), z, (xi[None, :], yi[:, None]), method=meth) cmap = plt.cm.get_cmap('RdYlBu') norm = mpl.colors.Normalize(vmin=z.min(), vmax=z.max()) #norm = mpl.colors.LogNorm(vmin=0.1, vmax=100000) m = cm.ScalarMappable(norm=norm, cmap=cmap) m.set_array(z) br = plt.contourf(xi, yi, zi, color=m.to_rgba(z), cmap=cmap) # setup the colorbar cbar = plt.colorbar(m) cbar.set_label('Discharge (cfs)') plt.xlabel('Month') plt.ylabel('Year') plt.yticks(range(y.min(), y.max())) mons = {'Apr': 90.25, 'Aug': 212.25, 'Dec': 334.25, 'Feb': 31, 'Jan': 1, 'Jul': 181.25, 'Jun': 151.25, 'Mar': 59.25, 'May': 120.25, 'Nov': 304.25, 'Oct': 273.25, 'Sep': 243.25} monnms = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] plt.title(self.sites.station_nm[0].title()) tickplc = [] plt.xticks([mons[i] for i in monnms], monnms) plt.grid()