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


Python LineCollection.set_cmap方法代码示例

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


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

示例1: __plot_all

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]
    def __plot_all(self):
        total = len(self.data)
        count = 0.0
        for timeStamp in self.data:
            if len(self.data[timeStamp]) < 2:
                self.parent.threadPlot = None
                return None, None

            if self.fade:
                alpha = (total - count) / total
            else:
                alpha = 1

            data = self.data[timeStamp].items()
            peakF, peakL = self.extent.get_peak_fl()

            segments, levels = self.__create_segments(data)
            lc = LineCollection(segments)
            lc.set_array(numpy.array(levels))
            lc.set_norm(self.__get_norm(self.autoL, self.extent))
            lc.set_cmap(self.colourMap)
            lc.set_linewidth(self.lineWidth)
            lc.set_gid('plot')
            lc.set_alpha(alpha)
            self.axes.add_collection(lc)
            count += 1

        return peakF, peakL
开发者ID:thatchristoph,项目名称:RTLSDR-Scanner,代码行数:30,代码来源:plot_line.py

示例2: draw_edges

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]
def draw_edges(tree, steiner_pos, diams=None, fig=None, ax=None, lim=None,
               colorbar=True):
    '''Draw edges with given positions.'''
    if fig is None:
        fig, ax = new_fig()
    if lim is None:
        lim = diam_min, diam_max

    pos = merge_pos(tree, steiner_pos)
    nodes = tree.get_nodes()
    arcs = tree.get_arcs()
    x = np.array([pos[n][0] for n in nodes])
    y = np.array([pos[n][1] for n in nodes])

    segments = [(pos[u], pos[v]) for (u,v) in arcs]

    if diams is None:
        lines = LineCollection(segments, colors='k', zorder=1)
    else:
        diams = np.array([diams[a] for a in arcs])
        lw = 7*diams + 1
        lines = LineCollection(segments, linewidths=lw, zorder=1)
        # set colors
        lines.set_array(diams)
        lines.set_cmap(_diam_cmap)
        lines.set_clim(*lim)
        if colorbar:
            plt.colorbar(lines, orientation='horizontal')
    ax.add_collection(lines)
开发者ID:hshlabs,项目名称:geonet,代码行数:31,代码来源:visual.py

示例3: __plot_all

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]
    def __plot_all(self, spectrum):
        total = len(spectrum)
        count = 0.0
        for timeStamp in spectrum:
            if self.settings.fadeScans:
                alpha = (total - count) / total
            else:
                alpha = 1

            data = spectrum[timeStamp].items()
            peakF, peakL = self.extent.get_peak_fl()

            segments, levels = self.__create_segments(data)
            if segments is not None:
                lc = LineCollection(segments)
                lc.set_array(numpy.array(levels))
                lc.set_norm(self.__get_norm(self.settings.autoL, self.extent))
                lc.set_cmap(self.colourMap)
                lc.set_linewidth(self.lineWidth)
                lc.set_gid('plot')
                lc.set_alpha(alpha)
                self.axes.add_collection(lc)
                count += 1

        return peakF, peakL
开发者ID:har5ha,项目名称:RTLSDR-Scanner,代码行数:27,代码来源:plot_line.py

示例4: plot_linestring_collection

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]
def plot_linestring_collection(ax, geoms, values=None, color=None,
                               cmap=None, vmin=None, vmax=None, **kwargs):
    """
    Plots a collection of LineString and MultiLineString geometries to `ax`

    Parameters
    ----------

    ax : matplotlib.axes.Axes
        where shapes will be plotted

    geoms : a sequence of `N` LineStrings and/or MultiLineStrings (can be
            mixed)

    values : a sequence of `N` values, optional
        Values will be mapped to colors using vmin/vmax/cmap. They should
        have 1:1 correspondence with the geometries (not their components).

    color : single color or sequence of `N` colors
        Cannot be used together with `values`.

    Returns
    -------

    collection : matplotlib.collections.Collection that was plotted

    """
    from matplotlib.collections import LineCollection

    geoms, values = _flatten_multi_geoms(geoms, values)
    if None in values:
        values = None

    # LineCollection does not accept some kwargs.
    if 'markersize' in kwargs:
        del kwargs['markersize']

    # color=None gives black instead of default color cycle
    if color is not None:
        kwargs['color'] = color

    segments = [np.array(linestring)[:, :2] for linestring in geoms]
    collection = LineCollection(segments, **kwargs)

    if values is not None:
        collection.set_array(np.asarray(values))
        collection.set_cmap(cmap)
        collection.set_clim(vmin, vmax)

    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    return collection
