Esempio n. 1
0
    def polygons(self,
                 llcrnrlon=0,
                 llcrnrlat=-90,
                 urcrnrlon=360,
                 urcrnrlat=90,
                 **kwargs_polygon):
        x, y, nb_pt_seg, id_seg = get_data_for_polygon(
            self.relative_x,
            self.relative_y,
            self.nb_seg_bin,
            self.i_first_seg_bin,
            self.nb_pt_seg,
            self.i_first_pt_seg,
            self.id_seg,
            self.nb_bin_x,
            self.nb_bin_y,
            self.bin_size,
            llcrnrlon,
            llcrnrlat,
            urcrnrlon,
            urcrnrlat,
        )

        polygons = build_polygon(x, y, nb_pt_seg, id_seg)
        print(len(polygons), id_seg.shape)
        kwargs_polygon["linewidth"] = 0
        kwargs_polygon["closed"] = False
        return mc.PolyCollection(polygons, **kwargs_polygon)
Esempio n. 2
0
 def _init(self):
     if True:  # not self._initialized:
         if not self.Q._initialized:
             self.Q._init()
         self._set_transform()
         with cbook._setattr_cm(self.Q, pivot=self.pivot[self.labelpos],
                                # Hack: save and restore the Umask
                                Umask=ma.nomask):
             u = self.U * np.cos(np.radians(self.angle))
             v = self.U * np.sin(np.radians(self.angle))
             angle = (self.Q.angles if isinstance(self.Q.angles, str)
                      else 'uv')
             self.verts = self.Q._make_verts(
                 np.array([u]), np.array([v]), angle)
         kwargs = self.Q.polykw
         kwargs.update(self.kw)
         self.vector = mcollections.PolyCollection(
                                     self.verts,
                                     offsets=[(self.X, self.Y)],
                                     transOffset=self.get_transform(),
                                     **kwargs)
         if self.color is not None:
             self.vector.set_color(self.color)
         self.vector.set_transform(self.Q.get_transform())
         self.vector.set_figure(self.get_figure())
         self._initialized = True
Esempio n. 3
0
    def plotRelief(self, ax, *args, **kwargs):
        positions = np.array(list(self.meshCorners.vp.position))
        polygons = []
        for k, corners in enumerate(self.meshCenters.vp.corners):
            lat, long = Projection().toLatLong(positions[corners])
            polygon = list(zip(long, lat))
            polygons.append(polygon)
        elevations = np.array(list(self.meshCenters.vp.elevation))

        cmap_terrain = plt.cm.get_cmap('gist_earth')
        cmap_ocean = plt.cm.get_cmap('ocean')

        def color(e):
            if e > 0:
                y = np.interp(e, [0, 10], [0.5, 1])
                return cmap_terrain(y)
            else:
                y = np.interp(e, [-10, 0], [0.25, 0.8])
                return cmap_ocean(y)

        colors = list(map(color, elevations))
        ax.add_collection(
            mc.PolyCollection(polygons,
                              *args,
                              transform=ccrs.Geodetic(),
                              facecolors=colors,
                              **kwargs))
Esempio n. 4
0
def drawMesh2DElements(plt, elements, deco):

    # ~~> Focus on current subplot / axes instance
    crax = plt.gca()
    # ~~>  Collections
    colection = collections.PolyCollection(
        elements,
        cmap=cm.jet,
        antialiaseds=0,  # norm=plt.Normalize()
        edgecolors='k',
        linewidth=1,
        facecolors='none')
    #colection.set_array(val)       # each triangle colour dependent on its value from its verticies
    # ~~> Plot data
    #ex: fig = plt.figure(1,figsize=(3.0,4.0),dpi=100), where figsize is in inches
    crax.add_collection(colection)  # adds, or plots our collection
    xmin = deco['roi'][0][0]
    xmax = deco['roi'][1][0]
    ymin = deco['roi'][0][1]
    ymax = deco['roi'][1][1]
    if deco.has_key('crax.xlim'):
        xmin -= deco['crax.xlim']
        xmax += deco['crax.xlim']
    if deco.has_key('crax.ylim'):
        ymin -= deco['crax.ylim']
        ymin += deco['crax.ylim']
    crax.set_xlim(xmin, xmax)  # sets x axis limits, default 0-1
    crax.set_ylim(ymin, ymax)  # sets y axis limits, default 0-1
    #plt.axis([np.min(x0),np.max(x0),np.min(y0),np.max(y0)])
    crax.axis('equal')  # sets both axis scale to be equal
    #curax.set_title('%s\n2D mesh with %d elements, timestep %d, Variable - %s' %(d['NAME'],d['NELEM3'],t,d['VARNAMES'][v]))     # sets up title

    return
