Python matplotlib.collections 模块,PolyCollection() 实例源码

我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用matplotlib.collections.PolyCollection()

项目:hylaa    作者:stanleybak    | 项目源码 | 文件源码
def add_aggregation_poly(self, poly_verts, mode_name):
        '''add a polygon that's an aggregation on the waiting list'''

        polys = self.aggregation_mode_to_polys.get(mode_name)

        if polys is None:
            _, edge_col = self.mode_colors.get_edge_face_colors(mode_name)
            edge_col = darker(edge_col)

            polys = collections.PolyCollection([], lw=4, animated=True,
                                               edgecolor=edge_col, facecolor='none')
            self.axes.add_collection(polys)
            self.aggregation_mode_to_polys[mode_name] = polys

        paths = polys.get_paths()

        codes = [Path.MOVETO] + [Path.LINETO] * (len(poly_verts) - 2) + [Path.CLOSEPOLY]
        paths.append(Path(poly_verts, codes))
项目:hylaa    作者:stanleybak    | 项目源码 | 文件源码
def add_waiting_list_poly(self, poly_verts, mode_name):
        '''add a polygon on the waiting list'''

        polys = self.waiting_list_mode_to_polys.get(mode_name)

        if polys is None:
            face_col, edge_col = self.mode_colors.get_edge_face_colors(mode_name)

            polys = collections.PolyCollection([], lw=2, animated=True, alpha=0.3,
                                               edgecolor=edge_col, facecolor=face_col)
            self.axes.add_collection(polys)
            self.waiting_list_mode_to_polys[mode_name] = polys

        paths = polys.get_paths()

        codes = [Path.MOVETO] + [Path.LINETO] * (len(poly_verts) - 2) + [Path.CLOSEPOLY]
        paths.append(Path(poly_verts, codes))
项目:plotnine    作者:has2k1    | 项目源码 | 文件源码
def add_segmented_colorbar(da, colors, direction):
    """
    Add 'non-rastered' colorbar to DrawingArea
    """
    nbreak = len(colors)
    if direction == 'vertical':
        linewidth = da.height/nbreak
        verts = [None] * nbreak
        x1, x2 = 0, da.width
        for i, color in enumerate(colors):
            y1 = i * linewidth
            y2 = y1 + linewidth
            verts[i] = ((x1, y1), (x1, y2), (x2, y2), (x2, y1))
    else:
        linewidth = da.width/nbreak
        verts = [None] * nbreak
        y1, y2 = 0, da.height
        for i, color in enumerate(colors):
            x1 = i * linewidth
            x2 = x1 + linewidth
            verts[i] = ((x1, y1), (x1, y2), (x2, y2), (x2, y1))

    coll = mcoll.PolyCollection(verts,
                                facecolors=colors,
                                linewidth=0,
                                antialiased=False)
    da.add_artist(coll)
项目:plotnine    作者:has2k1    | 项目源码 | 文件源码
def draw_group(data, panel_params, coord, ax, **params):
        data = coord.transform(data, panel_params, munch=True)
        data['size'] *= SIZE_FACTOR
        verts = [None] * len(data)
        limits = zip(data['xmin'], data['xmax'],
                     data['ymin'], data['ymax'])

        for i, (l, r, b, t) in enumerate(limits):
            verts[i] = [(l, b), (l, t), (r, t), (r, b)]

        fill = to_rgba(data['fill'], data['alpha'])
        color = data['color']

        # prevent unnecessary borders
        if all(color.isnull()):
            color = 'none'

        col = PolyCollection(
            verts,
            facecolors=fill,
            edgecolors=color,
            linestyles=data['linetype'],
            linewidths=data['size'],
            transOffset=ax.transData,
            zorder=params['zorder'])
        ax.add_collection(col)
