Exemple #1
0
 def set_subplot_map(self, highlights, cgeorange):
     ###SUBPLOT: SET MAP
     self.oldax = self.p.ax
     self.p.ax = self.p.fig.add_axes([0.02, -0.39, 1.04, 0.44])
     self.p.setmap(projection='cyl', georange=cgeorange, resolution='i')
     self.p.draw('country coastline province city')
     ###SUBPLOT: HIGHLIGHT COASTLINES & PLOT LEGEND
     colors = ['#AAFFAA', '#FFFF44', '#FF3333', '#BB0044']
     descr = ['10~25%', '25~50%', '50~75%', '>75%']
     handles = []
     for i, clr in enumerate(colors, 0):
         patch = PathCollection(geos_to_path(
             MultiLineString(highlights[i]).buffer(self.buffersize)),
                                facecolor=clr)
         self.p.ax.add_collection(patch)
         handles.append(Patch(color=clr, label=descr[i]))
     self.p.ax.text(0.98,
                    0.27,
                    '中心经过1经纬度\n范围内的几率',
                    transform=self.p.ax.transAxes,
                    va='bottom',
                    ha='right',
                    fontsize=6,
                    family='Source Han Sans CN')
     self.p.legend(handles=handles, loc='lower right', framealpha=0.8)
Exemple #2
0
def PolygonPath(shape):
    """Constructs a compound matplotlib path from a Shapely or GeoJSON-like
    geometric object"""

    if isinstance(shape, (sgeom.LineString, sgeom.Point)):
        return Path(np.vstack(shape.xy).T)

    elif isinstance(shape, sgeom.Polygon):
        codes, vertices = PolygonCodes(shape)
        return Path(vertices, codes)

    elif isinstance(
            shape,
        (sgeom.MultiPolygon, sgeom.MultiLineString, sgeom.MultiPoint)):
        codes, vertices = [], []
        for poly in shape:
            sub_codes, sub_vertices = PolygonCodes(poly)
            codes.append(sub_codes)
            vertices.append(sub_vertices)
        codes = np.concatenate(codes)
        vertices = np.concatenate(vertices)
        return Path(vertices, codes)

    elif isinstance(shape, sgeom.GeometryCollection):
        return PathCollection([PolygonPath(geom) for geom in shape.geoms])

    else:
        raise ValueError('Unsupported shape type {}.'.format(type(shape)))
Exemple #3
0
    def as_patch(self, **kwds):
        """ matplotlib pathpatch for hlines and vlines

        **pathkwds : any valid PathCollection keyword (linestyle, edgecolor)

        Notes
        -----
        First, finds coordinates of hlines, vlines.  Then, it it finds
        the x, y coords of each line; it extracts the points corresponding to
        each isoline, and makes a path for each of these."""

        hlines = zip(*np.where(self.hlines))
        vlines = zip(*np.where(self.vlines))

        xunique = set([x for x, y in hlines])
        yunique = set([y for x, y in vlines])

        hpaths = []
        vpaths = []

        # REVERSE PATHS FOR SAKE OF PLOT (y,x) !!
        for xun in xunique:
            hpaths.append(Path([(y, x) for x, y in hlines if x == xun]))

        for yun in yunique:
            vpaths.append(Path([(y, x) for x, y in vlines if y == yun]))

        return PathCollection(hpaths + vpaths, **kwds)
Exemple #4
0
 def _make_barb(self, temperature, theta, speed, angle):
     """Add the barb to the plot at the specified location."""
     u, v = self._uv(speed, angle)
     if 0 < speed < _BARB_BINS[0]:
         # Plot the missing barbless 1-2 knots line.
         length = self._kwargs['length']
         pivot_points = dict(tip=0.0, middle=-length / 2.)
         pivot = self._kwargs.get('pivot', 'tip')
         offset = pivot_points[pivot]
         verts = [(0.0, offset), (0.0, length + offset)]
         rangle = math.radians(-angle)
         verts = mtransforms.Affine2D().rotate(rangle).transform(verts)
         codes = [Path.MOVETO, Path.LINETO]
         path = Path(verts, codes)
         size = length**2 / 4
         xy = np.array([[temperature, theta]])
         barb = PathCollection([path], (size, ),
                               offsets=xy,
                               transOffset=self._transform,
                               **self._custom_kwargs)
         barb.set_transform(mtransforms.IdentityTransform())
         self.axes.add_collection(barb)
     else:
         barb = plt.barbs(temperature,
                          theta,
                          u,
                          v,
                          transform=self._transform,
                          **self._kwargs)
     return barb