Esempio n. 5
0
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)
Esempio n. 6
0
def test_polycollection_close():
    from mpl_toolkits.mplot3d import Axes3D

    vertsQuad = [
        [[0., 0.], [0., 1.], [1., 1.], [1., 0.]],
        [[0., 1.], [2., 3.], [2., 2.], [1., 1.]],
        [[2., 2.], [2., 3.], [4., 1.], [3., 1.]],
        [[3., 0.], [3., 1.], [4., 1.], [4., 0.]]]

    fig = plt.figure()
    ax = Axes3D(fig)

    colors = ['r', 'g', 'b', 'y', 'k']
    zpos = list(range(5))

    poly = mcollections.PolyCollection(
        vertsQuad * len(zpos), linewidth=0.25)
    poly.set_alpha(0.7)

    # need to have a z-value for *each* polygon = element!
    zs = []
    cs = []
    for z, c in zip(zpos, colors):
        zs.extend([z] * len(vertsQuad))
        cs.extend([c] * len(vertsQuad))

    poly.set_color(cs)

    ax.add_collection3d(poly, zs=zs, zdir='y')

    # axis limit settings:
    ax.set_xlim3d(0, 4)
    ax.set_zlim3d(0, 3)
    ax.set_ylim3d(0, 4)
Esempio n. 7
0
def plot_mesh(vertices, cells, materials=None, plotfile='tmp.png'):
    cell_vertex_coordinates = []
    for e in xrange(cells.shape[0]):
        local_vertex_numbers = cells[e,:]
        local_coordinates = vertices[local_vertex_numbers,:]
        cell_vertex_coordinates.append(local_coordinates)
    import matplotlib.cm as cm
    import matplotlib.collections as collections
    import matplotlib.pyplot as plt
    col = collections.PolyCollection(cell_vertex_coordinates)
    if materials is not None:
        col.set_array(materials)
        #col.set_cmap(cm.jet)
        #col.set_cmap(cm.gray_r)
        col.set_cmap(cm.hot_r)
    fig = plt.figure()
    ax = fig.gca()
    ax.add_collection(col)
    xmin, xmax = vertices[:,0].min(), vertices[:,0].max()
    ymin, ymax = vertices[:,1].min(), vertices[:,1].max()
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    ax.set_aspect('equal')
    plt.savefig(plotfile + '.png')
    plt.savefig(plotfile + '.pdf')
    plt.show()
Esempio n. 8
0
def trimesh(vertices, indices, labels=False):
    """
    Plot a 2D triangle mesh
    """
    from scipy import asarray
    from matplotlib import collections
    from pylab import gca, axis, text
    from numpy import average

    vertices, indices = asarray(vertices), asarray(indices)

    #3d tensor [triangle index][vertex index][x/y value]
    triangles = vertices[indices.ravel(), :].reshape((indices.shape[0], 3, 2))

    col = collections.PolyCollection(triangles)
    col.set_facecolor('grey')
    col.set_alpha(0.5)
    col.set_linewidth(1)

    sub = gca()
    sub.add_collection(col, autolim=True)
    axis('off')
    sub.autoscale_view()

    if labels:
        barycenters = average(triangles, axis=1)
        for n, bc in enumerate(barycenters):
            text(
                bc[0], bc[1], str(n), {
                    'color': 'k',
                    'fontsize': 8,
                    'horizontalalignment': 'center',
                    'verticalalignment': 'center'
                })