项目:plotnine    作者:has2k1    | 项目源码 | 文件源码
def draw_group(data, panel_params, coord, ax, **params):
        data = coord.transform(data, panel_params, munch=True)
        data['size'] *= SIZE_FACTOR

        # Each group is a polygon with a single facecolor
        # with potentially an edgecolor for every edge.
        ngroups = data['group'].unique().size
        verts = [None] * ngroups
        facecolor = [None] * ngroups
        edgecolor = [None] * ngroups
        linestyle = [None] * ngroups
        linewidth = [None] * ngroups

        # Some stats may order the data in ways that prevent
        # objects from occluding other objects. We do not want
        # to undo that order.
        grouper = data.groupby('group', sort=False)
        for i, (group, df) in enumerate(grouper):
            verts[i] = tuple(zip(df['x'], df['y']))
            fill = to_rgba(df['fill'].iloc[0], df['alpha'].iloc[0])
            facecolor[i] = 'none' if fill is None else fill
            edgecolor[i] = df['color'].iloc[0] or 'none'
            linestyle[i] = df['linetype'].iloc[0]
            linewidth[i] = df['size'].iloc[0]

        col = PolyCollection(
            verts,
            facecolors=facecolor,
            edgecolors=edgecolor,
            linestyles=linestyle,
            linewidths=linewidth,
            transOffset=ax.transData,
            zorder=params['zorder'])

        ax.add_collection(col)
项目:quantdigger    作者:andyzsf    | 项目源码 | 文件源码
def add_bars(self, colorup='g', colordown='r', alpha=0.5, width=1):
        r,g,b = colorConverter.to_rgb(colorup)
        colorup = r,g,b,alpha
        r,g,b = colorConverter.to_rgb(colordown)
        colordown = r,g,b,alpha
        colord = {True: colorup, False: colordown}
        colors = [colord[open<close] for open, close in zip(self.opens, self.closes)]

        delta = width/2.0
        bars = [((x-delta, 0), (x-delta, y), (x+delta, y), (x+delta, 0)) 
            for x, y in zip(self.dates, self.volumes)]

        barCollection = PolyCollection(bars, facecolors = colors)

        #self.ax.step(self.dates, self.volumes)
        #self.ax.add_collection(barCollection)
        #self.ax.bar(self.dates, self.volumes)
        #self.ax.plot(self.dates, self.volumes)
        self.ax.fill_between(self.dates, self.volumes, alpha=0.5)

        xmin, xmax = self.ax.get_xlim()
        ys = [y for x, y in zip(self.dates, self.volumes) if xmin<=x<=xmax]
        if ys:
            self.ax.set_ylim([0, max(ys)*10])

        for tick in self.ax.get_yticklabels():
            tick.set_visible(False)
项目:hylaa    作者:stanleybak    | 项目源码 | 文件源码
def __init__(self, plotman):
        self.plotman = plotman
        self.axes = plotman.axes
        self.mode_colors = plotman.mode_colors

        # create a blank invariant violation polys
        self.inv_vio_polys = collections.PolyCollection([], animated=True, alpha=0.7, edgecolor='red', facecolor='red')
        self.axes.add_collection(self.inv_vio_polys)

        # create a blank currently-tracked set of states poly
        self.cur_state_line2d = Line2D([], [], animated=True, color='k', lw=2, mew=2, ms=5, fillstyle='none')
        self.axes.add_line(self.cur_state_line2d)

        self.parent_to_polys = OrderedDict()
        self.parent_to_markers = OrderedDict()

        self.waiting_list_mode_to_polys = OrderedDict()
        self.aggregation_mode_to_polys = OrderedDict()

        self.trace = collections.LineCollection(
            [[(0, 0)]], animated=True, colors=('k'), linewidths=(3), linestyle='dashed')
        self.axes.add_collection(self.trace)

        if plotman.settings.extra_lines is not None:
            lines = plotman.settings.extra_lines
            self.extra_lines_col = collections.LineCollection(
                lines, animated=True, colors=('gray'), linewidths=(2), linestyle='dashed')
            self.axes.add_collection(self.extra_lines_col)
        else:
            self.extra_lines_col = None

        self.freeze_attrs()