def makeplot(field2plot, lon_ts, lat_ts, vmin, vmax, m, findex, shp_info):

    norm = colors.Normalize(vmin=vmin, vmax=vmax)
    bounds = np.arange(vmin, vmax + .0001, dvar)

    ax = plt.gca()
    ax.cla()

    paths = []
    for line in shp_info[4]._paths:
        paths.append(Path(line.vertices, codes=line.codes))
    coll = PathCollection(paths, linewidths=0, facecolors='black', zorder=2)
    ax.add_collection(coll)

    m.drawcoastlines(ax=ax, linewidth=0.05)
    m.drawcountries(ax=ax, linewidth=0.05)

    pcm = plt.pcolormesh(lon_ts, lat_ts, field2plot, norm=norm, cmap=cmap)
    #    cbar = plt.colorbar(pcm, norm=norm, cmap=cmap, orientation='vertical', pad=0.05, aspect=15,
    #                            shrink=0.7, extend='both')
    #    cbar.set_ticks(bounds)
    figname = str(findex).zfill(5)
    plt.savefig(figdir + figname, facecolor="black", dpi=150)
    plt.close()

    print findex

    return findex
Exemple #6
0
    def _add_bondlength_change_collection(self,
                                          index,
                                          threshold=0,
                                          zorder=20,
                                          **kwargs):
        """Comute and draw bondlength changes on the axes."""
        codes = [Path.MOVETO, Path.LINETO]
        col = []
        amp = []
        colors = []
        for obbond in ob.OBMolBondIter(self.molecule):
            atom1, atom2 = (self.molecule.GetAtom(obbond.GetBeginAtomIdx()),
                            self.molecule.GetAtom(obbond.GetEndAtomIdx()))
            atom1nc, atom2nc = [
                self._to_normal_coordinates(atom, index)
                for atom in (atom1, atom2)
            ]
            if obbond.GetLength() == 0.0:
                logger.error(
                    "Bond between %i and %i with length %.1f ignored." %
                    (atom1.GetIdx(), atom2.GetIdx(), obbond.GetLength()))
                continue
            amplitude = atom1.GetDistance(atom2) - atom1nc.GetDistance(atom2nc)
            if abs(amplitude * 100) <= threshold: continue
            amp.append(abs(amplitude * 50))
            colors.append(self.bond_colors[0 if amplitude < 0.0 else 1])

            verts = (self._2Dcoords(atom1), self._2Dcoords(atom2))
            segment = Path(verts, codes)
            col.append(segment)
        lw = 0.0 if not col else np.array(amp) * kwargs.pop("lw", 1.0)
        kw = {'edgecolors': colors, 'linewidths': lw}
        kwargs.update(kw)
        self._vib_bonds = PathCollection(col, zorder=zorder, **kwargs)
        self.axes.add_collection(self._vib_bonds)
Exemple #7
0
def plot_map_native(lon_corners, lat_corners, data, **kwargs):
    from matplotlib import pyplot, patches, path
    import numpy

    # Fix longitude coordinates; we need longitudes to run from
    # -180 to 180, not from 0 to 360
    lon_corners.values = numpy.where(lon_corners > 180, lon_corners - 360,
                                     lon_corners)

    # Loop over GLL nodes and create paths that describe the boundaries
    # of each node; collect these into a list to plot all at once
    path_list = []
    for icol in range(lon_corners.shape[0]):

        # Get corners for this node
        x_corners = lon_corners[icol, :].values
        y_corners = lat_corners[icol, :].values

        # Repeat first vertex at end of array to close the path
        x_corners = numpy.append(x_corners, x_corners[0])
        y_corners = numpy.append(y_corners, y_corners[0])

        # Create paths connecting the corners and append to list
        vertices = numpy.column_stack([x_corners, y_corners])
        path_list.append(path.Path(vertices, closed=True))

    # Plot collection of patches
    from matplotlib.collections import PathCollection
    collection = PathCollection(path_list, transform=crs.Geodetic(), **kwargs)
    collection.set_array(data)

    ax = pyplot.gca()
    pl = ax.add_collection(collection)

    return pl
Exemple #8
0
 def _get_patch_collections(self, axes):
     for key, collection in self._collection_map.items():
         marker = self._markers[key]
         coll = PathCollection([marker.get_path()],
                               offsets=collection,
                               transOffset=axes.transAxes,
                               facecolors=[self._colors[key]])
         yield coll
    def on_ax(self, ax, pos, orientation):
        trans = np.reshape(orientation, (2, 2)).T

        for offset, normal, text, size, halign, valign, color in self.texts:
            normal = np.matmul(normal, trans)
            angle = math.atan2(-normal[1], normal[0]) * 180 / math.pi

            x, y = (pos + np.matmul(offset, trans)) * Y_TRANS

            if angle >= 180 or angle < 0:
                if halign == 'right':
                    halign = 'left'
                elif halign == 'left':
                    halign = 'right'
                if valign == 'top':
                    valign = 'bottom'
                elif valign == 'bottom':
                    valign = 'top'
                angle -= 180

            kw = {
                'x': x,
                'y': y,
                'color': color,
                #                               'font': 'sans-serif',
                'fontsize': size,
                's': text,
                'rotation': angle,
                'rotation_mode': 'anchor',
                'horizontalalignment': halign,
                'verticalalignment': valign,
                'clip_on': True,
            }

            ax.text(**kw)

        if self.paths:
            d = {}
            d['paths'] = []
            d['linewidths'] = []
            d['edgecolors'] = []
            d['facecolors'] = []

            for path, linewidth, edgecolor, facecolor in self.paths:
                verts = path.vertices
                verts = np.matmul(verts, trans)
                verts = (pos + verts) * Y_TRANS
                path.vertices = verts

                d['paths'].append(path)
                d['linewidths'].append(linewidth)
                d['edgecolors'].append(edgecolor)
                d['facecolors'].append(facecolor)

            pc = PathCollection(offset_position='data', **d)
            ax.add_collection(pc)