Esempio n. 9
0
 def _init(self):
     if True:  # not self._initialized:
         if not self.Q._initialized:
             self.Q._init()
         self._set_transform()
         _pivot = self.Q.pivot
         self.Q.pivot = self.pivot[self.labelpos]
         # Hack: save and restore the Umask
         _mask = self.Q.Umask
         self.Q.Umask = ma.nomask
         self.verts = self.Q._make_verts(np.array([self.U]), np.zeros(
             (1, )), self.angle)
         self.Q.Umask = _mask
         self.Q.pivot = _pivot
         kw = self.Q.polykw
         kw.update(self.kw)
         self.vector = mcollections.PolyCollection(
             self.verts,
             offsets=[(self.X, self.Y)],
             transOffset=self.get_transform(),
             **kw)
         if self.color is not None:
             self.vector.set_color(self.color)
         self.vector.set_transform(self.Q.get_transform())
         self.vector.set_figure(self.get_figure())
         self._initialized = True
Esempio n. 10
0
def build_collection(coord, connect, disp_vector=None, timing=False):
    """ Build quad mesh.
    
    Args:
        coord (:obj:`numpy.array`): Coordinates of the element.
        connect (:obj:`numpy.array`): Element connectivity.
        disp_vector (:obj:`numpy.array`, optional): Displacement.
        timing (:obj:`bool`, optional): If True shows the time to build the mesh. Defaults to False.
     
    Returns:
        Matplotlib collection object.
    """
    t0 = time()
    x, y = coord[:, 1], coord[:, 2]
    xy = np.c_[x, y]
    squares = np.asarray(connect)
    verts = xy[squares - 1]
    pc = cl.PolyCollection(verts)
    if disp_vector is not None:
        pc.set_array(disp_vector)
        pc.set_cmap("viridis")
    else:
        pc.set_edgecolor("black")
        pc.set_facecolor("None")
    tf = time()
    if timing:
        print("Time to build collection: " + str(round((tf - t0), 6)) + '[s]')

    return pc
Esempio n. 11
0
def generate_polycollection(ax, x, y1, y2):
    """
    Accessory function that creates new PolyCollection class instance representing
    new correct field-of-view. We use its output to assign new *path* to the old
    one instance. Algorithm has been taken from the matplotlib' sources for the
    fill_between() function and used because there is no easy way to update polygon
    with new data

    input:
        same as for the fill_between() function

    returns:
        matplotlib.collections.PolyCollection instance
    """

    # i.e. where = outer_circle >= fov_circle
    where = y2 >= y1
    kwargs = {'facecolor': colors['fov_outer'], 'alpha': 0.25}

    # Convert the arrays so we can work with them
    x = np.ma.masked_invalid(ax.convert_xunits(x))
    y1 = np.ma.masked_invalid(ax.convert_yunits(y1))
    y2 = np.ma.masked_invalid(ax.convert_yunits(y2))

    where = where & ~functools.reduce(np.logical_or,
                                      map(np.ma.getmask, [x, y1, y2]))

    x, y1, y2 = np.broadcast_arrays(np.atleast_1d(x), y1, y2)

    polys = []
    for ind0, ind1 in contiguous_regions(where):
        xslice = x[ind0:ind1]
        y1slice = y1[ind0:ind1]
        y2slice = y2[ind0:ind1]

        if not len(xslice):
            continue

        N = len(xslice)
        X = np.zeros((2 * N + 2, 2), float)

        # the purpose of the next two lines is for when y2 is a
        # scalar like 0 and we want the fill to go all the way
        # down to 0 even if none of the y1 sample points do
        start = xslice[0], y2slice[0]
        end = xslice[-1], y2slice[-1]

        X[0] = start
        X[N + 1] = end

        X[1:N + 1, 0] = xslice
        X[1:N + 1, 1] = y1slice
        X[N + 2:, 0] = xslice[::-1]
        X[N + 2:, 1] = y2slice[::-1]

        polys.append(X)

    return mcoll.PolyCollection(polys, **kwargs)