开发者ID:micahcochran,项目名称:geopandas,代码行数:54,代码来源:plotting.py

示例5: __plot_single

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]
    def __plot_single(self, points):
        data = points.items()
        peakF, peakL = max(data, key=lambda item: item[1])

        segments, levels = self.__create_segments(data)
        lc = LineCollection(segments)
        lc.set_array(numpy.array(levels))
        lc.set_norm(self.__get_norm(self.autoL, self.extent))
        lc.set_cmap(self.colourMap)
        lc.set_linewidth(self.lineWidth)
        lc.set_gid('plot')
        self.axes.add_collection(lc)

        return peakF, peakL
开发者ID:thatchristoph,项目名称:RTLSDR-Scanner,代码行数:16,代码来源:plot_line.py

示例6: LineCollection

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]
for p in ps:
	gm = cmpy.machines.BiasedCoin(bias = p)
	data = gm.cmech_quantities(['HX0L', 'hmu'], maxL)
	lines1.append(zip(range(maxL+1),data[0]))
	data[1].mask[0] = False
	lines2.append(zip(range(maxL+1),data[1,:]))

fig = plt.figure()
fig.set_figheight(5)
fig.set_figwidth(10)
fig.subplots_adjust(left = 0.09, right = 0.86)
ax1 = fig.add_subplot(1,2,1)

lc1 = LineCollection(lines1)
lc1.set_array(ps)
lc1.set_cmap(plt.cm.jet)

ax1.add_collection(lc1)

ax1.set_xlabel("$L$ [symbols]")
ax1.set_ylabel("$H[X_0^L]$ [bits]")
ax1.axis('auto')
ax1.set_xlim((0,maxL))

ax2 = fig.add_subplot(1,2,2)

lc2 = LineCollection(lines2)
lc2.set_array(ps)
lc2.set_cmap(plt.cm.jet)

ax2.add_collection(lc2)
开发者ID:ekfriis,项目名称:thesis,代码行数:33,代码来源:BE_IID_all.py

示例7: plot

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]

#.........这里部分代码省略.........
        return tuple(xy1), tuple(xy2)

    x = network.buses["x"]
    y = network.buses["y"]

    if basemap and basemap_present:
        if boundaries is None:
            (x1, y1), (x2, y2) = compute_bbox_with_margins(margin, x, y)
        else:
            x1, x2, y1, y2 = boundaries
        bmap = Basemap(resolution='l', epsg=network.srid,
                       llcrnrlat=y1, urcrnrlat=y2, llcrnrlon=x1,
                       urcrnrlon=x2, ax=ax)
        bmap.drawcountries()
        bmap.drawcoastlines()

        x, y = bmap(x.values, y.values)
        x = pd.Series(x, network.buses.index)
        y = pd.Series(y, network.buses.index)

    c = pd.Series(bus_colors, index=network.buses.index)
    if c.dtype == np.dtype('O'):
        c.fillna("b", inplace=True)
    s = pd.Series(bus_sizes, index=network.buses.index, dtype="float").fillna(10)
    bus_collection = ax.scatter(x, y, c=c, s=s, cmap=bus_cmap)

    def as_branch_series(ser):
        if isinstance(ser, pd.Series):
            if isinstance(ser.index, pd.MultiIndex):
                return ser
            index = ser.index
            ser = ser.values
        else:
            index = network.lines.index
        return pd.Series(ser,
                         index=pd.MultiIndex(levels=(["Line"], index),
                                             labels=(np.zeros(len(index)),
                                                     np.arange(len(index)))))

    line_colors = as_branch_series(line_colors)
    line_widths = as_branch_series(line_widths)
    if not isinstance(line_cmap, dict):
        line_cmap = {'Line': line_cmap}

    branch_collections = []
    for t in network.iterate_components(branch_types):
        l_defaults = defaults_for_branches[t.name]
        l_widths = line_widths.get(t.name, l_defaults['width'])
        l_nums = None
        if t.name in line_colors:
            l_colors = line_colors[t.name]

            if issubclass(l_colors.dtype.type, np.number):
                l_nums = l_colors
                l_colors = None
            else:
                l_colors.fillna(l_defaults['color'], inplace=True)
        else:
            l_colors = l_defaults['color']

        if not geometry:
            segments = (np.asarray(((t.df.bus0.map(x),
                                     t.df.bus0.map(y)),
                                    (t.df.bus1.map(x),
                                     t.df.bus1.map(y))))
                        .transpose(2, 0, 1))
        else:
            from shapely.wkt import loads
            from shapely.geometry import LineString
            linestrings = t.df.geometry.map(loads)
            assert all(isinstance(ls, LineString) for ls in linestrings), \
                "The WKT-encoded geometry in the 'geometry' column must be composed of LineStrings"
            segments = np.asarray(list(linestrings.map(np.asarray)))
            if basemap and basemap_present:
                segments = np.transpose(bmap(*np.transpose(segments, (2, 0, 1))), (1, 2, 0))

        l_collection = LineCollection(segments,
                                      linewidths=l_widths,
                                      antialiaseds=(1,),
                                      colors=l_colors,
                                      transOffset=ax.transData)

        if l_nums is not None:
            l_collection.set_array(np.asarray(l_nums))
            l_collection.set_cmap(line_cmap.get(t.name, None))
            l_collection.autoscale()

        ax.add_collection(l_collection)
        l_collection.set_zorder(1)

        branch_collections.append(l_collection)

    bus_collection.set_zorder(2)

    ax.update_datalim(compute_bbox_with_margins(margin, x, y))
    ax.autoscale_view()

    ax.set_title(title)

    return (bus_collection,) + tuple(branch_collections)