Exemple #10
0
    def plot(self,
             *,
             ax,
             color,
             lw=2,
             n=30000,
             fuzz=3,
             rot=None,
             rot_point=None,
             **kwargs):
        """Add this plot to the axis.

        Parameters
        ----------
        ax: Axes
            Matplotlib axis to add the art to
        color: str
            Color to use. Must be readable by `matplotlib.colors.to_rgba`. Can be
            something like "black", "k", or "#ffffff".
        lw: float > 0
            Linewidth to use for chords
        n: int > 0
            Number of chords to use
        fuzz: float > 0
            How ragged edges should be
        rot: float
            How much to rotate the shape, in radians
        rot_point: ndarray (optional)
            What point to rotate the shape around (default is the center)
        kwargs:
            Passed to `PathCollection`

        Returns
        -------
        None
        """
        color = np.array(to_rgba(color)) * 255
        colors = np.tile(color.reshape(-1, 1), n).T
        colors[:, :3] += np.random.randint(-50, 50, (n, 3))

        colors = np.minimum(255, np.maximum(0, colors)) / 255
        alpha = kwargs.pop("alpha", 0.05)
        colors[:, -1] = alpha
        ax.add_collection(
            PathCollection(
                [
                    Path(p) for p in self.gen_points(
                        n=n, fuzz=fuzz, rot=rot, rot_point=rot_point)
                ],
                linewidths=lw,
                edgecolors=colors,
                facecolors="none",
                **kwargs,
            ))
Exemple #11
0
    def _add_oop_angle_change_collection(self,
                                         index,
                                         threshold=0,
                                         CURVE_TYPE=4,
                                         zorder=50,
                                         **kwargs):
        """Compute and draw torsion changes on the axes."""
        CURVE_TYPE_3, CURVE_TYPE_4 = 3, 4
        col = []
        edgecolors = []
        if CURVE_TYPE is CURVE_TYPE_3:
            codes = [
                Path.MOVETO,
                Path.CURVE3,
                Path.CURVE3,
            ]
        elif CURVE_TYPE is CURVE_TYPE_4:
            codes = [
                Path.MOVETO,
                Path.CURVE4,
                Path.CURVE4,
                Path.CURVE4,
            ]
        for torsion in ob.OBMolTorsionIter(self.molecule):
            atoms = [self.molecule.GetAtom(idx + 1) for idx in torsion]
            atomsnc = [
                self._to_normal_coordinates(atom, index) for atom in atoms
            ]
            teq = self.molecule.GetTorsion(*atoms)
            tnc = self.molecule.GetTorsion(*atomsnc)
            amplitude = (tnc - teq + 360.0) % 360.0
            if amplitude > 180.0:
                amplitude -= 360.0
            if abs(amplitude) <= threshold: continue
            intensity = abs(amplitude / 40)

            a, b, c, d = [self._2Dcoords(atom) for atom in atoms]
            p2 = 0.5 * (b + c)  # middle
            p1 = intensity * (a - p2) + p2
            p3 = intensity * (d - p2) + p2
            color = self.oop_colors[0 if amplitude < 0.0 else 1]
            if CURVE_TYPE is CURVE_TYPE_3:
                verts = [p1, p2, p3]
            elif CURVE_TYPE is CURVE_TYPE_4:
                verts = [p1, b, c, p3]
            curve = Path(verts, codes)
            col.append(curve)
            edgecolors.append(color)
        kw = {'edgecolors': edgecolors, 'facecolors': 'none'}
        kwargs.update(kw)
        self._vib_oop = PathCollection(col, zorder=zorder, **kwargs)
        self.axes.add_collection(self._vib_oop)
Exemple #12
0
 def __init__(self, n=100, marker=triangle):
     v, c = marker
     v, c = np.array(v), np.array(c)
     self._marker = marker
     self._base_vertices = np.tile(v.reshape(-1), n).reshape(n, len(v), 2)
     self._vertices = np.tile(v.reshape(-1), n).reshape(n, len(v), 2)
     self._codes = np.tile(c.reshape(-1), n)
     self._scale = np.ones(n)
     self._translate = np.zeros((n, 2))
     self._rotate = np.zeros(n)
     self._path = Path(vertices=self._vertices.reshape(n*len(v), 2),
                       codes=self._codes)
     self._collection = PathCollection(
         [self._path], facecolor="white", edgecolor="black")