Esempio n. 12
0
    def add_reachable_poly(self, stateset):
        '''add a polygon which was reachable'''

        poly_verts = stateset.verts(self.plotman, self.subplot)
        mode_name = stateset.mode.name

        if len(poly_verts
               ) <= 2 and self.plotman.settings.use_markers_for_small:
            markers = self.parent_to_markers.get('mode_' + mode_name)

            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['mode_' + mode_name] = 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(mode_name)

            if polys is None:
                lw = self.plotman.settings.reachable_poly_width
                face_col, edge_col = self.mode_colors.get_edge_face_colors(
                    mode_name)
                polys = collections.PolyCollection([],
                                                   lw=lw,
                                                   animated=True,
                                                   alpha=0.5,
                                                   edgecolor=edge_col,
                                                   facecolor=face_col)
                self.axes.add_collection(polys)
                self.parent_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))

            # save the Path list in the StateSet
            stateset.set_plot_path(self.subplot, paths, len(paths) - 1)
Esempio n. 13
0
def triamatrix(a, ax, rot=0, cmap="viridis", **kwargs):
    segs = []
    for i in range(a.shape[0]):
        for j in range(a.shape[1]):
            segs.append(triatpos((j, i), rot=rot))
    col = collections.PolyCollection(segs, cmap=cmap, **kwargs)
    col.set_array(a.flatten())
    ax.add_collection(col)
    return col
Esempio n. 14
0
        def init_polycollection_func():
            "initialization function if polycollection doesn't exist"

            return collections.PolyCollection(
                [],
                lw=self.plotman.settings.reachable_poly_width,
                animated=True,
                edgecolor='k',
                facecolor=(0., 0., 0., 0.0),
                zorder=3)
