当前位置: 首页>>代码示例>>Python>>正文


Python matplotlib.collections方法代码示例

本文整理汇总了Python中matplotlib.collections方法的典型用法代码示例。如果您正苦于以下问题:Python matplotlib.collections方法的具体用法?Python matplotlib.collections怎么用?Python matplotlib.collections使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib的用法示例。


在下文中一共展示了matplotlib.collections方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _set_ylim

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import collections [as 别名]
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) 
开发者ID:0todd0000,项目名称:spm1d,代码行数:24,代码来源:_plot.py

示例2: on_key

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import collections [as 别名]
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() 
开发者ID:noahbenson,项目名称:neuropythy,代码行数:15,代码来源:core.py

示例3: DrawContourAndMark

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import collections [as 别名]
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() 
开发者ID:flashlxy,项目名称:PyMICAPS,代码行数:39,代码来源:Map.py

示例4: _contour

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import collections [as 别名]
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 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:32,代码来源:parasite_axes.py

示例5: _get_handles

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import collections [as 别名]
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 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:13,代码来源:parasite_axes.py

示例6: plot_selected_energy_range

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import collections [as 别名]
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) 
开发者ID:NSLS-II,项目名称:PyXRF,代码行数:37,代码来源:lineplot.py

示例7: vertex

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import collections [as 别名]
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 
开发者ID:pmelchior,项目名称:skymapper,代码行数:41,代码来源:map.py

示例8: footprint

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import collections [as 别名]
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) 
开发者ID:pmelchior,项目名称:skymapper,代码行数:16,代码来源:map.py

示例9: _update_axis_2d

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import collections [as 别名]
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) 
开发者ID:meco-group,项目名称:omg-tools,代码行数:13,代码来源:plotlayer.py

示例10: _update_axis_3d

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import collections [as 别名]
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]) 
开发者ID:meco-group,项目名称:omg-tools,代码行数:36,代码来源:plotlayer.py

示例11: _embedding_delay_plot

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import collections [as 别名]
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 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:59,代码来源:complexity_delay.py

示例12: update_coverage_regions

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import collections [as 别名]
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]) 
开发者ID:acsicuib,项目名称:YAFS,代码行数:54,代码来源:animation.py

示例13: parametricPlot

# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import collections [as 别名]
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 
开发者ID:MaterialsDiscovery,项目名称:PyChemia,代码行数:56,代码来源:procar.py


注:本文中的matplotlib.collections方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。