Exemple #13
0
    def plot(self,
             ax=None,
             unfilled=(4, 5),
             edgecolors='k',
             facecolors=(0.75, 0.75, 0.75)):
        from matplotlib.path import Path
        from matplotlib.collections import PathCollection

        ax = get_axes(ax, xlab="R (m)", ylab="z (m)")
        ax.set_aspect('equal')
        ax.set_xlim((0.5, 2.5))
        ax.set_ylim((-1.5, 1.5))

        paths = [Path(xy) for i, xy in enumerate(self.xy) if i not in unfilled]
        pc = PathCollection(paths,
                            facecolors=facecolors,
                            edgecolors=edgecolors)
        ax.add_collection(pc)

        paths = [Path(self.xy[i]) for i in unfilled]
        pc = PathCollection(paths, facecolors='none', edgecolors=edgecolors)
        ax.add_collection(pc)
        return ax
Exemple #14
0
 def _add_spectrum_collection(self, **kwargs):
     """Draw spectrum on the axes."""
     codes = [
         Path.MOVETO,
         Path.LINETO,
     ]
     col = []
     for frequency, intensity in zip(self.frequencies, self.intensities):
         verts = [(frequency, 0.0), (frequency, intensity)]
         col.append(Path(verts, codes))
     kw = {}
     kwargs.update(kw)
     self._spectrum = PathCollection(col, **kwargs)
     self.axes.add_collection(self._spectrum)
Exemple #15
0
    def __init__(self, n=100):
        v = np.array([(-0.25, -0.25), (+0.0, +0.5), (+0.25, -0.25), (0, 0)])
        c = np.array([Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])
        self._base_vertices = np.tile(v.reshape(-1), n).reshape(n, len(v), 2)
        self._vertices = np.tile(v.reshape(-1), n).reshape(n, len(v), 2)
        self._codes = np.tile(c.reshape(-1), n)

        self._scale = np.ones(n)
        self._translate = np.zeros((n, 2))
        self._rotate = np.zeros(n)

        self._path = Path(vertices=self._vertices.reshape(n*len(v), 2),
                          codes=self._codes)
        self._collection = PathCollection([self._path], linewidth=0.5,
                                          facecolor="k", edgecolor="w")
Exemple #16
0
 def _add_bond_collection(self, zorder=10, **kwargs):
     """Draw molecule skeleton on the axes."""
     col = []
     codes = [
         Path.MOVETO,
         Path.LINETO,
     ]  # segment
     for obbond in ob.OBMolBondIter(self.molecule):
         atom1, atom2 = (self.molecule.GetAtom(obbond.GetBeginAtomIdx()),
                         self.molecule.GetAtom(obbond.GetEndAtomIdx()))
         verts = self._2Dcoords(atom1), self._2Dcoords(atom2)
         segment = Path(verts, codes)
         col.append(segment)
     kw = {'edgecolors': 'k'}
     kwargs.update(kw)
     self._mol_bonds = PathCollection(col, zorder=zorder, **kwargs)
     self.axes.add_collection(self._mol_bonds)
Exemple #17
0
def makeplot(field2plot, lon_ts, lat_ts, vmin, vmax, m, findex, shp_info):

    norm = colors.Normalize(vmin=vmin, vmax=vmax)
    bounds = np.arange(vmin, vmax + .0001, dvar)

    #fig = plt.figure()
    #ax = fig.add_subplot(111)
    ax = plt.gca()
    ax.cla()

    paths = []
    for line in shp_info[4]._paths:
        paths.append(Path(line.vertices, codes=line.codes))
    coll = PathCollection(paths, linewidths=0, facecolors='grey', zorder=2)
    ax.add_collection(coll)

    m.drawcoastlines(ax=ax, linewidth=0.05)
    m.drawcountries(ax=ax, linewidth=0.05)

    # m.fillcontinents(color = 'gray')
    # m.drawmapboundary()
    #    m.drawparallels(np.arange(round(coordinates[2]), coordinates[3], dlat), linewidth=0.,
    #                    labels=[1, 0, 0, 0], fontname='Times New Roman', fontsize=16, zorder=1)
    #    m.drawmeridians(np.arange(round(coordinates[0]), coordinates[1], dlon), linewidth=0.,
    #                    labels=[0, 0, 0, 1], fontname='Times New Roman', fontsize=16, zorder=1)

    # u2plot = u[tt, ::NN, ::NN].squeeze()
    # v2plot = v[tt, ::NN, ::NN].squeeze()
    # speed = np.sqrt(u2plot*u2plot + v2plot*v2plot)
    # speed = np.ma.masked_greater(speed, 1.5)

    pcm = plt.pcolormesh(lon_ts, lat_ts, field2plot, norm=norm, cmap=cmap)

    #    cbar = plt.colorbar(pcm, norm=norm, cmap=cmap, orientation='vertical', pad=0.05, aspect=15,
    #                            shrink=0.7, extend='both')
    #    cbar.set_ticks(bounds)
    figname = str(findex).zfill(5)
    plt.savefig(figdir + figname, dpi=200)
    plt.close()

    print findex

    return findex