开发者ID:cuihantao,项目名称:PyPSA,代码行数:104,代码来源:plot.py

示例8: plot

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]
    def plot(self, time, beam=None, 
        maxground=2000, maxalt=500, step=1,
        showrefract=False, nr_cmap='jet_r', nr_lim=[0.8, 1.], 
        raycolor='0.3', title=False, zorder=2, alpha=1, 
        fig=None, rect=111, ax=None, aax=None):
        """Plot ray paths
        
        **Args**: 
            * **time** (datetime.datetime): time of rays
            * [**beam**]: beam number
            * [**maxground**]: maximum ground range [km]
            * [**maxalt**]: highest altitude limit [km]
            * [**step**]: step between each plotted ray (in number of ray steps)
            * [**showrefract**]: show refractive index along ray paths (supersedes raycolor)
            * [**nr_cmap**]: color map name for refractive index coloring
            * [**nr_lim**]: refractive index plotting limits
            * [**raycolor**]: color of ray paths
            * [**rect**]: subplot spcification
            * [**fig**]: A pylab.figure object (default to gcf)
            * [**title**]: Show default title
            * [**ax**]: Existing main axes
            * [**aax**]: Existing auxialary axes
        **Returns**:
            * **ax**: matplotlib.axes object containing formatting
            * **aax**: matplotlib.axes object containing data
            * **cbax**: matplotlib.axes object containing colorbar
        **Example**:
            ::

                # Show ray paths with colored refractive index along path
                import datetime as dt
                from models import raydarn
                sTime = dt.datetime(2012, 11, 18, 5)
                rto = raydarn.RtRun(sTime, rCode='bks', beam=12, title=True)
                rto.readRays() # read rays into memory
                ax, aax, cbax = rto.rays.plot(sTime, step=10, showrefract=True, nr_lim=[.85,1])
                ax.grid()
                
        written by Sebastien, 2013-04
        """
        from utils import plotUtils
        from matplotlib.collections import LineCollection
        import matplotlib.pyplot as plt
        import numpy as np
        from types import MethodType

        # Set up axes
        if not ax and not aax:
            ax, aax = plotUtils.curvedEarthAxes(fig=fig, rect=rect, 
                maxground=maxground, maxalt=maxalt)
        else:
            ax = ax
            aax = aax
            if hasattr(ax, 'time'):
                time = ax.time
            if hasattr(ax, 'beam'):
                beam = ax.beam

        # make sure that the required time and beam are present
        assert (time in self.paths.keys()), 'Unkown time %s' % time
        if beam:
            assert (beam in self.paths[time].keys()), 'Unkown beam %s' % beam
        else:
            beam = self.paths[time].keys()[0]
        
        for ir, (el, rays) in enumerate( sorted(self.paths[time][beam].items()) ):
            if not ir % step:
                if not showrefract:
                    aax.plot(rays['th'], rays['r']*1e-3, c=raycolor, 
                        zorder=zorder, alpha=alpha)
                else:
                    points = np.array([rays['th'], rays['r']*1e-3]).T.reshape(-1, 1, 2)
                    segments = np.concatenate([points[:-1], points[1:]], axis=1)
                    lcol = LineCollection( segments, zorder=zorder, alpha=alpha)
                    _ = lcol.set_cmap( nr_cmap )
                    _ = lcol.set_norm( plt.Normalize(*nr_lim) )
                    _ = lcol.set_array( rays['nr'] )
                    _ = aax.add_collection( lcol )

        # Plot title with date ut time and local time
        if title:
            stitle = _getTitle(time, beam, self.header, self.name)
            ax.set_title( stitle )

        # Add a colorbar when plotting refractive index
        if showrefract:
            cbax = plotUtils.addColorbar(lcol, ax)
            _ = cbax.set_ylabel("refractive index")
        else: cbax = None

        # Declare a new method to show range markers
        # This method is only available after rays have been plotted
        # This ensures that the markers match the plotted rays
        def showRange(self, markers=None, 
            color='.8', s=2, zorder=3, 
            **kwargs):
            """Plot ray paths
            
            **Args**: 
                * [**markers**]: range markers. Defaults to every 250 km
#.........这里部分代码省略.........
开发者ID:DeepHorizons,项目名称:davitpy,代码行数:103,代码来源:rt.py

示例9: draw_networkx_edges

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]

#.........这里部分代码省略.........
                edge_colors = tuple(edge_color)
            else:
                # numbers (which are going to be mapped with a colormap)
                edge_colors = None
        else:
            raise ValueError('edge_color must consist of either color names or numbers')
    else:
        if cb.is_string_like(edge_color) or len(edge_color) == 1:
            edge_colors = (colorConverter.to_rgba(edge_color, alpha), )
        else:
            raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges')

    edge_collection = LineCollection(edge_pos,
                                     colors=edge_colors,
                                     linewidths=lw,
                                     antialiaseds=(1,),
                                     linestyle=style,
                                     transOffset = ax.transData,
                                     )

    edge_collection.set_zorder(1)  # edges go behind nodes
    edge_collection.set_label(label)
    ax.add_collection(edge_collection)

    # Note: there was a bug in mpl regarding the handling of alpha values for
    # each line in a LineCollection.  It was fixed in matplotlib in r7184 and
    # r7189 (June 6 2009).  We should then not set the alpha value globally,
    # since the user can instead provide per-edge alphas now.  Only set it
    # globally if provided as a scalar.
    if cb.is_numlike(alpha):
        edge_collection.set_alpha(alpha)

    if edge_colors is None:
        if edge_cmap is not None:
            assert(isinstance(edge_cmap, Colormap))
        edge_collection.set_array(numpy.asarray(edge_color))
        edge_collection.set_cmap(edge_cmap)
        if edge_vmin is not None or edge_vmax is not None:
            edge_collection.set_clim(edge_vmin, edge_vmax)
        else:
            edge_collection.autoscale()

    arrow_collection = None

    if G.is_directed() and arrows:

        # a directed graph hack
        # draw thick line segments at head end of edge
        # waiting for someone else to implement arrows that will work
        arrow_colors = edge_colors
        a_pos = []
        p = 1.0-0.25  # make head segment 25 percent of edge length
        for src, dst in edge_pos:
            x1, y1 = src
            x2, y2 = dst
            dx = x2-x1   # x offset
            dy = y2-y1   # y offset
            d = numpy.sqrt(float(dx**2 + dy**2))  # length of edge
            if d == 0:   # source and target at same position
                continue
            if dx == 0:  # vertical edge
                xa = x2
                ya = dy*p+y1
            if dy == 0:  # horizontal edge
                ya = y2
                xa = dx*p+x1
            else:
                theta = numpy.arctan2(dy, dx)
                xa = p*d*numpy.cos(theta)+x1
                ya = p*d*numpy.sin(theta)+y1

            a_pos.append(((xa, ya), (x2, y2)))

        arrow_collection = LineCollection(a_pos,
                                colors=arrow_colors,
                                linewidths=[4*ww for ww in lw],
                                antialiaseds=(1,),
                                transOffset = ax.transData,
                                )

        arrow_collection.set_zorder(1)  # edges go behind nodes
        arrow_collection.set_label(label)
        ax.add_collection(arrow_collection)

    # update view
    minx = numpy.amin(numpy.ravel(edge_pos[:, :, 0]))
    maxx = numpy.amax(numpy.ravel(edge_pos[:, :, 0]))
    miny = numpy.amin(numpy.ravel(edge_pos[:, :, 1]))
    maxy = numpy.amax(numpy.ravel(edge_pos[:, :, 1]))

    w = maxx-minx
    h = maxy-miny
    padx,  pady = 0.05*w, 0.05*h
    corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady)
    ax.update_datalim(corners)
    ax.autoscale_view()

#    if arrow_collection:

    return edge_collection
开发者ID:chrisnatali,项目名称:networkx,代码行数:104,代码来源:nx_pylab.py

示例10: plot

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]

#.........这里部分代码省略.........
            ax, aax = plotUtils.curvedEarthAxes(fig=fig, rect=rect, 
                maxground=maxground, maxalt=maxalt)
        else:
            ax = ax
            aax = aax
            if hasattr(ax, 'time'):
                time = ax.time
            if hasattr(ax, 'beam'):
                beam = ax.beam

        # make sure that the required time and beam are present
        # Allow a 60 second difference between the requested time and the time
        # available.
        keys    = np.array(self.paths.keys())
        diffs   = np.abs(keys-time)
        if diffs.min() < dt.timedelta(minutes=1):
            time = keys[diffs.argmin()]

        assert (time in self.paths.keys()), logging.error('Unkown time %s' % time)
        if beam:
            assert (beam in self.paths[time].keys()), logging.error('Unkown beam %s' % beam)
        else:
            beam = self.paths[time].keys()[0]
        
        for ir, (el, rays) in enumerate( sorted(self.paths[time][beam].items()) ):
            if not ir % step:
                if not showrefract:
                    aax.plot(rays['th'], rays['r']*1e-3, c=raycolor, 
                        zorder=zorder, alpha=alpha)
                else:
                    points = np.array([rays['th'], rays['r']*1e-3]).T.reshape(-1, 1, 2)
                    segments = np.concatenate([points[:-1], points[1:]], axis=1)
                    lcol = LineCollection( segments, zorder=zorder, alpha=alpha)
                    _ = lcol.set_cmap( nr_cmap )
                    _ = lcol.set_norm( plt.Normalize(*nr_lim) )
                    _ = lcol.set_array( rays['nr'] )
                    _ = aax.add_collection( lcol )

        # Plot title with date ut time and local time
        if title:
            stitle = _getTitle(time, beam, self.header, self.name)
            ax.set_title( stitle )

        # Add a colorbar when plotting refractive index
        if showrefract:
            cbax = plotUtils.addColorbar(lcol, ax)
            _ = cbax.set_ylabel("refractive index")
        else: cbax = None

        # Declare a new method to show range markers
        # This method is only available after rays have been plotted
        # This ensures that the markers match the plotted rays
        def showRange(self, markers=None, 
            color='.8', s=2, zorder=3, 
            **kwargs):
            """Plot ray paths
            
            Parameters
            ----------
            markers : Optional[ ]
                range markers. Defaults to every 250 km
            color : Optional[float]

            s : Optional[int]

            zorder : Optional[int]