项目:hylaa    作者:stanleybak    | 项目源码 | 文件源码
def add_reachable_poly(self, poly_verts, parent, mode_name):
        '''add a polygon which was reachable'''

        assert isinstance(parent, ContinuousPostParent)

        if len(poly_verts) <= 2:
            markers = self.parent_to_markers.get(parent)

            if markers is None:
                face_col, edge_col = self.mode_colors.get_edge_face_colors(mode_name)

                markers = Line2D([], [], animated=True, ls='None', alpha=0.5, marker='o', mew=2, ms=5,
                                 mec=edge_col, mfc=face_col)
                self.axes.add_line(markers)
                self.parent_to_markers[parent] = markers

            xdata = markers.get_xdata()
            ydata = markers.get_ydata()
            xdata.append(poly_verts[0][0])
            ydata.append(poly_verts[0][1])
            markers.set_xdata(xdata)
            markers.set_ydata(ydata)
        else:
            polys = self.parent_to_polys.get(parent)

            if polys is None:
                face_col, edge_col = self.mode_colors.get_edge_face_colors(mode_name)
                polys = collections.PolyCollection([], lw=2, animated=True, alpha=0.5,
                                                   edgecolor=edge_col, facecolor=face_col)
                self.axes.add_collection(polys)
                self.parent_to_polys[parent] = polys

            paths = polys.get_paths()

            codes = [Path.MOVETO] + [Path.LINETO] * (len(poly_verts) - 2) + [Path.CLOSEPOLY]
            paths.append(Path(poly_verts, codes))
项目:wradlib    作者:wradlib    | 项目源码 | 文件源码
def add_patches(ax, patch_array, **kwargs):
    """
    Add patches (points in the form Nx2) to axes


    Add patches (points in the form Nx2) to existing axes ax
    using :class:`matplotlib:matplotlib.collections.PolyCollection`.

    .. versionadded:: 0.6.0

    Parameters
    ----------
    ax : :class:`matplotlib:matplotlib.axes.Axes`
    patch_array : nested :class:`numpy:numpy.ndarray` Nx2 array(s)
    kwargs : :class:`matplotlib:matplotlib.collections.PolyCollection`

    Examples
    --------
    See :ref:`notebooks/visualisation/wradlib_overlay.ipynb`.
    """

    try:
        ax.add_collection(PolyCollection([patch_array], **kwargs))
    except AssertionError:
        ax.add_collection(PolyCollection([patch_array[None, ...]], **kwargs))
    except ValueError:
        for patch in patch_array:
            add_patches(ax, patch, **kwargs)
项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
def volume_overlay(ax, opens, closes, volumes, colorup='r', colordown='g', width=4, alpha=1.0):
    """Add a volume overlay to the current axes.  The opens and closes
    are used to determine the color of the bar.  -1 is missing.  If a
    value is missing on one it must be missing on all

    Parameters
    ----------
    ax : `Axes`
        an Axes instance to plot to
    opens : sequence
        a sequence of opens
    closes : sequence
        a sequence of closes
    volumes : sequence
        a sequence of volumes
    width : int
        the bar width in points
    colorup : color
        the color of the lines where close >= open
    colordown : color
        the color of the lines where close <  open
    alpha : float
        bar transparency

    Returns
    -------
    ret : `barCollection`
        The `barrCollection` added to the axes

    """

    colorup = mcolors.to_rgba(colorup, alpha)
    colordown = mcolors.to_rgba(colordown, alpha)
    colord = {True: colorup, False: colordown}
    colors = [colord[open < close]
              for open, close in zip(opens, closes)
              if open != -1 and close != -1]

    delta = width / 2.
    bars = [((i - delta, 0), (i - delta, v), (i + delta, v), (i + delta, 0))
            for i, v in enumerate(volumes)
            if v != -1]

    barCollection = PolyCollection(bars,
                                   facecolors=colors,
                                   edgecolors=((0, 0, 0, 1), ),
                                   antialiaseds=(0,),
                                   linewidths=(0.5,),
                                   )

    ax.add_collection(barCollection)
    corners = (0, 0), (len(bars), max(volumes))
    ax.update_datalim(corners)
    ax.autoscale_view()

    # add these last
    return barCollection