Exemple #18
0
    def get_patches(self, ax):
        ranges = LineCollection(self._cap_ranges, linestyle="solid")
        links = LineCollection(self._oob_links,
                               linestyle="dotted",
                               colors=colorConverter.to_rgba_array("#808080"))

        color = colorConverter.to_rgba_array("#DC143C")
        scales = np.array((20, ))
        marker_obj = MarkerStyle("o")
        path = marker_obj.get_path().transformed(marker_obj.get_transform())

        offsets = PathCollection((path, ),
                                 scales,
                                 facecolors=color,
                                 offsets=self._oob_offsets,
                                 transOffset=ax.transData)
        offsets.set_transform(IdentityTransform())

        return [ranges, links, offsets]
Exemple #19
0
def _generate_node_artist(pos, styles, *, ax):
    N = len(pos)
    proto_node = next(iter(pos))

    x = np.zeros(N) * np.nan
    y = np.zeros(N) * np.nan
    properties = {
        k: [None] * N
        for k in styles[proto_node] if k in _VALID_NODE_STYLE
    }

    for j, node in enumerate(pos):
        x[j], y[j] = pos[node]
        for key, values in properties.items():
            values[j] = styles[node][key]

    key_map = {
        'size': 'sizes',
        'color': 'facecolors',
        'shape': 'marker',
        'width': 'linewidths',
        'edgecolor': 'edgecolors'
    }
    renamed_properties = {key_map[k]: v for k, v in properties.items()}

    markers = renamed_properties.pop('marker', None)

    if markers is None:
        paths = (MarkerStyle('o'), )
    else:
        paths = [MarkerStyle(m) for m in markers]
    paths = [p.get_path().transformed(p.get_transform()) for p in paths]

    offsets = np.column_stack([x, y])
    node_art = PathCollection(paths,
                              offsets=offsets,
                              transOffset=ax.transData,
                              **renamed_properties)
    node_art.set_transform(mtransforms.IdentityTransform())

    ax.add_collection(node_art)
    ax.autoscale_view()
    return node_art
Exemple #20
0
    def my_scatter(self, ax, x, y):
        from matplotlib.collections import PathCollection
        from matplotlib.path import Path
        import matplotlib.transforms as mtransforms

        phi = np.linspace(0, 2 * np.pi, 100)
        # Scale, in pixel coordinates
        rad = 2
        x_circle = np.cos(phi) * rad
        y_circle = np.sin(phi) * rad

        verts = np.vstack([x_circle, y_circle]).T
        path = Path(verts, closed=False)
        collection = PathCollection(
            [path],
            facecolor='blue',
            edgecolor='black',
            transOffset=ax.transData,
        )
        collection.set_transform(mtransforms.IdentityTransform())
        ax.add_collection(collection, autolim=True)

        ax.autoscale()
Exemple #21
0
px = np.random.rand(10)
py = np.random.rand(10)

offsets = np.ma.column_stack([px, py])

#%% 1
fig, ax = plt.subplots()

reduction = 50
c = Path.unit_circle()
c = c.transformed(Affine2D().scale(0.5 * reduction))

collection = PathCollection(
    (c,), offsets=offsets, 
    transOffset = ax.transData,
    edgecolor='black', 
    facecolor=(0, 0, 0, .0125),
    linewidth=1
)

collection.set_transform(IdentityTransform())
ax.add_collection( collection )

#%% 2

collection.set_path_effects([withStroke(linewidth=5, foreground='r')])
collection.set_path_effects([])
collection.get_path_effects()


Exemple #22
0
            'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
            'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
            'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar'])]

colormaplist = sum([x[1] for x in colormap_from_reference],[])

#
#  Artist may not reture the same value as given by setter...
#  Also, matplotlib has a routine to get a list of valid property values.
#  With get_valid_values, it may be possible to implement more automatic
#  property list generation.
#
#  The following is an initial attempt. Needs to check more how well
#  matplotlib is organized in this aspect.

obj = PathCollection(Path.unit_rectangle())
#plinestylelist, plinestyle_rlist = artist_property_checker(obj, 'linestyle')
pedgecolorlist, pedgecolor_rlist = artist_property_checker(
    obj, 'edgecolor', values="'"+"','".join(collist)+"'")
plinestylelist = ['solid', 'dotted', 'dashed', 'dashdot']
plinestyle_rlist = ['solid', 'dotted', 'dashed', 'dashdot']
if isMPL2:
    plinestylelist = plinestylelist[:4]
    plinestyle_rlist = plinestyle_rlist[:4]


def colormap_list():
    return colormaplist