开发者ID:KM4ICI-Harry,项目名称:davitpy,代码行数:70,代码来源:rt.py

示例11: plot

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]
    def plot(self, time, beam=None, maxground=2000, maxalt=500, step=1,
        showrefract=False, nr_cmap='jet_r', nr_lim=[0.8, 1.], 
        raycolor='0.4',  
        fig=None, rect=111):
        """Plot ray paths
        
        **Args**: 
            * **time** (datetime.datetime): time of rays
            * [**beam**]: beam number
            * [**maxground**]: maximum ground range [km]
            * [**maxalt**]: highest altitude limit [km]
            * [**step**]: step between each plotted ray (in number of ray steps)
            * [**showrefract**]: show refractive index along ray paths (supersedes raycolor)
            * [**nr_cmap**]: color map name for refractive index coloring
            * [**nr_lim**]: refractive index plotting limits
            * [**raycolor**]: color of ray paths
            * [**rect**]: subplot spcification
            * [**fig**]: A pylab.figure object (default to gcf)
        **Returns**:
            * **ax**: matplotlib.axes object containing formatting
            * **aax**: matplotlib.axes object containing data
            * **cbax**: matplotlib.axes object containing colorbar
        **Example**:
            ::

                # Show ray paths with colored refractive index along path
                import datetime as dt
                from models import raydarn
                sTime = dt.datetime(2012, 11, 18, 5)
                rto = raydarn.rtRun(sTime, rCode='bks', beam=12)
                rto.readRays() # read rays into memory
                ax, aax, cbax = rto.rays.plot(sTime, step=2, showrefract=True, nr_lim=[.85,1])
                ax.grid()
                
        written by Sebastien, 2013-04
        """
        from utils import plotUtils
        from mpl_toolkits.axes_grid1 import make_axes_locatable
        from matplotlib.collections import LineCollection
        import matplotlib.pyplot as plt
        import numpy as np

        ax, aax = plotUtils.curvedEarthAxes(fig=fig, rect=rect, 
            maxground=maxground, maxalt=maxalt)

        # make sure that the required time and beam are present
        assert (time in self.paths.keys()), 'Unkown time %s' % time
        if beam:
            assert (beam in self.paths[time].keys()), 'Unkown beam %s' % beam
        else:
            beam = self.paths[time].keys()[0]
        
        for ir, (el, rays) in enumerate( sorted(self.paths[time][beam].items()) ):
            if not ir % step:
                if not showrefract:
                    aax.plot(rays['th'], rays['r']*1e-3, c=raycolor, zorder=2)
                else:
                    points = np.array([rays['th'], rays['r']*1e-3]).T.reshape(-1, 1, 2)
                    segments = np.concatenate([points[:-1], points[1:]], axis=1)
                    lcol = LineCollection( segments )
                    lcol.set_cmap( nr_cmap )
                    lcol.set_norm( plt.Normalize(*nr_lim) )
                    lcol.set_array( rays['nr'] )
                    aax.add_collection( lcol )
        # Add a colorbar when plotting refractive index
        if showrefract:
            from mpl_toolkits.axes_grid1 import SubplotDivider, LocatableAxes, Size

            fig1 = ax.get_figure()
            divider = SubplotDivider(fig1, *ax.get_geometry(), aspect=True)

            # axes for colorbar
            cbax = LocatableAxes(fig1, divider.get_position())

            h = [Size.AxesX(ax), # main axes
                 Size.Fixed(0.1), # padding
                 Size.Fixed(0.2)] # colorbar
            v = [Size.AxesY(ax)]

            divider.set_horizontal(h)
            divider.set_vertical(v)

            ax.set_axes_locator(divider.new_locator(nx=0, ny=0))
            cbax.set_axes_locator(divider.new_locator(nx=2, ny=0))

            fig1.add_axes(cbax)

            cbax.axis["left"].toggle(all=False)
            cbax.axis["top"].toggle(all=False)
            cbax.axis["bottom"].toggle(all=False)
            cbax.axis["right"].toggle(ticklabels=True, label=True)

            plt.colorbar(lcol, cax=cbax)
            cbax.set_ylabel("refractive index")

        return ax, aax, cbax