Esempio n. 15
0
def volume_overlay(ax, opens, closes, volumes, colorup='g', colordown='r', 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 = colorConverter.to_rgba(colorup, alpha)
    colordown = colorConverter.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 = collections.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
Esempio n. 16
0
    def plot_env(self):
        if self.draw == False:
            plt.show(block=False)
            self.draw = True
        plt.cla()
        ''' bounding box '''
        self.ax.set_xlim(self.bnd[0:2] + array([-0.5, 0.5]))
        self.ax.set_ylim(self.bnd[2:4] + array([-0.5, 0.5]))
        self.ax.plot([self.bnd[0], self.bnd[0], self.bnd[1], self.bnd[1], self.bnd[0]], \
                [self.bnd[2], self.bnd[3], self.bnd[3], self.bnd[2], self.bnd[2]], \
                color='k', linewidth=3.0)
        ''' polygon obstacles '''
        col_poly_vert = []
        for i in range(len(self.obs_poly_array)):
            col_poly_vert.append(self.obs_poly_array[i].vertices)

        col_poly = plt_col.PolyCollection(col_poly_vert,
                                          edgecolor='none',
                                          facecolor='k')
        self.ax.add_collection(col_poly)
        ''' spherical obstacles '''
        for i in range(len(self.obs_sph_array)):
            cir_tmp = plt.Circle((self.obs_sph_array[i].pos),
                                 self.obs_sph_array[i].radius,
                                 color='k')
            self.ax.add_artist(cir_tmp)
        ''' initial and final pos '''
        circle_init = plt.Circle((self.ini_pos), 0.2, color='r')
        circle_end = plt.Circle((self.fin_pos), 0.2, color='g')
        self.ax.add_artist(circle_init)
        self.ax.add_artist(circle_end)
        ''' rrt tree '''
        segments = []
        for i in range(len(self.vertices)):
            # root
            if self.vertices[i].parent == None:
                continue
            else:
                segments.append(
                    (self.vertices[i].pos, self.vertices[i].parent.pos))
        col_tree = plt_col.LineCollection(segments, linewidths=1, colors='b')
        self.ax.add_collection(col_tree)
        ''' best path so far '''
        isSolnFound, bestPath = self.curBestPath()
        self.curTree()
        if isSolnFound == True:
            plt.plot(bestPath[:, 0],
                     bestPath[:, 1],
                     linewidth=2,
                     color='r',
                     marker='o')
        plt.draw()

        pass
Esempio n. 17
0
def plot_spectrum25D(spectrum, harpy_input, plane):
    nbins = 20

    freqs, amps, amp_range = _get_sorted_amp_and_freq(spectrum)
    df = np.min(freqs[1:] - freqs[:-1]) / 2

    blocks = []
    values = []
    av = np.empty(len(freqs))
    print "  |- Calculating histograms"
    for i, f in enumerate(freqs):
        # get histogram values
        amp_range_in_f = [np.min(amps[i]), np.max(amps[i])]
        a = np.histogram(amps[i], bins=nbins, range=amp_range_in_f)
        av[i] = np.average(amps[i])

        # define xy-values of blocks (counter clockwise, start=bottom left)
        y = np.append(amp_range[0], a[1])  # add empty bottom block
        yp = np.c_[y[:-1], y[:-1], y[1:], y[1:]]
        xp = np.repeat([[f - df, f + df, f + df, f - df]], nbins + 1, axis=0)

        # add to list of blocks and values
        blocks.append(np.dstack((xp, yp)))
        values.append(np.append(0, a[0]))

    blocks = np.concatenate(blocks, 0)
    values = np.concatenate(values, 0)
    pc = mc.PolyCollection(blocks, cmap='jet', edgecolors=None)
    pc.set_array(values)

    print "  |- Actual plotting"
    ps.set_style('presentation',
                 manual={
                     'lines.marker': '',
                     'grid.alpha': 0.2
                 })
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlim([freqs[0], freqs[-1]])
    ax.set_ylim(amp_range)
    ax.set_ylabel('Relative Amplitude dB')
    ax.set_xlabel('Frequency Hz')
    ax.set_title('Spectrum of plane ' + plane.upper())

    _add_tunes_to_ax(ax, harpy_input, plane)
    ax.add_collection(pc)

    ax.plot(freqs, av, label='average', color='black', linestyle='--')

    plt.colorbar(mappable=pc)
    plt.draw()
    plt.show()
    pass
Esempio n. 18
0
    def plot_tiles(self, table, x, y, width, height, color=None,
                   anchor='center', edgecolors='face', linewidth=0.8,
                   **kwargs):
        # get x/y data
        xdata = get_table_column(table, x)
        ydata = get_table_column(table, y)
        wdata = get_table_column(table, width)
        hdata = get_table_column(table, height)

        # get color and sort
        if color:
            cdata = get_table_column(table, color)
            zipped = zip(xdata, ydata, wdata, hdata, cdata)
            zipped.sort(key=lambda row: row[-1])
            try:
                xdata, ydata, wdata, hdata, cdata = map(numpy.asarray,
                                                        zip(*zipped))
            except ValueError:
                pass

        # construct vertices
        if anchor == 'll':
            verts = [((x, y), (x, y+height), (x+width, y+height),
                      (x+width, y)) for (x,y,width,height) in
                     zip(xdata, ydata, wdata, hdata)]
        elif anchor == 'lr':
            verts = [((x-width, y), (x-width, y+height), (x, y+height),
                      (x, y)) for (x,y,width,height) in
                     zip(xdata, ydata, wdata, hdata)]
        elif anchor == 'ul':
            verts = [((x, y-height), (x, y), (x+width, y),
                      (x+width, y-height)) for (x,y,width,height) in
                     zip(xdata, ydata, wdata, hdata)]
        elif anchor == 'ur':
            verts = [((x-width, y-height), (x-width, y), (x, y),
                      (x, y-height)) for (x,y,width,height) in
                     zip(xdata, ydata, wdata, hdata)]
        elif anchor == 'center':
            verts = [((x-width/2., y-height/2.), (x-width/2., y+height/2.),
                       (x+width/2., y+height/2.), (x+width/2., y-height/2.))
                     for (x,y,width,height) in zip(xdata, ydata, wdata, hdata)]
        else:
            raise ValueError("Unrecognised tile anchor '%s'." % anchor)

        # build collection
        cmap = kwargs.pop('cmap', cm.jet)
        coll = collections.PolyCollection(verts, edgecolors=edgecolors,
                                          linewidth=linewidth, **kwargs)
        if color:
            coll.set_array(cdata)
            coll.set_cmap(cmap)

        return self.add_collection(coll)
Esempio n. 19
0
    def manual_arrows(self, x, y, u, v, speeds, size=1.0):
        # manual arrow heads.
        angles = np.arctan2(v, u)

        polys = [utils.rot(angle, self.sym) for angle in angles]
        polys = np.array(polys)
        polys[speeds < 0.1, :] = self.diam
        polys *= size
        polys[..., 0] += x[:, None]
        polys[..., 1] += y[:, None]
        pcoll = collections.PolyCollection(polys)
        return pcoll
Esempio n. 20
0
def test_polycollection_joinstyle():
    # Bug #2890979 reported by Matthew West

    from matplotlib import collections as mcoll

    fig = plt.figure()
    ax = fig.add_subplot(111)
    verts = np.array([[1, 1], [1, 2], [2, 2], [2, 1]])
    c = mcoll.PolyCollection([verts], linewidths=40)
    ax.add_collection(c)
    ax.set_xbound(0, 3)
    ax.set_ybound(0, 3)
Esempio n. 21
0
    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))