项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
def index_bar(ax, vals, facecolor='b', edgecolor='l', width=4, alpha=1.0, ):
    """Add a bar collection graph with height vals (-1 is missing).

    Parameters
    ----------
    ax : `Axes`
        an Axes instance to plot to
    vals : sequence
        a sequence of values
    facecolor : color
        the color of the bar face
    edgecolor : color
        the color of the bar edges
    width : int
        the bar width in points
    alpha : float
       bar transparency

    Returns
    -------
    ret : `barCollection`
        The `barrCollection` added to the axes

    """

    facecolors = (mcolors.to_rgba(facecolor, alpha),)
    edgecolors = (mcolors.to_rgba(edgecolor, alpha),)

    right = width / 2.0
    left = -width / 2.0

    bars = [((left, 0), (left, v), (right, v), (right, 0))
            for v in vals if v != -1]

    sx = ax.figure.dpi * (1.0 / 72.0)  # scale for points
    sy = ax.bbox.height / ax.viewLim.height

    barTransform = Affine2D().scale(sx, sy)

    offsetsBars = [(i, 0) for i, v in enumerate(vals) if v != -1]

    barCollection = PolyCollection(bars,
                                   facecolors=facecolors,
                                   edgecolors=edgecolors,
                                   antialiaseds=(0,),
                                   linewidths=(0.5,),
                                   offsets=offsetsBars,
                                   transOffset=ax.transData,
                                   )
    barCollection.set_transform(barTransform)

    minpy, maxx = (0, len(offsetsBars))
    miny = 0
    maxy = max([v for v in vals if v != -1])
    corners = (minpy, miny), (maxx, maxy)
    ax.update_datalim(corners)
    ax.autoscale_view()

    # add these last
    ax.add_collection(barCollection)
    return barCollection
项目:phoebe2    作者:phoebe-project    | 项目源码 | 文件源码
def anim_set_data(artist, data, fixed_limits=True):
    """
    """
    # of course mpl has to be difficult and not allow set_data
    # on polycollections...
    ax = artist.axes
    if isinstance(artist, PolyCollection) or isinstance(artist, Poly3DCollection):
        ax.collections.remove(artist)

        if data is not None:
            pckwargs = {k:v for k,v in data.items() if k!='data'}
            data = data['data']
        else:
            data = []
            pckwargs = {}

        if len(data):
            xarray = np.array(data[:, :, 0])
            yarray = np.array(data[:, :, 1])
        else:
            xarray = []
            yarray = []

        if isinstance(artist, Poly3DCollection):
            if len(data):
                zarray = np.array(data[:, :, 2])
            else:
                zarray = []
            artist = Poly3DCollection(data, **pckwargs)
        else:
            zarray = None
            artist = PolyCollection(data, **pckwargs)

        ax.add_collection(artist)

        created = True
    else:             
        if data is None:
            # TODO: may need to be smart here to send the right shape,
            # especially for 3d axes
            data = ([], []) 
        artist.set_data(*data)

        created = False
        xarray = np.array(data[0])
        yarray = np.array(data[1])
        zarray = None # TODO: add support for 3d


    # TODO: need to be smarter about this - the user may have provided limits
    # in one of the plot_argss
    if not fixed_limits:
        ax = handle_limits(ax, xarray, yarray, zarray, apply=True)

    return artist, created