开发者ID:alexmorrisak,项目名称:davitpy,代码行数:98,代码来源:rt.py

示例12: draw_networkx_edges

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]
def draw_networkx_edges(G, pos,
                        edgelist=None,
                        width=1.0,
                        edge_color='k',
                        style='solid',
                        alpha=1.0,
                        edge_cmap=None,
                        edge_vmin=None,
                        edge_vmax=None, 
                        ax=None,
                        arrows=True,
                        **kwds):
    """Draw the edges of the graph G

    This draws only the edges of the graph G.

    pos is a dictionary keyed by vertex with a two-tuple
    of x-y positions as the value.
    See networkx_v099.layout for functions that compute node positions.

    edgelist is an optional list of the edges in G to be drawn.
    If provided, only the edges in edgelist will be drawn. 

    edgecolor can be a list of matplotlib color letters such as 'k' or
    'b' that lists the color of each edge; the list must be ordered in
    the same way as the edge list. Alternatively, this list can contain
    numbers and those number are mapped to a color scale using the color
    map edge_cmap.
    
    For directed graphs, "arrows" (actually just thicker stubs) are drawn
    at the head end.  Arrows can be turned off with keyword arrows=False.

    See draw_networkx_v099 for the list of other optional parameters.

    """
    if ax is None:
        ax=matplotlib.pylab.gca()

    if edgelist is None:
        edgelist=G.edges()

    if not edgelist or len(edgelist)==0: # no edges!
        return None

    # set edge positions
    edge_pos=asarray([(pos[e[0]],pos[e[1]]) for e in edgelist])

    if not cb.iterable(width):
        lw = (width,)
    else:
        lw = width

    if not cb.is_string_like(edge_color) \
           and cb.iterable(edge_color) \
           and len(edge_color)==len(edge_pos):
        if matplotlib.numerix.alltrue([cb.is_string_like(c) 
                                       for c in edge_color]):
            # (should check ALL elements)
            # list of color letters such as ['k','r','k',...]
            edge_colors = tuple([colorConverter.to_rgba(c,alpha) 
                                 for c in edge_color])
        elif matplotlib.numerix.alltrue([not cb.is_string_like(c) 
                                         for c in edge_color]):
            # numbers (which are going to be mapped with a colormap)
            edge_colors = None
        else:
            raise ValueError('edge_color must consist of either color names or numbers')
    else:
        if len(edge_color)==1:
            edge_colors = ( colorConverter.to_rgba(edge_color, alpha), )
        else:
            raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges')

    edge_collection = LineCollection(edge_pos,
                                colors       = edge_colors,
                                linewidths   = lw,
                                antialiaseds = (1,),
                                linestyle    = style,     
                                transOffset = ax.transData,             
                                )
    edge_collection.set_alpha(alpha)

    # need 0.87.7 or greater for edge colormaps
    mpl_version=matplotlib.__version__
    if mpl_version.endswith('svn'):
        mpl_version=matplotlib.__version__[0:-3]
    if mpl_version.endswith('pre'):
        mpl_version=matplotlib.__version__[0:-3]
    if map(int,mpl_version.split('.'))>=[0,87,7]:
        if edge_colors is None:
            if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap))
            edge_collection.set_array(asarray(edge_color))
            edge_collection.set_cmap(edge_cmap)
            if edge_vmin is not None or edge_vmax is not None:
                edge_collection.set_clim(edge_vmin, edge_vmax)
            else:
                edge_collection.autoscale()
            matplotlib.pylab.sci(edge_collection)