Esempio n. 22
0
def show(mesh):
    vertices = mesh[0]
    face_ids = mesh[2]
    group_ids = compute_groups(mesh)

    # display the graph
    # Only support up to 20 difference colours (see cmap=plt.cm.tab20)
    fig, ax = plt.subplots(figsize=(6, 6))
    ax.axis('equal')
    min_range = np.min(vertices, axis=0)
    max_range = np.max(vertices, axis=0)
    ax.set_xlim(min_range[0], max_range[0])
    ax.set_ylim(min_range[1], max_range[1])

    font = {
        'family': 'serif',
        'color': 'darkblue',
        'weight': 'normal',
        'size': 14
    }
    num_groups = np.max(group_ids)
    plt.title(('Greedy Coloring Algorithm (%d colors)' % num_groups),
              fontdict=font)
    plt.axis('off')

    triangles = []
    for face_id in face_ids:
        v0 = vertices[face_id[0]]
        v1 = vertices[face_id[1]]
        v2 = vertices[face_id[2]]
        triangles.append([v0, v1, v2])

    # draw mesh
    collec = collections.PolyCollection(triangles,
                                        facecolors='white',
                                        edgecolors='black',
                                        linewidths=0.1)
    ax.add_collection(collec)

    # draw nodes
    colors = ['blue', 'red', 'yellow', 'green', 'orange', 'pink']
    for group_id in range(num_groups):
        node_indices, = np.where(group_ids == group_id)
        if len(node_indices) == 0:
            continue

        vtx = vertices[node_indices]
        x, y = zip(*vtx)
        ax.plot(x, y, '.', alpha=1.0, color=colors[group_id], markersize=5.0)

    plt.show()
