Python matplotlib.collections() Examples
The following are 15
code examples of matplotlib.collections().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib
, or try the search function
.
Example #1
Source File: _plot.py From spm1d with GNU General Public License v3.0 | 6 votes |
def _set_ylim(self, pad=0.075): def minmax(x): return np.ma.min(x), np.ma.max(x) ax = self.ax ymin,ymax = +1e10, -1e10 for line in ax.lines: y0,y1 = minmax( line.get_data()[1] ) ymin = min(y0, ymin) ymax = max(y1, ymax) for collection in ax.collections: datalim = collection.get_datalim(ax.transData) y0,y1 = minmax( np.asarray(datalim)[:,1] ) ymin = min(y0, ymin) ymax = max(y1, ymax) for text in ax.texts: r = matplotlib.backend_bases.RendererBase() bbox = text.get_window_extent(r) y0,y1 = ax.transData.inverted().transform(bbox)[:,1] ymin = min(y0, ymin) ymax = max(y1, ymax) dy = 0.075*(ymax-ymin) ax.set_ylim(ymin-dy, ymax+dy)
Example #2
Source File: core.py From neuropythy with GNU Affero General Public License v3.0 | 5 votes |
def on_key(self, event): import matplotlib.collections if event.inaxes != self.line.axes: return if event.key == 'tab': # we go to the next plot... if not self.plot_list: return self.plot_list[self.current_plot].set_visible(False) tmp = self.current_plot self.current_plot = (self.current_plot + 1) % len(self.plot_list) a = self.plot_list[self.current_plot] if isinstance(a, matplotlib.collections.TriMesh): a.set_visible(True) else: self.plot_list[self.current_plot] = a(self.axes) a.figure.canvas.draw()
Example #3
Source File: Map.py From PyMICAPS with GNU General Public License v2.0 | 5 votes |
def DrawContourAndMark(contour, x, y, z, level, clipborder, patch, m): # 是否绘制等值线 ------ 等值线和标注是一体的 if contour.contour['visible']: matplotlib.rcParams['contour.negative_linestyle'] = 'dashed' if contour.contour['colorline']: CS1 = m.contour(x, y, z, levels=level, linewidths=contour.contour['linewidth']) else: CS1 = m.contour(x, y, z, levels=level, linewidths=contour.contour['linewidth'], colors=contour.contour['linecolor']) # 是否绘制等值线标注 CS2 = None if contour.contourlabel['visible']: CS2 = plt.clabel(CS1, inline=1, fmt=contour.contourlabel['fmt'], inline_spacing=contour.contourlabel['inlinespacing'], fontsize=contour.contourlabel['fontsize'], colors=contour.contourlabel['fontcolor']) # 用区域边界裁切等值线图 if clipborder.path is not None and clipborder.using: for collection in CS1.collections: # collection.set_clip_on(True) collection.set_clip_path(patch) if CS2 is not None: for text in CS2: if not clipborder.path.contains_point(text.get_position()): text.remove()
Example #4
Source File: parasite_axes.py From Computable with MIT License | 5 votes |
def _contour(self, method_name, *XYCL, **kwargs): if len(XYCL) <= 2: C = XYCL[0] ny, nx = C.shape gx = np.arange(0., nx, 1.) gy = np.arange(0., ny, 1.) X,Y = np.meshgrid(gx, gy) CL = XYCL else: X, Y = XYCL[:2] CL = XYCL[2:] contour_routine = self._get_base_axes_attr(method_name) if kwargs.has_key("transform"): cont = contour_routine(self, X, Y, *CL, **kwargs) else: orig_shape = X.shape xy = np.vstack([X.flat, Y.flat]) xyt=xy.transpose() wxy = self.transAux.transform(xyt) gx, gy = wxy[:,0].reshape(orig_shape), wxy[:,1].reshape(orig_shape) cont = contour_routine(self, gx, gy, *CL, **kwargs) for c in cont.collections: c.set_transform(self._parent_axes.transData) return cont
Example #5
Source File: parasite_axes.py From Computable with MIT License | 5 votes |
def _get_handles(ax): handles = ax.lines[:] handles.extend(ax.patches) handles.extend([c for c in ax.collections if isinstance(c, mcoll.LineCollection)]) handles.extend([c for c in ax.collections if isinstance(c, mcoll.RegularPolyCollection)]) handles.extend([c for c in ax.collections if isinstance(c, mcoll.CircleCollection)]) return handles
Example #6
Source File: parasite_axes.py From matplotlib-4-abaqus with MIT License | 5 votes |
def _contour(self, method_name, *XYCL, **kwargs): if len(XYCL) <= 2: C = XYCL[0] ny, nx = C.shape gx = np.arange(0., nx, 1.) gy = np.arange(0., ny, 1.) X,Y = np.meshgrid(gx, gy) CL = XYCL else: X, Y = XYCL[:2] CL = XYCL[2:] contour_routine = self._get_base_axes_attr(method_name) if kwargs.has_key("transform"): cont = contour_routine(self, X, Y, *CL, **kwargs) else: orig_shape = X.shape xy = np.vstack([X.flat, Y.flat]) xyt=xy.transpose() wxy = self.transAux.transform(xyt) gx, gy = wxy[:,0].reshape(orig_shape), wxy[:,1].reshape(orig_shape) cont = contour_routine(self, gx, gy, *CL, **kwargs) for c in cont.collections: c.set_transform(self._parent_axes.transData) return cont
Example #7
Source File: parasite_axes.py From matplotlib-4-abaqus with MIT License | 5 votes |
def _get_handles(ax): handles = ax.lines[:] handles.extend(ax.patches) handles.extend([c for c in ax.collections if isinstance(c, mcoll.LineCollection)]) handles.extend([c for c in ax.collections if isinstance(c, mcoll.RegularPolyCollection)]) handles.extend([c for c in ax.collections if isinstance(c, mcoll.CircleCollection)]) return handles
Example #8
Source File: lineplot.py From PyXRF with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot_selected_energy_range(self, *, e_low=None, e_high=None): """ Plot the range of energies selected for processing. The range may be optionally provided as arguments. The range values that are not provided, are read from globally accessible dictionary of parameters. The values passed as arguments are mainly used if the function is called during interactive update of the range, when the order of update is undetermined and the parameter dictionary may be updated after the function is called. """ # The range of energy selected for analysis if e_low is None: e_low = self.param_model.param_new['non_fitting_values']['energy_bound_low']['value'] if e_high is None: e_high = self.param_model.param_new['non_fitting_values']['energy_bound_high']['value'] n_x = 4096 # Set to the maximum possible number of points # Generate the values for 'energy' axis x_v = (self.parameters['e_offset']['value'] + np.arange(n_x) * self.parameters['e_linear']['value'] + np.arange(n_x) ** 2 * self.parameters['e_quadratic']['value']) ss = (x_v < e_high) & (x_v > e_low) y_min, y_max = 1e-30, 1e30 # Select the max and min values for plotted rectangles # Remove the plot if it exists if self.plot_energy_barh in self._ax.collections: self._ax.collections.remove(self.plot_energy_barh) # Create the new plot (based on new parameters if necessary self.plot_energy_barh = BrokenBarHCollection.span_where( x_v, ymin=y_min, ymax=y_max, where=ss, facecolor='white', edgecolor='yellow', alpha=1) self._ax.add_collection(self.plot_energy_barh)
Example #9
Source File: map.py From skymapper with MIT License | 5 votes |
def vertex(self, vertices, color=None, vmin=None, vmax=None, **kwargs): """Plot polygons (e.g. Healpix vertices) Args: vertices: cell boundaries in RA/Dec, from getCountAtLocations() color: string or matplib color, or numeric array to set polygon colors vmin: if color is numeric array, use vmin to set color of minimum vmax: if color is numeric array, use vmin to set color of minimum **kwargs: matplotlib.collections.PolyCollection keywords Returns: matplotlib.collections.PolyCollection """ vertices_ = np.empty_like(vertices) vertices_[:,:,0], vertices_[:,:,1] = self.proj.transform(vertices[:,:,0], vertices[:,:,1]) # remove vertices which are split at the outer meridians # find variance of vertice nodes large compared to dispersion of centers centers = np.mean(vertices, axis=1) x, y = self.proj.transform(centers[:,0], centers[:,1]) var = np.sum(np.var(vertices_, axis=1), axis=-1) / (x.var() + y.var()) sel = var < 0.05 vertices_ = vertices_[sel] from matplotlib.collections import PolyCollection zorder = kwargs.pop("zorder", 0) # same as for imshow: underneath everything rasterized = kwargs.pop('rasterized', True) alpha = kwargs.pop('alpha', 1) if alpha < 1: lw = kwargs.pop('lw', 0) else: lw = kwargs.pop('lw', None) coll = PolyCollection(vertices_, zorder=zorder, rasterized=rasterized, alpha=alpha, lw=lw, **kwargs) if color is not None: coll.set_array(color[sel]) coll.set_clim(vmin=vmin, vmax=vmax) coll.set_edgecolor("face") self.ax.add_collection(coll) self.ax.set_rasterization_zorder(zorder) return coll
Example #10
Source File: map.py From skymapper with MIT License | 5 votes |
def footprint(self, survey, nside, **kwargs): """Plot survey footprint onto map Uses `contains()` method of a `skymapper.Survey` derived class instance Args: survey: name of the survey, must be in keys of `skymapper.survey_register` nside: HealPix nside **kwargs: styling of `matplotlib.collections.PolyCollection` """ pixels, rap, decp, vertices = healpix.getGrid(nside, return_vertices=True) inside = survey.contains(rap, decp) return self.vertex(vertices[inside], **kwargs)
Example #11
Source File: plotlayer.py From omg-tools with GNU Lesser General Public License v3.0 | 5 votes |
def _update_axis_2d(axis, info, data): if 'lines' in data: for p, dat in enumerate(data['lines']): axis.lines[p].set_data(dat[0, :].ravel(), dat[1, :].ravel()) if 'surfaces' in data: for p, dat in enumerate(data['surfaces']): axis.collections[p].set_verts([dat.T.tolist()]) axis.relim() scalex = ('xlim' not in info or info['xlim'] is None) scaley = ('ylim' not in info or info['ylim'] is None) axis.autoscale_view(True, scalex, scaley)
Example #12
Source File: plotlayer.py From omg-tools with GNU Lesser General Public License v3.0 | 5 votes |
def _update_axis_3d(axis, info, data): if 'lines' in data: for p, dat in enumerate(data['lines']): axis.lines[p].set_data(dat[0, :].ravel(), dat[1, :].ravel()) axis.lines[p].set_3d_properties(dat[2, :].ravel()) if 'surfaces' in data: for p, dat in enumerate(data['surfaces']): axis.collections[p].set_verts([dat.T.tolist()]) axis.relim() scalex = ('xlim' not in info or info['xlim'] is None) scaley = ('ylim' not in info or info['ylim'] is None) scalez = ('zlim' not in info or info['zlim'] is None) axis.autoscale_view(True, scalex, scaley, scalez) if 'aspect_equal' in info and info['aspect_equal']: # hack due to bug in matplotlib3d limits = [] if 'xlim' in info: limits.append(info['xlim']) else: limits.append(axis.get_xlim3d()) if 'ylim' in info: limits.append(info['ylim']) else: limits.append(axis.get_ylim3d()) if 'zlim' in info: limits.append(info['zlim']) else: limits.append(axis.get_zlim3d()) ranges = [abs(lim[1] - lim[0]) for lim in limits] centra = [np.mean(lim) for lim in limits] radius = 0.5*max(ranges) axis.set_xlim3d([centra[0] - radius, centra[0] + radius]) axis.set_ylim3d([centra[1] - radius, centra[1] + radius]) axis.set_zlim3d([centra[2] - radius, centra[2] + radius])
Example #13
Source File: complexity_delay.py From NeuroKit with MIT License | 4 votes |
def _embedding_delay_plot( signal, metric_values, tau_sequence, tau=1, metric="Mutual Information", ax0=None, ax1=None, plot="2D" ): # Prepare figure if ax0 is None and ax1 is None: fig = plt.figure(constrained_layout=False) spec = matplotlib.gridspec.GridSpec(ncols=1, nrows=2, height_ratios=[1, 3], width_ratios=[2]) ax0 = fig.add_subplot(spec[0]) if plot == "2D": ax1 = fig.add_subplot(spec[1]) elif plot == "3D": ax1 = fig.add_subplot(spec[1], projection="3d") else: fig = None ax0.set_title("Optimization of Delay (tau)") ax0.set_xlabel("Time Delay (tau)") ax0.set_ylabel(metric) ax0.plot(tau_sequence, metric_values, color="#FFC107") ax0.axvline(x=tau, color="#E91E63", label="Optimal delay: " + str(tau)) ax0.legend(loc="upper right") ax1.set_title("Attractor") ax1.set_xlabel("Signal [i]") ax1.set_ylabel("Signal [i-" + str(tau) + "]") # Get data points, set axis limits embedded = complexity_embedding(signal, delay=tau, dimension=3) x = embedded[:, 0] y = embedded[:, 1] z = embedded[:, 2] ax1.set_xlim(x.min(), x.max()) ax1.set_ylim(x.min(), x.max()) # Colors norm = plt.Normalize(z.min(), z.max()) cmap = plt.get_cmap("plasma") colors = cmap(norm(x)) # Attractor for 2D vs 3D if plot == "2D": points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = matplotlib.collections.LineCollection(segments, cmap="plasma", norm=norm) lc.set_array(z) ax1.add_collection(lc) elif plot == "3D": points = np.array([x, y, z]).T.reshape(-1, 1, 3) segments = np.concatenate([points[:-1], points[1:]], axis=1) for i in range(len(x) - 1): seg = segments[i] (l,) = ax1.plot(seg[:, 0], seg[:, 1], seg[:, 2], color=colors[i]) l.set_solid_capstyle("round") ax1.set_zlabel("Signal [i-" + str(2 * tau) + "]") return fig
Example #14
Source File: animation.py From YAFS with MIT License | 4 votes |
def update_coverage_regions(self): point_mobiles = [] for ix,code_mobile in enumerate(self.sim.mobile_fog_entities.keys()): if code_mobile in self.track_code_last_position.keys(): (lng, lat) = self.track_code_last_position[code_mobile] point_mobiles.append(np.array([lng, lat])) point_mobiles = np.array(point_mobiles) if len(point_mobiles)==0: self.pointsVOR = self.sim.endpoints else: self.pointsVOR = np.concatenate((self.sim.endpoints, point_mobiles), axis=0) self.sim.coverage.update_coverage_of_endpoints(self.sim.map, self.pointsVOR) self.axarr.clear() plt.xticks([]) plt.yticks([]) plt.grid(False) plt.xlim(0, self.sim.map.w) plt.ylim(self.sim.map.h, 0) plt.axis('off') plt.tight_layout() self.axarr.imshow(self.sim.map.img) # self.axarr.add_collection( # mpl.collections.PolyCollection( # self.sim.coverage.cells, facecolors=self.sim.coverage.colors_cells, # edgecolors='k', alpha=.25)) # p = PatchCollection(self.sim.coverage.get_polygon_to_map(),facecolors=self.sim.coverage.get_polygon_colors(),alpha=.25) # p.set_array(self.sim.coverage.colors_cells) self.axarr.add_collection(self.sim.coverage.get_polygons_on_map()) # self.ppix = [self.sim.map.to_pixels(vp[0], vp[1]) for vp in self.pointsVOR] # self.ppix = np.array(self.ppix) # for point in self.ppix: # ab = AnnotationBbox(self.car_icon, (point[0], point[1]),frameon=False) # self.axarr.add_artist(ab) # Endpoints of the network self.ppix = [self.sim.map.to_pixels(vp[0], vp[1]) for vp in self.sim.endpoints] for point in self.ppix: ab = AnnotationBbox(self.endpoint_icon, (point[0], point[1]), frameon=False) self.axarr.add_artist(ab) # self.axarr.scatter(self.ppix[:, 0], self.ppix[:, 1])
Example #15
Source File: procar.py From PyChemia with MIT License | 4 votes |
def parametricPlot(self, cmap='hot_r', vmin=None, vmax=None, mask=None, ticks=None): from matplotlib.collections import LineCollection import matplotlib fig = plt.figure() gca = fig.gca() bsize, ksize = self.bands.shape # print self.bands if mask is not None: mbands = np.ma.masked_array(self.bands, np.abs(self.spd) < mask) else: # Faking a mask, all elemtnet are included mbands = np.ma.masked_array(self.bands, False) # print mbands if vmin is None: vmin = self.spd.min() if vmax is None: vmax = self.spd.max() print("normalizing to: ", (vmin, vmax)) norm = matplotlib.colors.Normalize(vmin, vmax) if self.kpoints is not None: xaxis = [0] for i in range(1, len(self.kpoints)): d = self.kpoints[i - 1] - self.kpoints[i] d = np.sqrt(np.dot(d, d)) xaxis.append(d + xaxis[-1]) xaxis = np.array(xaxis) else: xaxis = np.arange(ksize) for y, z in zip(mbands, self.spd): # print xaxis.shape, y.shape, z.shape points = np.array([xaxis, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=plt.get_cmap(cmap), norm=norm, alpha=0.8) lc.set_array(z) lc.set_linewidth(2) gca.add_collection(lc) plt.colorbar(lc) plt.xlim(xaxis.min(), xaxis.max()) plt.ylim(mbands.min(), mbands.max()) # handling ticks if ticks: ticks, ticksNames = zip(*ticks) ticks = [xaxis[x] for x in ticks] plt.xticks(ticks, ticksNames) return fig