#    else:
#.........这里部分代码省略.........
开发者ID:jbjorne,项目名称:CVSTransferTest,代码行数:103,代码来源:nx_pylab.py

示例13: SunPlotPy

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]

#.........这里部分代码省略.........
                self.PTM.plot(self.PTM.nt-1,ax=self.axes,fontcolor='w',\
                    color=self.particlecolor,markersize=self.particlesize)
            # redraw the figure
            self.canvas.draw()

        
    def on_show_edges(self,event):
        sender=event.GetEventObject()
        self.showedges = sender.GetValue()

        # Update the figure
        self.update_figure()

    def on_clim_check(self,event):
        sender=event.GetEventObject()
        if sender.GetValue() == True:
            self.autoclim=False
            self.update_figure()
        else:
            self.autoclim=True
       

    def on_climlow(self,event):
        self.clim[0] = event.GetString()
        #self.update_figure()

    def on_climhigh(self,event):
        self.clim[1] = event.GetString()
        #self.update_figure()

    def on_select_cmap(self,event):
        self.cmap=event.GetString()
        if USECMOCEAN:
            self.collection.set_cmap(getattr(cm,self.cmap))
        else:
            self.collection.set_cmap(self.cmap)

        # Update the figure
        self.update_figure()

    def on_save_fig(self,event):
        """
        Save a figure of the current scene to a file
        """
        file_choices = " (*.png)|*.png| (*.pdf)|*.pdf |(*.jpg)|*.jpg |(*.eps)|*eps "
        filters=['.png','.pdf','.png','.png']

        
        dlg = wx.FileDialog(
            self, 
            message="Save figure to file...",
            defaultDir=os.getcwd(),
            defaultFile="",
            wildcard=file_choices,
            style= wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)

        if dlg.ShowModal() == wx.ID_OK:

            path = dlg.GetPath()
            ext = filters[dlg.GetFilterIndex()]
            if ext in path:
                outfile=path
            else:
                outfile = path+ext

            self.fig.savefig(outfile)