Esempio n. 23
0
  def polycol(self, verts, facecolors='none', **kwargs):
    'add polycollection'

    from matplotlib import collections
    if facecolors != 'none':
      assert numeric.isarray(facecolors) and facecolors.shape == (len(verts),)
      array = facecolors
      facecolors = None
    polycol = collections.PolyCollection(verts, facecolors=facecolors, **kwargs)
    if facecolors is None:
      polycol.set_array(array)
    self.gca().add_collection(polycol)
    self.sci(polycol)
    return polycol
Esempio n. 24
0
def add_feature3d(ax, feature, clip_geom=None, zs=None):
    """
    Add the given feature to the given axes.
    """
    concat = lambda iterable: list(itertools.chain.from_iterable(iterable))

    target_projection = ax.projection

    if hasattr(feature, 'geometries'):
        # cartopy.feature.Feature
        feature_hook = feature
    elif hasattr(feature._feature, 'geometries'):
        # cartopy.feature_artist.FeatureArtist ?
        feature_hook = feature._feature
    else:
        raise RuntimeError('problem with feature: %s' % type(feature))

    geoms = list(feature_hook.geometries())

    if target_projection != feature_hook.crs:
        # Transform the geometries from the feature's CRS into the
        # desired projection.
        geoms = [
            target_projection.project_geometry(geom, feature_hook.crs)
            for geom in geoms
        ]

    if clip_geom:
        # Clip the geometries based on the extent of the map (because mpl3d
        # can't do it for us)
        geoms = [geom.intersection(clip_geom) for geom in geoms]

    # Convert the geometries to paths so we can use them in matplotlib.
    paths = concat(geos_to_path(geom) for geom in geoms)

    # Bug: mpl3d can't handle edgecolor='face'
    kwargs = feature_hook.kwargs
    if kwargs.get('edgecolor') == 'face':
        kwargs['edgecolor'] = kwargs['facecolor']

    polys = concat(path.to_polygons(closed_only=False) for path in paths)

    if kwargs.get('facecolor', 'none') == 'none':
        lc = mcoll.LineCollection(polys, **kwargs)
    else:
        lc = mcoll.PolyCollection(polys, closed=False, **kwargs)

    #ax.add_collection3d(lc, zs=zs)
    add_fixzordercollection3d(ax, lc, zs=zs)
Esempio n. 25
0
    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()
Esempio n. 26
0
 def add_polygons(self, verts):
     # PolyCollection does not allow `vmin`/`vmax`,
     # and `norm` is already passed.
     kwds = {
         k: v for k, v in self.plot_kwds.items()
         if k not in ("vmin", "vmax", "norm")
     }
     p = collections.PolyCollection(
         verts,
         array=self.container.data,
         norm=self.container.norm,
         **kwds)
     self.ax.add_collection(p)
     self.ax.autoscale_view()
     return p
Esempio n. 27
0
def _hexplot(matrix, fig, colormap):
    """Internal function to plot a hexagonal map.
    """
    umatrix_min = matrix.min()
    umatrix_max = matrix.max()
    n_rows, n_columns = matrix.shape
    cmap = plt.get_cmap(colormap)
    offsets = np.zeros((n_columns * n_rows, 2))
    facecolors = []
    for row in range(n_rows):
        for col in range(n_columns):
            if row % 2 == 0:
                offsets[row * n_columns + col] = [col + 0.5, 2 * n_rows - 2 * row]
                facecolors.append(
                    cmap((matrix[row, col] - umatrix_min) / (umatrix_max) * 255)
                )
            else:
                offsets[row * n_columns + col] = [col, 2 * n_rows - 2 * row]
                facecolors.append(
                    cmap((matrix[row, col] - umatrix_min) / (umatrix_max) * 255)
                )
    polygon = np.zeros((6, 2), float)
    polygon[:, 0] = 1.1 * np.array([0.5, 0.5, 0.0, -0.5, -0.5, 0.0])
    polygon[:, 1] = 1.1 * np.array(
        [
            -np.sqrt(3) / 6,
            np.sqrt(3) / 6,
            np.sqrt(3) / 2 + np.sqrt(3) / 6,
            np.sqrt(3) / 6,
            -np.sqrt(3) / 6,
            -np.sqrt(3) / 2 - np.sqrt(3) / 6,
        ]
    )
    polygons = np.expand_dims(polygon, 0) + np.expand_dims(offsets, 1)
    ax = fig.gca()
    collection = mcoll.PolyCollection(
        polygons,
        offsets=offsets,
        facecolors=facecolors,
        edgecolors=facecolors,
        linewidths=1.0,
        offset_position="data",
    )
    ax.add_collection(collection, autolim=False)
    corners = ((-0.5, -0.5), (n_columns + 0.5, 2 * n_rows + 0.5))
    ax.update_datalim(corners)
    ax.autoscale_view(tight=True)
    return offsets