def scratch_file():
Exemple #23
0
    which = values > 1.

    for shp_link in [shp_link]:

        fig = plt.figure()
        patchco = map_poly_shp(shp_link)
        patchcoB = map_poly_shp(shp_link, which=which)
        patchco.set_facecolor('none')
        ax = setup_ax([patchco, patchcoB])
        fig.add_axes(ax)
        plt.show()
        break
    '''

    xy = (((0, 0), (0, 0)), ((2, 1), (2, 1)), ((3, 1), (3, 1)), ((2, 5), (2,
                                                                          5)))
    xy = np.array([[10, 30], [20, 20]])
    markerobj = mpl.markers.MarkerStyle('o')
    path = markerobj.get_path().transformed(markerobj.get_transform())
    scales = np.array([2, 2])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    pc = PathCollection((path,), scales, offsets=xy, \
            facecolors='r', transOffset=mpl.transforms.IdentityTransform())
    #pc.set_transform(mpl.transforms.IdentityTransform())
    #_ = _add_axes2col(pc, [0, 0, 5, 5])
    ax.add_collection(pc)
    fig.add_axes(ax)
    #ax = setup_ax([pc], ax)
    plt.show()
Exemple #24
0
    def __init__(self, n=100, angle=0, radius=0):
        v = np.array([(-0.25, -0.25), (+0.0, +0.5), (+0.25, -0.25), (0, 0)])
        c = np.array([Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])
        self._base_vertices = np.tile(v.reshape(-1), n).reshape(n, len(v), 2)
        self._vertices = np.tile(v.reshape(-1), n).reshape(n, len(v), 2)
        self._codes = np.tile(c.reshape(-1), n)

        self._scale = np.ones(n)
        self._translate = np.zeros((n, 2))
        self._rotate = np.zeros((n, 2))

        self._path = Path(vertices=self._vertices.reshape(n * len(v), 2),
                          codes=self._codes)

        self.cone = True if angle else False

        if self.cone:

            # viewing cone
            angles = [-angle / 2, -angle / 4, 0, angle / 4, angle / 2]

            #cos_ang = np.cos(angle/2)
            #sin_ang = np.sin(angle/2)
            #cos_ang2 = np.cos(angle/4)
            #sin_ang2 = np.sin(angle/4)
            bl = np.tan(angle / np.pi) * 4 / 3 * np.sqrt(radius) / np.pi
            v_cone = []
            for a in angles:
                cos_ang = np.cos(a)
                sin_ang = np.sin(a)
                v_cone.append((sin_ang * radius - cos_ang * bl,
                               cos_ang * radius + sin_ang * bl))
                v_cone.append((sin_ang * radius, cos_ang * radius))
                v_cone.append((sin_ang * radius + cos_ang * bl,
                               cos_ang * radius - sin_ang * bl))
            v_cone = np.array([(0, 0)] + v_cone[1:-1] + [(0, 0)])

            #v_cone = np.array([(+0.0, +0.0),

            #    (-sin_ang*radius, cos_ang*radius),
            #    (-sin_ang*radius + cos_ang*bl, cos_ang*radius + sin_ang*bl),

            #    (-sin_ang2*radius -cos_ang2*bl, cos_ang2*radius -sin_ang2*bl),
            #    (-sin_ang2*radius, cos_ang2*radius),
            #    (0,0),
            #    (-sin_ang2*radius, cos_ang2*radius),
            #    (-sin_ang2*radius + cos_ang2*bl, cos_ang2*radius + sin_ang2*bl),

            #    (-bl, radius),
            #    (0.,radius),
            #    (bl, radius),

            #    (sin_ang2*radius - cos_ang2*bl, cos_ang2*radius + sin_ang2*bl),
            #    (sin_ang2*radius, cos_ang2*radius),
            #    (sin_ang2*radius + cos_ang2*bl, cos_ang2*radius - sin_ang2*bl),

            #    (sin_ang*radius - cos_ang*bl, cos_ang*radius + sin_ang*bl),
            #    (sin_ang*radius, cos_ang*radius),

            #    (0,0)])
            c_cone = np.array([
                Path.MOVETO, Path.LINETO, Path.CURVE4, Path.CURVE4,
                Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4,
                Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4,
                Path.CURVE4, Path.CURVE4, Path.CLOSEPOLY
            ])
            #c_cone = np.array([Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])
            self._base_vertices_cone = np.tile(v_cone.reshape(-1),
                                               n).reshape(n, len(v_cone), 2)
            self._vertices_cone = np.tile(v_cone.reshape(-1),
                                          n).reshape(n, len(v_cone), 2)
            self._codes_cone = np.tile(c_cone.reshape(-1), n)

            self._path_cone = Path(vertices=self._vertices_cone.reshape(
                n * len(v_cone), 2),
                                   codes=self._codes_cone)

            self._collection = PathCollection([self._path, self._path_cone],
                                              linewidths=[0.5, 0.1],
                                              facecolors=["k", (0, 0, 0, 0)],
                                              edgecolors=["w", "b"])
        else:
            self._collection = PathCollection([self._path],
                                              linewidth=0.5,
                                              facecolor="k",
                                              edgecolor="w")
    angle2 = angle1 + np.random.randint(180, 270)
    path = mpath.Path.wedge(angle1, angle2)
    verts, codes = path.vertices * .25, path.codes
    path = mpath.Path(verts, codes)
    paths.append(path)

offsets = np.ones((n, 2))
offsets[:, 0], offsets[:, 1] = np.linspace(1, 10, n) + .2, y
X, Y = offsets[:, 0], offsets[:, 1]
sizes = np.ones(n) / 100
offsets[:, 1] -= sizes / 2 - .125
facecolors = ['%.1f' % c for c in np.linspace(0.25, 0.75, n)]
collection = PathCollection(paths,
                            sizes=None,
                            linewidths=1.0,
                            facecolors=facecolors,
                            edgecolor="black",
                            offsets=offsets - (0.2, -0.25),
                            transOffset=ax.transData)
ax.add_collection(collection)
ax.text(1 - 0.25,
        y + 0.35,
        "Path collection",
        size="small",
        ha="left",
        va="baseline")
ax.text(10 + 0.25,
        y + 0.35,
        "PathCollection",
        color="blue",
        size="small",
Exemple #26
0
def plot_beachball_mpl(
        mt, axes,
        beachball_type='deviatoric',
        position=(0., 0.),
        size=None,
        zorder=0,
        color_t='red',
        color_p='white',
        edgecolor='black',
        linewidth=2,
        alpha=1.0,
        projection='lambert',
        size_units='points'):

    '''
    Plot beachball diagram to a Matplotlib plot

    :param mt: :py:class:`pyrocko.moment_tensor.MomentTensor` object or an
        array or sequence which can be converted into an MT object
    :param beachball_type: ``'deviatoric'`` (default), ``'full'``, or ``'dc'``
    :param position: position of the beachball in data coordinates
    :param size: diameter of the beachball either in points or in data
        coordinates, depending on the ``size_units`` setting
    :param zorder: (passed through to matplotlib drawing functions)
    :param color_t: color for compressional quadrants (default: ``'red'``)
    :param color_p: color for extensive quadrants (default: ``'white'``)
    :param edgecolor: color for lines (default: ``'black'``)
    :param linewidth: linewidth in points (default: ``2``)
    :param alpha: (passed through to matplotlib drawing functions)
    :param projection: ``'lambert'`` (default), ``'stereographic'``, or
        ``'orthographic'``
    :param size_units: ``'points'`` (default) or ``'data'``, where the
        latter causes the beachball to be projected in the plots data
        coordinates (axes must have an aspect ratio of 1.0 or the
        beachball will be shown distorted when using this).
    '''

    transform, position, size = choose_transform(
        axes, size_units, position, size)

    mt = deco_part(mt, beachball_type)

    eig = mt.eigensystem()
    if eig[0] == 0. and eig[1] == 0. and eig[2] == 0:
        raise BeachballError('eigenvalues are zero')

    data = []
    for (group, patches, patches_lower, patches_upper,
            lines, lines_lower, lines_upper) in eig2gx(eig):

        if group == 'P':
            color = color_p
        else:
            color = color_t

        # plot "upper" features for lower hemisphere, because coordinate system
        # is NED

        for poly in patches_upper:
            verts = project(poly, projection)[:, ::-1] * size + position[NA, :]
            if alpha == 1.0:
                data.append((Path(verts), color, color, linewidth))
            else:
                data.append((Path(verts), color, 'none', 0.0))

        for poly in lines_upper:
            verts = project(poly, projection)[:, ::-1] * size + position[NA, :]
            data.append((Path(verts), 'none', edgecolor, linewidth))

    paths, facecolors, edgecolors, linewidths = zip(*data)
    path_collection = PathCollection(
        paths,
        facecolors=facecolors,
        edgecolors=edgecolors,
        linewidths=linewidths,
        alpha=alpha,
        zorder=zorder,
        transform=transform)

    axes.add_artist(path_collection)
Exemple #27
0
 def as_path_collection(self, **kw):
     kw.setdefault('facecolors', 'none')
     kw.setdefault('edgecolors', 'b')
     kw.setdefault('linewidth', 2)
     paths = [Path(self.y[:, :2])]
     return PathCollection(paths, **kw)
Exemple #28
0
cols = []
#서울 구별 인구수 반영 그림 그리기
fig = plt.figure()
ax = plt.gca()
for x in range(len(seoul)):
    coord = seoul[x]['geometry']
    verts = coord['coordinates'][0]
    patch = Polygon.Polygon(
        verts,
        facecolor=seoulcolor[seoul[x]['properties']['SIG_KOR_NM']],
        ec='k')
    cols.append(patch)
    ax.add_patch(patch)
plt.autoscale()
plt.axis('off')
p = PathCollection(cols, cmap=cm.Blues)
p.set_array(np.array(colors))
ax.add_collection(p)
ax.autoscale_view()
plt.colorbar(p)
plt.show()

#Draw Heat Map

dx, dy = 0.15, 0.05

y, x = np.mgrid[slice(-3, 3 + dy, dy), slice(-3, 3 + dx, dx)]
z = (1 - x / 2. + x**5 + y**3) * np.exp(-x**2 - y**2)
z = z[:-1, :-1]
z_min, z_max = -np.abs(z).max(), np.abs(z).max()
Exemple #29
0
def draw_networkx_nodes(
    G,
    pos,
    nodelist=None,
    node_size=300,
    node_color="#1f78b4",
    node_shape="o",
    alpha=None,
    cmap=None,
    vmin=None,
    vmax=None,
    ax=None,
    linewidths=None,
    edgecolors=None,
    label=None,
):
    """Draw the nodes of the graph G.

    This draws only the nodes of the graph G.

    Parameters
    ----------
    G : graph
       A networkx graph

    pos : dictionary
       A dictionary with nodes as keys and positions as values.
       Positions should be sequences of length 2.

    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.

    nodelist : list, optional
       Draw only specified nodes (default G.nodes())

    node_size : scalar or array
       Size of nodes (default=300).  If an array is specified it must be the
       same length as nodelist.

    node_color : color or array of colors (default='#1f78b4')
       Node color. Can be a single color or a sequence of colors with the same
       length as nodelist. Color can be string, or rgb (or rgba) tuple of
       floats from 0-1. If numeric values are specified they will be
       mapped to colors using the cmap and vmin,vmax parameters. See
       matplotlib.scatter for more details.

    node_shape :  string
       The shape of the node.  Specification is as matplotlib.scatter
       marker, one of 'so^>v<dph8' (default='o').

    alpha : float or array of floats
       The node transparency.  This can be a single alpha value (default=None),
       in which case it will be applied to all the nodes of color. Otherwise,
       if it is an array, the elements of alpha will be applied to the colors
       in order (cycling through alpha multiple times if necessary).

    cmap : Matplotlib colormap
       Colormap for mapping intensities of nodes (default=None)

    vmin,vmax : floats
       Minimum and maximum for node colormap scaling (default=None)

    linewidths : [None | scalar | sequence]
       Line width of symbol border (default =1.0)

    edgecolors : [None | scalar | sequence]
       Colors of node borders (default = node_color)

    label : [None| string]
       Label for legend

    Returns
    -------
    matplotlib.collections.PathCollection
        `PathCollection` of the nodes.

    Examples
    --------
    >>> G = nx.dodecahedral_graph()
    >>> nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))

    Also see the NetworkX drawing examples at
    https://networkx.github.io/documentation/latest/auto_examples/index.html

    See Also
    --------
    draw()
    draw_networkx()
    draw_networkx_edges()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    from collections.abc import Iterable

    try:
        import matplotlib.pyplot as plt
        from matplotlib.collections import PathCollection
        import numpy as np
    except ImportError as e:
        raise ImportError("Matplotlib required for draw()") from e
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

    if ax is None:
        ax = plt.gca()

    if nodelist is None:
        nodelist = list(G)

    if len(nodelist) == 0:  # empty nodelist, no drawing
        return PathCollection(None)

    try:
        xy = np.asarray([pos[v] for v in nodelist])
    except KeyError as e:
        raise nx.NetworkXError(f"Node {e} has no position.") from e
    except ValueError as e:
        raise nx.NetworkXError("Bad value in node positions.") from e

    if isinstance(alpha, Iterable):
        node_color = apply_alpha(node_color, alpha, nodelist, cmap, vmin, vmax)
        alpha = None

    node_collection = ax.scatter(
        xy[:, 0],
        xy[:, 1],
        s=node_size,
        c=node_color,
        marker=node_shape,
        cmap=cmap,
        vmin=vmin,
        vmax=vmax,
        alpha=alpha,
        linewidths=linewidths,
        edgecolors=edgecolors,
        label=label,
    )
    ax.tick_params(
        axis="both",
        which="both",
        bottom=False,
        left=False,
        labelbottom=False,
        labelleft=False,
    )

    node_collection.set_zorder(2)
    return node_collection
Exemple #30
0
m = Basemap(projection='cyl',llcrnrlat=-10,urcrnrlat=70,\
        llcrnrlon=-140,urcrnrlon=-40,resolution='c')
shp_info = m.readshapefile(
    '/home/s1251441/Python/landfile/land/ne_10m_land_scale_rank',
    'scalerank',
    drawbounds=True)
ax = plt.gca()
ax.cla()

paths = []
for line in shp_info[4]._paths:
    paths.append(Path(line.vertices, codes=line.codes))

coll = PathCollection(paths,
                      linewidths=0.5,
                      zorder=0,
                      facecolors='black',
                      color='grey')

##    m = Basemap(projection='robin',lon_0=0,resolution='c')
##    m = Basemap(projection='ortho',lon_0=-90,lat_0=90,resolution='c')
m = Basemap(projection='cyl',llcrnrlat=20,urcrnrlat=80,\
        llcrnrlon=-160,urcrnrlon=-40,resolution='c')
# drawing something seems necessary to 'initiate' the map properly
m.drawcoastlines(color='black', zorder=0, linewidth=0)
m.drawcountries(color='black', zorder=0, linewidth=0)
m.drawparallels(np.arange(-90., 90., 10.), linewidth=0.5, labels=[1, 1, 0, 0])
m.drawmeridians(np.arange(0., 360., 20.), linewidth=0.5, labels=[0, 0, 1, 1])
##
##m.bluemarble()
ax = plt.gca()