开发者ID:mrayson,项目名称:soda,代码行数:70,代码来源:sunplotpy.py

示例14: run

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]
    def run(self):
        if self.data is None:
            self.parent.threadPlot = None
            return

        peakF = None
        peakL = None
        total = len(self.data)
        if total > 0:
            self.parent.clear_plots()
            lc = None
            if self.average:
                avg = OrderedDict()
                count = len(self.data)

                for timeStamp in self.data:

                    if len(self.data[timeStamp]) < 2:
                        return

                    for x, y in self.data[timeStamp].items():
                        if x in avg:
                            avg[x] = (avg[x] + y) / 2
                        else:
                            avg[x] = y

                data = avg.items()
                peakF, peakL = max(data, key=lambda item: item[1])

                segments, levels = self.create_segments(data)
                lc = LineCollection(segments)
                lc.set_array(numpy.array(levels))
                lc.set_norm(self.get_norm(self.autoL, self.extent))
                lc.set_cmap(self.colourMap)
                lc.set_linewidth(self.lineWidth)
                lc.set_gid('plot')
                self.axes.add_collection(lc)
                self.parent.lc = lc
            else:
                count = 0.0
                for timeStamp in self.data:

                    if len(self.data[timeStamp]) < 2:
                        self.parent.threadPlot = None
                        return

                    if self.fade:
                        alpha = (total - count) / total
                    else:
                        alpha = 1

                    data = self.data[timeStamp].items()
                    peakF, peakL = self.extent.get_peak_fl()

                    segments, levels = self.create_segments(data)
                    lc = LineCollection(segments)
                    lc.set_array(numpy.array(levels))
                    lc.set_norm(self.get_norm(self.autoL, self.extent))
                    lc.set_cmap(self.colourMap)
                    lc.set_linewidth(self.lineWidth)
                    lc.set_gid('plot')
                    lc.set_alpha(alpha)
                    self.axes.add_collection(lc)
                    count += 1

            if self.annotate:
                self.annotate_plot(peakF, peakL)

        if total > 0:
            self.parent.scale_plot()
            self.parent.redraw_plot()

        self.parent.threadPlot = None