Esempio n. 28
0
def draw_values(ax, opens, highs, lows, closes, width=4, up_color='r', down_color='g', alpha=0.75):
    '''K-bars'''
    delta = width / 2.
    barVerts = [((i - delta, open),
                 (i - delta, close),
                 (i + delta, close),
                 (i + delta, open))
                for i, open, close in zip(range(len(opens)), opens, closes)]

    downSegments = [((i, low), (i, min(open, close)))
                    for i, low, high, open, close in zip(range(len(lows)), lows, highs, opens, closes)]

    upSegments = [((i, max(open, close)), (i, high))
                  for i, low, high, open, close in zip(range(len(lows)), lows, highs, opens, closes)]
    segments = downSegments + upSegments

    r, g, b = colorConverter.to_rgb(up_color)
    up_color = r, g, b, alpha
    r, g, b = colorConverter.to_rgb(down_color)
    down_color = r, g, b, alpha

    color_dict = {True: up_color, False: down_color,}
    colors = [color_dict[open < close] for open, close in zip(opens, closes)]

    line_collections = collections.LineCollection( segments,
                                                   linewidths=(0.5,),
                                                   colors=((0,0,0,1),),
                                                   antialiaseds=(0,)
                                                 )
    bar_collections = collections.PolyCollection( barVerts,
                                      facecolors=colors,
                                      edgecolors=((0, 0, 0, 1),),
                                      antialiaseds=(0,),
                                      linewidths=(0.5,),
                                    )
    min_x, max_x = 0, len(opens)
    min_y = min([low for low in lows])
    max_y = max([high for high in highs])

    corners = (min_x, min_y), (max_x, max_y)
    ax.update_datalim(corners)
    ax.autoscale_view()

    ax.add_collection(line_collections)
    ax.add_collection(bar_collections)

    return line_collections, bar_collections
Esempio n. 29
0
 def create_artists(self):
     self._update_verts()
     self.artists = []
     self.collections = []
     for i, k in enumerate(self.verts.keys()):
         fc = set_area.fc[1]
         ec = set_area.ec[1]
         if self.area_status:
             fc = set_area.fc[0]
             ec = set_area.ec[0]
         verts = self.verts[k]
         collection = colls.PolyCollection([verts],
                                           facecolors=fc,
                                           edgecolors=ec,
                                           visible=False)
         self.artists += [collection]
         self.collections += [collection]
Esempio n. 30
0
def drawMesh2DElements(myplt, decoUser, elements):

    #  *2DElements: draw individual elements polygons  (triangle or quads)
    # ~~> Focus on current subplot / axes instance
    crax = myplt.gca()
    # ~~>  Collections
    #   colection = collections.PolyCollection(
    #      elements, cmap=cm.jet, antialiaseds=0, # norm=myplt.Normalize()
    #      edgecolors = 'k', linewidth=1, facecolors = 'none')

    colection = collections.PolyCollection(elements)

    #colection.set_array(val)       # each triangle colour dependent on its value from its verticies
    # ~~> Plot data
    #ex: fig = myplt.figure(1,figsize=(3.0,4.0),dpi=100), where figsize is in inches
    crax.add_collection(colection)  # adds, or plots our collection

    return