项目:quantdigger    作者:andyzsf    | 项目源码 | 文件源码
def plot(self, widget, width = 0.6, colorup = 'r', colordown='g', lc='k', alpha=1):
        """docstring for plot""" 
        delta = self.width/2.
        barVerts = [ ( (i-delta, open), (i-delta, close), (i+delta, close), (i+delta, open) ) for i, open, close in zip(xrange(len(self.data)), self.data.open, self.data.close) if open != -1 and close!=-1 ]
        rangeSegments = [ ((i, low), (i, high)) for i, low, high in zip(xrange(len(self.data)), self.data.low, self.data.high) if low != -1 ]
        r,g,b = colorConverter.to_rgb(self.colorup)
        colorup = r,g,b,self.alpha
        r,g,b = colorConverter.to_rgb(self.colordown)
        colordown = r,g,b,self.alpha
        colord = { True : colorup,
                   False : colordown,
                   }
        colors = [colord[open<close] for open, close in zip(self.data.open, self.data.close) if open!=-1 and close !=-1]
        assert(len(barVerts)==len(rangeSegments))
        useAA = 0,  # use tuple here
        lw = 0.5,   # and here
        r,g,b = colorConverter.to_rgb(self.lc)
        linecolor = r,g,b,self.alpha
        lineCollection = LineCollection(rangeSegments,
                                         colors       = ( linecolor, ),
                                         linewidths   = lw,
                                         antialiaseds = useAA,
                                         zorder = 0,
                                         )

        barCollection = PolyCollection(barVerts,
                                       facecolors   = colors,
                                       edgecolors   = colors,
                                       antialiaseds = useAA,
                                       linewidths   = lw,
                                       zorder = 1,
                                       )
        #minx, maxx = 0, len(rangeSegments)
        #miny = min([low for low in self.data.low if low !=-1])
        #maxy = max([high for high in self.data.high if high != -1])
        #corners = (minx, miny), (maxx, maxy)
        #ax.update_datalim(corners)
        widget.autoscale_view()
        # add these last
        widget.add_collection(barCollection)
        widget.add_collection(lineCollection)

        #ax.plot(self.data.close, color = 'y')
        #lineCollection, barCollection = None, None
        return lineCollection, barCollection
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _check_colors(self, collections, linecolors=None, facecolors=None,
                      mapping=None):
        """
        Check each artist has expected line colors and face colors

        Parameters
        ----------
        collections : list-like
            list or collection of target artist
        linecolors : list-like which has the same length as collections
            list of expected line colors
        facecolors : list-like which has the same length as collections
            list of expected face colors
        mapping : Series
            Series used for color grouping key
            used for andrew_curves, parallel_coordinates, radviz test
        """

        from matplotlib.lines import Line2D
        from matplotlib.collections import Collection, PolyCollection
        conv = self.colorconverter
        if linecolors is not None:

            if mapping is not None:
                linecolors = self._get_colors_mapped(mapping, linecolors)
                linecolors = linecolors[:len(collections)]

            self.assertEqual(len(collections), len(linecolors))
            for patch, color in zip(collections, linecolors):
                if isinstance(patch, Line2D):
                    result = patch.get_color()
                    # Line2D may contains string color expression
                    result = conv.to_rgba(result)
                elif isinstance(patch, PolyCollection):
                    result = tuple(patch.get_edgecolor()[0])
                else:
                    result = patch.get_edgecolor()

                expected = conv.to_rgba(color)
                self.assertEqual(result, expected)

        if facecolors is not None:

            if mapping is not None:
                facecolors = self._get_colors_mapped(mapping, facecolors)
                facecolors = facecolors[:len(collections)]

            self.assertEqual(len(collections), len(facecolors))
            for patch, color in zip(collections, facecolors):
                if isinstance(patch, Collection):
                    # returned as list of np.array
                    result = patch.get_facecolor()[0]
                else:
                    result = patch.get_facecolor()

                if isinstance(result, np.ndarray):
                    result = tuple(result)

                expected = conv.to_rgba(color)
                self.assertEqual(result, expected)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_area_colors(self):
        from matplotlib import cm
        from matplotlib.collections import PolyCollection

        custom_colors = 'rgcby'
        df = DataFrame(rand(5, 5))

        ax = df.plot.area(color=custom_colors)
        self._check_colors(ax.get_lines(), linecolors=custom_colors)
        poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)]
        self._check_colors(poly, facecolors=custom_colors)

        handles, labels = ax.get_legend_handles_labels()
        # legend is stored as Line2D, thus check linecolors
        linehandles = [x for x in handles if not isinstance(x, PolyCollection)]
        self._check_colors(linehandles, linecolors=custom_colors)
        for h in handles:
            self.assertTrue(h.get_alpha() is None)
        tm.close()

        ax = df.plot.area(colormap='jet')
        jet_colors = lmap(cm.jet, np.linspace(0, 1, len(df)))
        self._check_colors(ax.get_lines(), linecolors=jet_colors)
        poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)]
        self._check_colors(poly, facecolors=jet_colors)

        handles, labels = ax.get_legend_handles_labels()
        linehandles = [x for x in handles if not isinstance(x, PolyCollection)]
        self._check_colors(linehandles, linecolors=jet_colors)
        for h in handles:
            self.assertTrue(h.get_alpha() is None)
        tm.close()

        # When stacked=False, alpha is set to 0.5
        ax = df.plot.area(colormap=cm.jet, stacked=False)
        self._check_colors(ax.get_lines(), linecolors=jet_colors)
        poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)]
        jet_with_alpha = [(c[0], c[1], c[2], 0.5) for c in jet_colors]
        self._check_colors(poly, facecolors=jet_with_alpha)

        handles, labels = ax.get_legend_handles_labels()
        # Line2D can't have alpha in its linecolor
        self._check_colors(handles[:len(jet_colors)], linecolors=jet_colors)
        for h in handles:
            self.assertEqual(h.get_alpha(), 0.5)