开发者ID:vlslv,项目名称:RTLSDR-Scanner,代码行数:75,代码来源:plot.py

示例15: plot

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_cmap [as 别名]

#.........这里部分代码省略.........
            "in the second MultiIndex level of bus_sizes"

        bus_sizes = bus_sizes.sort_index(level=0, sort_remaining=False)

        patches = []
        for b_i in bus_sizes.index.levels[0]:
            s = bus_sizes.loc[b_i]
            radius = s.sum()**0.5
            ratios = s/s.sum()

            start = 0.25
            for i, ratio in ratios.iteritems():
                patches.append(Wedge((x.at[b_i], y.at[b_i]), radius,
                                     360*start, 360*(start+ratio),
                                     facecolor=bus_colors[i]))
                start += ratio
        bus_collection = PatchCollection(patches, match_original=True)
        ax.add_collection(bus_collection)
    else:
        c = pd.Series(bus_colors, index=network.buses.index)
        if c.dtype == np.dtype('O'):
            c.fillna("b", inplace=True)
            c = list(c.values)
        s = pd.Series(bus_sizes, index=network.buses.index, dtype="float").fillna(10)
        bus_collection = ax.scatter(x, y, c=c, s=s, cmap=bus_cmap)

    def as_branch_series(ser):
        if isinstance(ser, dict) and set(ser).issubset(branch_components):
            return pd.Series(ser)
        elif isinstance(ser, pd.Series):
            if isinstance(ser.index, pd.MultiIndex):
                return ser
            index = ser.index
            ser = ser.values
        else:
            index = network.lines.index
        return pd.Series(ser,
                         index=pd.MultiIndex(levels=(["Line"], index),
                                             labels=(np.zeros(len(index)),
                                                     np.arange(len(index)))))

    line_colors = as_branch_series(line_colors)
    line_widths = as_branch_series(line_widths)
    if not isinstance(line_cmap, dict):
        line_cmap = {'Line': line_cmap}

    branch_collections = []
    for c in network.iterate_components(branch_components):
        l_defaults = defaults_for_branches[c.name]
        l_widths = line_widths.get(c.name, l_defaults['width'])
        l_nums = None
        l_colors = line_colors.get(c.name, l_defaults['color'])

        if isinstance(l_colors, pd.Series):
            if issubclass(l_colors.dtype.type, np.number):
                l_nums = l_colors
                l_colors = None
            else:
                l_colors.fillna(l_defaults['color'], inplace=True)

        if not geometry:
            segments = (np.asarray(((c.df.bus0.map(x),
                                     c.df.bus0.map(y)),
                                    (c.df.bus1.map(x),
                                     c.df.bus1.map(y))))
                        .transpose(2, 0, 1))
        else:
            from shapely.wkt import loads
            from shapely.geometry import LineString
            linestrings = c.df.geometry.map(loads)
            assert all(isinstance(ls, LineString) for ls in linestrings), \
                "The WKT-encoded geometry in the 'geometry' column must be composed of LineStrings"
            segments = np.asarray(list(linestrings.map(np.asarray)))
            if basemap and basemap_present:
                segments = np.transpose(bmap(*np.transpose(segments, (2, 0, 1))), (1, 2, 0))

        l_collection = LineCollection(segments,
                                      linewidths=l_widths,
                                      antialiaseds=(1,),
                                      colors=l_colors,
                                      transOffset=ax.transData)

        if l_nums is not None:
            l_collection.set_array(np.asarray(l_nums))
            l_collection.set_cmap(line_cmap.get(c.name, None))
            l_collection.autoscale()

        ax.add_collection(l_collection)
        l_collection.set_zorder(1)

        branch_collections.append(l_collection)

    bus_collection.set_zorder(2)

    ax.update_datalim(compute_bbox_with_margins(margin, x, y))
    ax.autoscale_view()

    ax.set_title(title)

    return (bus_collection,) + tuple(branch_collections)
开发者ID:jdedecca,项目名称:PyPSA,代码行数:104,代码来源:plot.py


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