Exemple #1
0
def plot_prediction_over_epochs_plt():
    """
    Plots the polygon generated by generate_vertices() using matplotlib.
    """
    generate_vertices()
    results_dir = '../results/UKDALE-RNN-lr=1e-5-2018-01-26 14:33:59'
    verts = pickle.load(open(os.path.join(results_dir, 'vertices.pkl'), 'rb'))
    zs = pickle.load(open(os.path.join(results_dir, 'zs.pkl'), 'rb'))
    ys = pickle.load(open(os.path.join(results_dir, 'ys.pkl'), 'rb'))

    fig = plt.figure(figsize=(18, 8))
    ax = fig.gca(projection='3d')

    poly = PolyCollection(verts[::], facecolors='w')
    poly.set_edgecolor((0, 0, 0, .5))
    poly.set_facecolor((.9, .9, 1, 0.3))
    ax.add_collection3d(poly, zs=zs[::], zdir='y')

    ax.set_xlabel('timestamps')
    ax.set_xlim3d(0, ys.shape[0])
    ax.set_ylabel('epochs')
    ax.set_ylim3d(0, 320)
    ax.set_zlabel('power')
    ax.set_zlim3d(0, 2000)
    ax.view_init(-40, -94)

    plt.savefig(os.path.join(results_dir, 'prediction_over_epochs.png'))
Exemple #2
0
def plotmesh_SubTh2simp2D(q, me, **kwargs):
    lim = kwargs.pop('lim', True)
    color = check_color(kwargs.pop('color', 'Blue'))
    kwargs['edgecolor'] = check_color(kwargs.pop('edgecolor', color))
    facecolor = check_color(kwargs.pop('facecolor', None))
    if facecolor is None:
        facecolor = 'none'
    z = kwargs.pop('z', None)
    if z is None:
        fig = plt.gcf()
        ax = fig.gca()
        polys = PolyCollection(q[me], **kwargs)
        polys.set_facecolor(facecolor)
        coll = ax.add_collection(polys)
        if lim:
            box = np.array([
                np.min(q[:, 0]),
                np.max(q[:, 0]),
                np.min(q[:, 1]),
                np.max(q[:, 1])
            ])
            set_axes(ax, box)
        return coll
        #return plt.triplot(q[:,0],q[:,1],triangles=me,**kwargs)
    nq = q.shape[0]
    assert isinstance(z, np.ndarray) and z.shape[0] == nq
    z.resize((nq, 1))
    return plotmesh_SubTh2simp3D(np.concatenate((q, z), axis=1),
                                 me,
                                 lim=lim,
                                 **kwargs)
Exemple #3
0
def plot_triangles(p,
                   adjustLowerLeft=False,
                   values=None,
                   values_cmap=matplotlib.cm.jet,
                   edgecolors='k'):
    """ Add mesh triangles to a pyplot plot
        
       @param p = object holding sww vertex information (from util.get_output)
       @param adjustLowerLeft = if TRUE, use spatial coordinates, otherwise use ANUGA internal coordinates     
       @param values = list or array of length(p.vols), or None. All triangles are assigned this value (for face plotting colors).
       @param values_cmap = colormap for faces [e.g. values_cmap = matplotlib.cm.get_cmap('spectral')]
       @param edgecolors = edge color for polygons (using matplotlib.colors notation). Use 'none' for no color
    """
    import matplotlib
    from matplotlib import pyplot as pyplot
    from matplotlib.collections import PolyCollection

    x0 = p.xllcorner
    y0 = p.yllcorner

    # Make vertices for PolyCollection Object
    vertices = []
    for i in range(len(p.vols)):
        k1 = p.vols[i][0]
        k2 = p.vols[i][1]
        k3 = p.vols[i][2]

        tri_coords = numpy.array([[p.x[k1], p.y[k1]], [p.x[k2], p.y[k2]],
                                  [p.x[k3], p.y[k3]]])
        if adjustLowerLeft:
            tri_coords[:, 0] = tri_coords[:, 0] + x0
            tri_coords[:, 1] = tri_coords[:, 1] + y0

        vertices.append(tri_coords)

    # Make PolyCollection
    if values is None:
        all_poly = PolyCollection(vertices,
                                  array=numpy.zeros(len(vertices)),
                                  edgecolors=edgecolors)
        all_poly.set_facecolor('none')
    else:
        try:
            lv = len(values)
        except:
            values = numpy.array(len(p.vols) * [values])
            lv = len(values)

        msg = 'len(values) must be the same as len(p.vols) (or values can be a constant)'
        assert lv == len(p.vols), msg
        all_poly = PolyCollection(vertices,
                                  array=values,
                                  cmap=values_cmap,
                                  edgecolors=edgecolors)

    # Add to plot
    # FIXME: To see the triangles, this might require that the user does
    # something else to the plot?
    pyplot.gca().add_collection(all_poly)
Exemple #4
0
def plot_grid_2d(g, cell_value, ax, **kwargs):
    """
    Plot the 2d grid g to the axis ax, with cell_value represented by the cell coloring.
    keywargs: Keyword arguments:
        color_map: Limits of the cell value color axis.
        linewidth: Width of faces in 2d and edges in 3d.
        rgb: Color map weights. Defaults to [1, 0, 0].
        alpha: Transparency of the plot.
        cells: boolean array with length number of cells. Only plot cells c
               where cells[c]=True
    """
    faces, _, _ = sps.find(g.cell_faces)
    nodes, _, _ = sps.find(g.face_nodes)

    alpha = kwargs.get("alpha", 1)
    if kwargs.get("color_map"):
        scalar_map = kwargs["color_map"]

        @pp.time_logger(sections=module_sections)
        def color_face(value):
            return scalar_map.to_rgba(value, alpha)

    else:
        cell_value = np.zeros(g.num_cells)
        rgb = kwargs.get("rgb", [1, 0, 0])

        @pp.time_logger(sections=module_sections)
        def color_face(value):
            return np.r_[rgb, alpha]

    cells = kwargs.get("cells", np.ones(g.num_cells, dtype=bool))
    for c in np.arange(g.num_cells):
        if not cells[c]:
            continue
        loc_f = slice(g.cell_faces.indptr[c], g.cell_faces.indptr[c + 1])
        faces_loc = faces[loc_f]

        loc_n = g.face_nodes.indptr[faces_loc]
        pts_pairs = np.array([nodes[loc_n], nodes[loc_n + 1]])
        sorted_nodes, _ = pp.utils.sort_points.sort_point_pairs(pts_pairs)
        ordering = sorted_nodes[0, :]

        pts = g.nodes[:, ordering]
        linewidth = kwargs.get("linewidth", 1)
        if kwargs.get("plot_2d", False):
            poly = PolyCollection([pts[:2].T], linewidth=linewidth)
            poly.set_edgecolor("k")
            poly.set_facecolor(color_face(cell_value[c]))
            ax.add_collection(poly)
        else:
            poly = Poly3DCollection([pts.T], linewidth=linewidth)
            poly.set_edgecolor("k")
            poly.set_facecolors(color_face(cell_value[c]))
            ax.add_collection3d(poly)

    if not kwargs.get("plot_2d", False):
        ax.view_init(90, -90)
Exemple #5
0
    def plot_box(box, proc, fig, ax):
        if sim.structure.gv.dim == 2:
            low = mp.Vector3(box.low.x, box.low.y, box.low.z)
            high = mp.Vector3(box.high.x, box.high.y, box.high.z)
            points = [low, high]

            x_len = mp.Vector3(high.x) - mp.Vector3(low.x)
            y_len = mp.Vector3(y=high.y) - mp.Vector3(y=low.y)
            xy_len = mp.Vector3(high.x, high.y) - mp.Vector3(low.x, low.y)

            points += [low + x_len]
            points += [low + y_len]
            points += [low + xy_len]
            points += [high - x_len]
            points += [high - y_len]
            points += [high - xy_len]
            points = np.array([np.array(v) for v in points])

            edges = [
                [points[0], points[2], points[4], points[3]],
                [points[1], points[5], points[7], points[6]],
                [points[0], points[3], points[5], points[7]],
                [points[1], points[4], points[2], points[6]],
                [points[3], points[4], points[1], points[5]],
                [points[0], points[7], points[6], points[2]]
            ]

            faces = Poly3DCollection(edges, linewidths=1, edgecolors='k')
            color_with_alpha = matplotlib.colors.to_rgba(chunk_colors[proc], alpha=0.2)
            faces.set_facecolor(color_with_alpha)
            ax.add_collection3d(faces)

            # Plot the points themselves to force the scaling of the axes
            ax.scatter(points[:, 0], points[:, 1], points[:, 2], s=0)
        else:
            low = mp.Vector3(box.low.x, box.low.y)
            high = mp.Vector3(box.high.x, box.high.y)
            points = [low, high]

            x_len = mp.Vector3(high.x) - mp.Vector3(low.x)
            y_len = mp.Vector3(y=high.y) - mp.Vector3(y=low.y)

            points += [low + x_len]
            points += [low + y_len]
            points = np.array([np.array(v)[:-1] for v in points])

            edges = [
                [points[0], points[2], points[1], points[3]]
            ]

            faces = PolyCollection(edges, linewidths=1, edgecolors='k')
            color_with_alpha = matplotlib.colors.to_rgba(chunk_colors[proc])
            faces.set_facecolor(color_with_alpha)
            ax.add_collection(faces)

            # Plot the points themselves to force the scaling of the axes
            ax.scatter(points[:, 0], points[:, 1], s=0)
Exemple #6
0
def plot_polys(verts, polys, facecolors=(1, 1, 1)):
    collection = PolyCollection([verts[p, ::-1] for p in polys])
    collection.set_facecolor(facecolors)
    collection.set_edgecolor((0.8, 0.8, 0.8))
    collection.set_linewidth(0.15)
    ax = plt.gca()
    ax.add_collection(collection)
    xmin, xmax = np.amin(verts[:, 1]), np.amax(verts[:, 1])
    ymin, ymax = np.amin(verts[:, 0]), np.amax(verts[:, 0])
    ax.set_xlim([xmin - 1, xmax + 1])
    ax.set_ylim([ymin - 1, ymax + 1])
def plot_triangles(p, adjustLowerLeft=False, values=None, values_cmap=matplotlib.cm.jet, edgecolors='k'):
    """ Add mesh triangles to a pyplot plot
        
       @param p = object holding sww vertex information (from util.get_output)
       @param adjustLowerLeft = if TRUE, use spatial coordinates, otherwise use ANUGA internal coordinates     
       @param values = list or array of length(p.vols), or None. All triangles are assigned this value (for face plotting colors).
       @param values_cmap = colormap for faces [e.g. values_cmap = matplotlib.cm.get_cmap('spectral')]
       @param edgecolors = edge color for polygons (using matplotlib.colors notation). Use 'none' for no color
    """
    import matplotlib
    from matplotlib import pyplot as pyplot
    from matplotlib.collections import PolyCollection

    x0=p.xllcorner
    y0=p.yllcorner 

    # Make vertices for PolyCollection Object
    vertices = []
    for i in range(len(p.vols)):
        k1=p.vols[i][0]
        k2=p.vols[i][1]
        k3=p.vols[i][2]

        tri_coords = numpy.array([ [p.x[k1], p.y[k1]], [p.x[k2], p.y[k2]], [p.x[k3], p.y[k3]] ])
        if adjustLowerLeft:
            tri_coords[:,0] = tri_coords[:,0] + x0
            tri_coords[:,1] = tri_coords[:,1] + y0

        vertices.append(tri_coords)
     
    # Make PolyCollection 
    if values is None: 
        all_poly = PolyCollection( vertices, array = numpy.zeros(len(vertices)), 
            edgecolors=edgecolors)
        all_poly.set_facecolor('none')
    else:
        try:
            lv = len(values)
        except:
            values = numpy.array(len(p.vols)*[values])
            lv = len(values)

        msg = 'len(values) must be the same as len(p.vols) (or values can be a constant)'
        assert lv==len(p.vols), msg
        all_poly = PolyCollection( vertices, array = values, cmap = values_cmap, 
            edgecolors=edgecolors)

    # Add to plot
    # FIXME: To see the triangles, this might require that the user does
    # something else to the plot?
    pyplot.gca().add_collection(all_poly)
class ScatterPlotCC(ScatterPlot):

    def get_polygon(self, x, y, c):
        color_map = ('c', 'r', 'b', 'm', 'y', 'g')
        d = defaultdict(list)

        for p, cc in zip(zip(x, y), c):
            d[cc].append(p)

        polygons = []
        colors = []
        for k in set(c):
            if len(d[k]) == 2:
                pt1 = d[k][0]
                pt2 = d[k][1]
                dist = math.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
                xmid = (pt1[0] + pt2[0]) / 2
                ymid = (pt1[1] + pt2[1]) / 2
                polygons.append(d[k])
                colors.append(color_map[k])
            elif len(d[k]) == 1:
                pass
            else:
                ch = ConvexHull(d[k])
                points = ch.points
                pts = zip(points[ch.vertices, 0], points[ch.vertices, 1])
                polygons.append(pts)
                colors.append(color_map[k])

        return polygons, colors

    def setup_plot(self):
        ax = plt.gca()
        x, y, c = next(self.stream)
        po, co = self.get_polygon(x, y, c)
        self.poly = PolyCollection(po, facecolors = co, edgecolors='none')

        ax.add_collection(self.poly)
        self.scat = ax.scatter(x, y, c='k', marker = self.marker, s = 25)
        return self.scat

    def update_plot(self):
        x, y, c = next(self.stream)
        new_data = np.array(zip(x, y))
        po, co = self.get_polygon(x, y, c)
        self.poly.set_facecolor(co)
        self.poly.set_verts(po)
        self.scat.set_offsets(new_data)
        return self.scat
Exemple #9
0
def plot_polygons(verts, colors, ax=None, edgecolor=None):
    """
    `verts` is a sequence of ( verts0, verts1, ...) where verts_i is a sequence of
    xy tuples of vertices, or an equivalent numpy array of shape (nv, 2).
   
    `c` is a sequence of (color0, color1, ...) where color_i is a color,
    represented by a hex string (7 characters #xxxxxx).
   
    Creates a PolygonCollection object in the axis `ax`."""
    if ax is None:
        fig = plt.gcf()
        ax = fig.add_subplot(1,1,1)
    pc = PolyCollection(verts)
    pc.set_edgecolor(edgecolor)    
    pc.set_facecolor(colors)
    ax.add_collection(pc)
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')
Exemple #10
0
def plotmap(shpfile,color='0.5',fieldname='FID',convert=None,zone=15,\
    scale=1.,offset=0.,subset=1):
    """
    Plots a map layer from a polygon or multipolygon shapefile
    
    Usage:
        plotmap(shpfile,color='0.5',fieldname='FID',convert=None,zone=15)
        
        convert = 'll2utm' or 'utm2ll'
        zone = utm zone number
    """

    from matplotlib.collections import PolyCollection

    # Read the shapefile
    xy, marker = readShpPoly(shpfile, FIELDNAME=fieldname)

    if convert == 'utm2ll':
        ll = []
        for xytmp in xy:
            ll.append(utm2ll(xytmp, zone, CS='WGS84', north=True))
        xy = ll
    elif convert == 'll2utm':
        ll = []
        for xytmp in xy:
            ll.append(ll2utm(xytmp, zone, CS='WGS84', north=True))
        xy = ll

    for ii in range(len(xy)):
        xy[ii] = xy[ii][::subset] * scale + offset

    # Add the polygons to the current axis as a series of patches
    fig = plt.gcf()
    ax = fig.gca()

    collection = PolyCollection(xy)
    collection.set_facecolor(color)
    #collection.set_rasterized(True)
    ax.add_collection(collection)
    #ax.axis('equal')

    return ax, collection
Exemple #11
0
def plotmap(shpfile,color='0.5',fieldname='FID',convert=None,zone=15,\
    scale=1.,offset=0.,subset=1):
    """
    Plots a map layer from a polygon or multipolygon shapefile
    
    Usage:
        plotmap(shpfile,color='0.5',fieldname='FID',convert=None,zone=15)
        
        convert = 'll2utm' or 'utm2ll'
        zone = utm zone number
    """
    
    from matplotlib.collections import PolyCollection
    
    # Read the shapefile
    xy,marker = readShpPoly(shpfile,FIELDNAME=fieldname)
    
    if convert=='utm2ll':
        ll=[]
        for xytmp in xy:
            ll.append(utm2ll(xytmp,zone,CS='WGS84',north=True))
        xy=ll
    elif convert=='ll2utm':
        ll=[]
        for xytmp in xy:
            ll.append(ll2utm(xytmp,zone,CS='WGS84',north=True))
        xy=ll
        
    for ii in range(len(xy)):
        xy[ii] = xy[ii][::subset]*scale+offset

    # Add the polygons to the current axis as a series of patches
    fig = plt.gcf()
    ax = fig.gca()
    
    collection = PolyCollection(xy)
    collection.set_facecolor(color)
    #collection.set_rasterized(True)
    ax.add_collection(collection)
    #ax.axis('equal')
    
    return ax, collection
Exemple #12
0
def main_2d(vertices, faces, facecolors, edges, edgecolors, verts,
            vertexcolors, args, canvassize=4):
    fig = plt.figure()
    fig.set_size_inches(canvassize, canvassize)
    ax = fig.add_subplot(111)
    ax.set_aspect("equal")
    plt.axis('off')
    these_faces = [vertices[i] for i in faces]
    pd = PolyCollection(these_faces, edgecolors=edgecolors)
    try:
        pd.set_facecolor(facecolors)
    except ValueError:
        pd.set_array(np.array(facecolors))
        pd.set_cmap(plt.get_cmap(args.cmap))
    ax.add_collection(pd)
    these_edges = vertices[edges]
    ld = LineCollection(these_edges, edgecolor=edgecolors)
    ax.add_collection(ld)
    these_vertices = vertices[verts]
    ax.scatter(these_vertices[..., 0], these_vertices[..., 1], c=vertexcolors)
Exemple #13
0
    def draw_colorbar(self, orientation):

        self.axes.clear()
        self.axes.set_axis_off()

        if orientation is "vertical":
            bin_height = 0.99 / len(self.color)
            barverts = tuple(((0.89, i*bin_height+0.005), (0.99, i*bin_height+0.005), (0.99, (i+1)*bin_height+0.005), (0.89, (i+1)*bin_height+0.005)) for i in range(len(self.color)))
            for i in range(len(self.bin)):
                self.axes.text(1.00, (i+1)*bin_height - 0.01, str(self.bin[i]))
        else:
            bin_width = 0.99 / len(self.color)
            barverts = tuple(((i*bin_width+0.005, 0.005), (i*bin_width+0.005, 0.105), ((i+1)*bin_width+0.005, 0.105), ((i+1)*bin_width+0.005, 0.005)) for i in range(len(self.color)))
            for i in range(len(self.bin)):
                self.axes.text((i+1)*bin_width - 0.015, -0.06, str(self.bin[i]))

        bar = PolyCollection(barverts)
        bar.set_edgecolor('black')
        bar.set_facecolor(self.color)
        bar.set_linewidth(0.5)

        self.axes.add_collection(bar)
Exemple #14
0
def swhlocal(swhs,
             verts,
             ncels,
             colrs,
             config,
             mdlname='SMC',
             datx='2018',
             psfile='output.ps',
             paprorn='portrait',
             paprtyp='a3'):

    ##  Import relevant modules and functions

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt

    from matplotlib.collections import PolyCollection

    from readcell import readtext
    from colrboxy import colrboxy
    from scale_swh import scale_swh

    ##  Degree to radian conversion parameter.
    d2rad = np.pi / 180.0

    ##  Local plot configuration parameters
    rdpols = config[0]
    sztpxy = config[1]
    rngsxy = config[2]
    clrbxy = config[3]

    ##  Maximum mapping radius.
    radius = rdpols[0]

    ##  Set up wave height scale and marks with colrs.N.
    ##  colrs.N returns colrs' total number of colors 256.
    waveht, factor, residu, marks, ncstr, nclrm = scale_swh(nclrm=colrs.N)

    resmn1 = residu - 1.0
    nswh0 = ncstr + int(factor * np.log(-resmn1 + residu))

    #   print ' nswh0 and marks = ', nswh0, marks
    #   print ' factor, residu, resmn1 = %f, %f, %f' % (factor, residu, resmn1)

    ##  Some constant variables for plots.
    xprop = {'xlim': rngsxy[0:2], 'xlabel': ''}
    yprop = {'ylim': rngsxy[2:4], 'ylabel': ''}

    ##  Use ijk to count how many times to draw.
    ijk = 0

    if True:
        ##  Work out max and min values, excluding missing data (-999.0)
        cmax = swhs.max()
        cmin = swhs[swhs > -999.0].min()
        print(' swh range %f, %f' % (cmin, cmax))
        cmxs = 'SWHmx = %6.2f m' % cmax
        cmns = 'SWHmn = %10.3E' % cmin

        ##  Reset missing values (-999.0) to be -resmn1
        swhs[swhs < -resmn1] = -resmn1

        ##  Trim large values into plot range if any
        swhs[swhs > 32.0] = 32.0

        ##  Convert swhs with logarithm scale.
        icnf = ncstr + np.rint(factor * np.log(swhs + residu))
        nswh = np.array(icnf, dtype=np.int16)

        print(" Drawing " + psfile)

        ##  Set up first subplot and axis for northern hemisphere

        fig = plt.figure(figsize=sztpxy[0:2])
        ax = fig.add_subplot(1, 1, 1)
        ax.set(**xprop)
        ax.set(**yprop)
        ax.set_aspect('equal')
        ax.set_autoscale_on(False)
        ax.set_axis_off()
        plt.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0)

        ## Prepare PolyCollection for this plot.
        polynorth = PolyCollection(verts)

        ## Create color array for this plot
        pcface = []
        pcedge = []
        for i in ncels:
            if (nswh[i] != nswh0):
                pcface.append(colrs(nswh[i]))
                pcedge.append(colrs(nswh[i]))
            else:
                pcface.append(colrs(255))
                pcedge.append(colrs(0))

#   smcpoly.set_color(pcolr)    ## This line defines both edge and face color.
        polynorth.set_facecolor(pcface)
        polynorth.set_edgecolor(pcedge)
        polynorth.set_linewidth(0.2)
        #       print (" Drawing north hemisphere cells ... ")
        ax.add_collection(polynorth)

        ##  Draw colorbar inside plot.
        xkeys, ykeys, clrply = colrboxy(clrbxy, colrs, marks)
        ax.add_collection(clrply)
        dkx = clrbxy[2]
        dky = clrbxy[3]
        for i in range(len(waveht)):
            m = marks[i]
            if (dkx < dky):
                plt.text(xkeys[0] + 1.15 * dkx,
                         ykeys[m],
                         str(waveht[i]),
                         verticalalignment='center',
                         fontsize=11,
                         color='b')
            else:
                plt.text(xkeys[m],
                         ykeys[0] + 1.15 * dky,
                         str(waveht[i]),
                         horizontalalignment='center',
                         fontsize=11,
                         color='b')

        if (dkx < dky):
            plt.text(xkeys[0] + 2.0 * dkx,
                     ykeys[marks[3]],
                     'SWH m',
                     rotation=90,
                     verticalalignment='center',
                     fontsize=15,
                     color='k')
        else:
            plt.text(xkeys[marks[3]],
                     ykeys[0] + 2.0 * dky,
                     'SWH m',
                     rotation=0,
                     horizontalalignment='center',
                     fontsize=15,
                     color='k')

##  Put cell information inside plot
        tpx = sztpxy[2]
        tpy = sztpxy[3]
        plt.text(tpx,
                 tpy - 1.0,
                 mdlname,
                 horizontalalignment='center',
                 fontsize=17,
                 color='g')
        plt.text(tpx,
                 tpy - 1.6,
                 datx,
                 horizontalalignment='center',
                 fontsize=15,
                 color='k')
        plt.text(tpx,
                 tpy - 2.1,
                 cmxs,
                 horizontalalignment='center',
                 fontsize=13,
                 color='r')
        plt.text(tpx,
                 tpy - 2.6,
                 cmns,
                 horizontalalignment='center',
                 fontsize=13,
                 color='b')

        ##  Refresh subplots and save them.
        plt.savefig(psfile,
                    dpi=None,
                    facecolor='w',
                    edgecolor='w',
                    orientation=paprorn,
                    papertype=paprtyp)

        plt.close()
Exemple #15
0
def plot_geocol_mpl(gc,
                    color=None,
                    facecolor='0.3',
                    edgecolor='0.7',
                    alpha=1.,
                    linewidth=0.2,
                    marker='o',
                    marker_size=20,
                    ax=None,
                    figsize=(9, 9)):
    '''
    Plot geographical data from the `geometry` column of a PySAL geotable to a
    matplotlib backend.

    ...

    Parameters
    ----------
    gc : DataFrame
        GeoCol with data to be plotted.
    color : str/tuple/Series
        [Optional. Default=None] Wrapper that sets both `facecolor`
        and `edgecolor` at the same time. If set, `facecolor` and
        `edgecolor` are ignored. It allows for either a single color
        or a Series of the same length as `gc` with colors, indexed
        on `gc.index`.
    facecolor : str/tuple/Series
        [Optional. Default='0.3'] Color for polygons and points. It
        allows for either a single color or a Series of the same
        length as `gc` with colors, indexed on `gc.index`.
    edgecolor : str/tuple/Series
        [Optional. Default='0.7'] Color for the polygon and point
        edges. It allows for either a single color or a Series of
        the same length as `gc` with colors, indexed on `gc.index`.
    alpha : float/Series
        [Optional. Default=1.] Transparency. It allows for either a
        single value or a Series of the same length as `gc` with
        colors, indexed on `gc.index`.
    linewidth : float/Series
        [Optional. Default=0.2] Width(s) of the lines in polygon and
        line plotting (not applicable to points). It allows for
        either a single value or a Series of the same length as `gc`
        with colors, indexed on `gc.index`.
    marker : 'o'
    marker_size : int
    ax : AxesSubplot
        [Optional. Default=None] Pre-existing axes to which append the
        collections and setup
    figsize : tuple
        w,h of figure

    '''
    geom = type(gc.iloc[0])
    if color is not None:
        facecolor = edgecolor = color
    draw = False
    if not ax:
        f, ax = plt.subplots(1, figsize=figsize)
        draw = True
    # Geometry plotting
    patches = []
    ids = []
    # Polygons
    if geom == ps.cg.shapes.Polygon:
        for id, shape in gc.iteritems():
            for ring in shape.parts:
                xy = np.array(ring)
                patches.append(xy)
                ids.append(id)
        mpl_col = PolyCollection(patches)
    # Lines
    elif geom == ps.cg.shapes.Chain:
        for id, shape in gc.iteritems():
            for xy in shape.parts:
                patches.append(xy)
                ids.append(id)
        mpl_col = LineCollection(patches)
        facecolor = 'None'
    # Points
    elif geom == ps.cg.shapes.Point:
        edgecolor = facecolor
        xys = np.array(zip(*gc)).T
        ax.scatter(xys[:, 0],
                   xys[:, 1],
                   marker=marker,
                   s=marker_size,
                   c=facecolor,
                   edgecolors=edgecolor,
                   linewidths=linewidth)
        mpl_col = None
    # Styling mpl collection (polygons & lines)
    if mpl_col:
        if type(facecolor) is pd.Series:
            facecolor = facecolor.reindex(ids)
        mpl_col.set_facecolor(facecolor)
        if type(edgecolor) is pd.Series:
            edgecolor = edgecolor.reindex(ids)
        mpl_col.set_edgecolor(edgecolor)
        if type(linewidth) is pd.Series:
            linewidth = linewidth.reindex(ids)
        mpl_col.set_linewidth(linewidth)
        if type(alpha) is pd.Series:
            alpha = alpha.reindex(ids)
        mpl_col.set_alpha(alpha)

        ax.add_collection(mpl_col, autolim=True)
        ax.autoscale_view()
    ax.set_axis_off()
    if draw:
        plt.axis('equal')
        plt.show()
    return None
Exemple #16
0
def smcglobl(cel,
             nvrts,
             ncels,
             svrts,
             scels,
             colrs,
             config,
             Arctic=None,
             mdlname='SMC',
             buoys=None,
             psfile='output.ps',
             paprtyp='a3'):
    """
    ##  The smcglobl function plots a global view of a given smc grid.
    ##  cel is the full cell array in shape(nc, 5).
    ##                                JGLi04Mar2019
    """

    ##  Degree to radian conversion parameter.
    d2rad = np.pi / 180.0

    ##  Global plot configuration parameters.
    rdpols = config[0]
    sztpxy = config[1]
    rngsxy = config[2]
    clrbxy = config[3]
    if (Arctic is not None): ncabgm = config[4]

    ##  Maximum mapping radius.
    radius = rdpols[0]
    pangle = rdpols[1]
    plon = rdpols[2]
    plat = rdpols[3]

    ##  Outline circle at equator
    ciran = np.arange(1081) * d2rad / 3.0
    xcirc = radius * np.cos(ciran)
    ycirc = radius * np.sin(ciran)

    ##  Define depth to color index conversion parameters and marks.
    ##  Use only first 131 colors in colrs(0:255).
    depth, factr, cstar, marks, ncstr, nclrm = scale_depth(nclrm=131)

    ##  Cell color is decided by its depth value, dry cells use default 0 color.
    nc = cel.shape[0]
    ndeps = np.zeros((nc), dtype=np.int)
    for j in range(nc):
        if (cel[j, 4] > 0):
            ndeps[j] = ncstr + np.rint(
                (cstar - np.log10(cel[j, 4])) * factr).astype(np.int)
    #ndeps = ncstr + np.rint( (cstar-np.log10(cel[:,4]))*factr ).astype(np.int)

    if (Arctic is not None):
        na = int(ncabgm[1])
        nb = int(ncabgm[2])
        jm = int(ncabgm[3])

    ##  Set up first subplot and axis for northern hemisphere
    print(" Drawing north hemisphere cells ... ")
    fig = plt.figure(figsize=sztpxy[0:2])
    ax1 = fig.add_subplot(1, 2, 1)
    ax1.set_aspect('equal')
    ax1.set_autoscale_on(False)
    ax1.set_axis_off()
    plt.subplots_adjust(left=0.02, bottom=0.02, right=0.98, top=0.95)
    plt.subplots_adjust(wspace=0.02, hspace=0.01)

    xprop = {'xlim': rngsxy[0:2], 'xlabel': 'Nothing'}
    yprop = {'ylim': rngsxy[2:4], 'ylabel': 'Nothing'}
    ax1.set(**xprop)
    ax1.set(**yprop)

    ax1.plot(xcirc, ycirc, 'b-')

    ## Select cells for one subplot and create verts and pcolr.
    pcface = []
    pcedge = []
    for i in ncels:
        if (Arctic is not None) and (cel[i, 1] == Arctic):
            # Mark the arctic map-east reference region by first ring of its boundary cells
            pcface.append(colrs(246))
            pcedge.append(colrs(246))
        #elif( Arctic is not None ) and ( cel[i,1] == jm ):
        #    # Mark the arctic cells
        #    pcface.append(colrs(168))
        #    pcedge.append(colrs(168))
        else:
            pcface.append(colrs(255))
            pcedge.append(colrs(ndeps[i]))

    ##  Draw this hemisphere cells
    smcpoly = PolyCollection(nvrts)
    smcpoly.set_facecolor(pcface)
    smcpoly.set_edgecolor(pcedge)
    smcpoly.set_linewidth(0.2)
    ax1.add_collection(smcpoly)

    ##  Draw colorbar for ax1.
    xkeys, ykeys, clrply = colrboxy(clrbxy, colrs, marks, nclrm=nclrm)
    ax1.add_collection(clrply)
    for i in range(len(depth)):
        m = marks[i]
        plt.text(xkeys[m],
                 ykeys[0] + 1.15 * (ykeys[1] - ykeys[0]),
                 str(depth[i]),
                 horizontalalignment='center',
                 fontsize=11,
                 color='b')
        #rotation=-90,verticalalignment='center', fontsize=11, color='b' )

    plt.text(xkeys[marks[0]],
             ykeys[0] + 2.2 * (ykeys[1] - ykeys[0]),
             'Depth m',
             horizontalalignment='left',
             fontsize=15,
             color='k')
    #rotation=-90,verticalalignment='center', fontsize=15, color='k' )

    # Overlay buoy sites on grid map if buoy file is provided.
    if (buoys is not None):
        hdr, buoyll = readtext(buoys)
        nmbu = long(hdr[0])
        buoyids = buoyll[:, 0].astype(str)
        buoylat = buoyll[:, 1].astype(np.float)
        buoylon = buoyll[:, 2].astype(np.float)

        #; Convert slat slon to elat elon with given new pole
        elat, elon, sxc, syc = steromap(buoylat,
                                        buoylon,
                                        plat,
                                        plon,
                                        Pangl=pangle)

        #; Mark buoy position on map
        print(' Selected buoys on north hemisphere ...')
        for i in range(nmbu):
            if ((elat[i] >= 0.0) and (rngsxy[0] < sxc[i] < rngsxy[1])
                    and (rngsxy[2] < syc[i] < rngsxy[3])):
                print(' {:6} {:8.3f} {:8.3f}'.format(buoyids[i], buoylat[i],
                                                     buoylon[i]))
                txtsz = int(abs(np.sin(elat[i] * d2rad) * 12.0))
                plt.text(sxc[i],
                         syc[i],
                         'r',
                         fontsize=txtsz,
                         horizontalalignment='center',
                         color='r')
                plt.text(sxc[i],
                         syc[i],
                         '.',
                         fontsize=txtsz * 2,
                         horizontalalignment='center',
                         color='r')

    ##  Southern hemisphere
    print(" Drawing south hemisphere cells ... ")
    ax2 = fig.add_subplot(1, 2, 2)
    ax2.set_aspect('equal')
    ax2.axis('off')
    plt.subplots_adjust(left=0.02, bottom=0.02, right=0.98, top=0.95)
    plt.subplots_adjust(wspace=0.02, hspace=0.01)
    ax2.set(**xprop)
    ax2.set(**yprop)

    ax2.plot(xcirc, ycirc, 'b-')

    ## Select cells for one subplot and create verts and pcolr.
    pcface = []
    pcedge = []
    for i in scels:
        pcface.append(colrs(255))
        pcedge.append(colrs(ndeps[i]))

    ## Generate polygon collections for southern hemisphere
    smcpoly = PolyCollection(svrts)
    smcpoly.set_facecolor(pcface)
    smcpoly.set_edgecolor(pcedge)
    smcpoly.set_linewidth(0.2)

    ax2.add_collection(smcpoly)

    ##  Put cell information inside plot
    tpx = sztpxy[2]
    tpy = sztpxy[3]
    dpy = 0.6

    plt.text(tpx,
             tpy + dpy * 0.5,
             mdlname + ' Grid',
             horizontalalignment='center',
             fontsize=15,
             color='k')
    plt.text(tpx,
             tpy + dpy * 2.0,
             'NC=' + str(nc),
             horizontalalignment='center',
             fontsize=13,
             color='r')
    if (Arctic is not None):
        plt.text(tpx,
                 tpy + dpy * 3.0,
                 'NA=' + str(na),
                 horizontalalignment='center',
                 fontsize=13,
                 color='r')
        plt.text(tpx,
                 tpy + dpy * 4.0,
                 'NB=' + str(nb),
                 horizontalalignment='center',
                 fontsize=13,
                 color='r')

    ##  Draw colorbar for ax2.
    xkeys, ykeys, clrply = colrboxy(clrbxy, colrs, marks, nclrm=nclrm)
    ax2.add_collection(clrply)
    for i in range(len(depth)):
        m = marks[i]
        plt.text(xkeys[m],
                 ykeys[0] + 1.18 * (ykeys[1] - ykeys[0]),
                 str(depth[i]),
                 horizontalalignment='center',
                 fontsize=11,
                 color='b')
        #verticalalignment='center', fontsize=11, color='b' )
        #rotation=-90,verticalalignment='center', fontsize=11, color='b' )

    plt.text(xkeys[marks[-1]],
             ykeys[0] + 2.2 * (ykeys[1] - ykeys[0]),
             'Depth m',
             horizontalalignment='right',
             fontsize=15,
             color='k')
    #rotation=-90,verticalalignment='center', fontsize=15, color='k' )

    # Overlay buoy sites on grid map if buoy file is provided.
    if (buoys is not None):

        #; Mark buoy position on map
        print(' Selected buoys on south hemisphere ...')
        for i in range(nmbu):
            if ((elat[i] < 0.0) and (rngsxy[0] < -sxc[i] < rngsxy[1])
                    and (rngsxy[2] < syc[i] < rngsxy[3])):
                print(' {:6} {:8.3f} {:8.3f}'.format(buoyids[i], buoylat[i],
                                                     buoylon[i]))
                txtsz = int(abs(np.sin(elat[i] * d2rad) * 12.0))
                plt.text(-sxc[i],
                         syc[i],
                         'r',
                         fontsize=txtsz,
                         horizontalalignment='center',
                         color='r')
                plt.text(-sxc[i],
                         syc[i],
                         '.',
                         fontsize=txtsz * 2,
                         horizontalalignment='center',
                         color='r')

    ##  Refresh subplots and save them.
    plt.subplots_adjust(wspace=0.02, hspace=0.01)

    plt.savefig(psfile, dpi=None,facecolor='w',edgecolor='w', \
                orientation='landscape',papertype=paprtyp,format='ps')
Exemple #17
0
def smclocal(cel,
             verts,
             ncels,
             colrs,
             config,
             Arctic=None,
             mdlname='SMC',
             buoys=None,
             psfile='output.ps',
             paprorn='portrait',
             paprtyp='a3'):
    """
    ##  The smclocal function plots a local region of a given smc grid.
    ##  cel is the full cell array in shape(nc, 5).
    ##                                JGLi04Mar2019
    """

    #  Degree to radian conversion parameter.
    d2rad = np.pi / 180.0

    #  Local plot configuration parameters
    rdpols = config[0]
    sztpxy = config[1]
    rngsxy = config[2]
    clrbxy = config[3]
    if (Arctic): ncabgm = config[4]

    # Maximum mapping radius.
    radius = rdpols[0]
    pangle = rdpols[1]
    plon = rdpols[2]
    plat = rdpols[3]

    # Define depth to color index conversion parameters and marks.
    # Use only first 131 colors in colrs(0:255).
    depth, factr, cstar, marks, ncstr, nclrm = scale_depth(nclrm=136)

    # Cell color is decided by its depth value.
    nc = cel.shape[0]
    ndeps = np.zeros((nc), dtype=np.int)
    for j in range(nc):
        if (cel[j, 4] > -11):
            ndeps[j] = ncstr + np.rint(
                (cstar - np.log10(cel[j, 4] + 11)) * factr).astype(np.int)
    #ndeps = ncstr + np.rint( (cstar-np.log10(cel[:,4]))*factr ).astype(np.int)

    if (Arctic is not None):
        na = int(ncabgm[1])
        nb = int(ncabgm[2])
        jm = int(ncabgm[3])

    # Workout output file format from its extension
    #for i in np.arange(len(psfile))[::-1]:
    #    if( psfile[i] == '.' ):
    #        psfmt = psfile[i+1:]
    #        break
    #print " Output file format will be "+psfmt
    # Python plt.savefig will do this automatically.

    # Use selected cells to draw the plot.
    fig = plt.figure(figsize=sztpxy[0:2])
    ax = fig.add_subplot(1, 1, 1)
    yprop = {'ylim': rngsxy[2:4], 'ylabel': ''}
    xprop = {'xlim': rngsxy[0:2], 'xlabel': ''}
    ax.set(**xprop)
    ax.set(**yprop)
    ax.set_aspect('equal')
    ax.set_autoscale_on(False)
    ax.set_axis_off()
    plt.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0)

    # Create color array for this plot
    pcface = []
    pcedge = []
    for i in ncels:
        if (Arctic is not None) and (cel[i, 1] == Arctic):
            # Mark the arctic map-east reference region by first ring of its boundary cells
            pcface.append(colrs(246))
            pcedge.append(colrs(246))
        #elif( Arctic is not None ) and ( cel[i,1] == jm ):
        #    # Mark the arctic cells
        #    pcface.append(colrs(168))
        #    pcedge.append(colrs(168))
        else:
            pcedge.append(colrs(ndeps[i] + 10))
            pcface.append(colrs(ndeps[i]))
            #pcface.append(colrs(255))
            #pcedge.append(colrs(ndeps[i]))

    # Create PolyCollection from selected verts and define edge and face color.
    polynorth = PolyCollection(verts)
    polynorth.set_facecolor(pcface)
    polynorth.set_edgecolor(pcedge)
    polynorth.set_linewidth(0.2)

    # Draw the selected cells as colored polygons.
    ax.add_collection(polynorth)

    # Draw colorbar inside plot.
    xkeys, ykeys, clrply = colrboxy(clrbxy, colrs, marks, nclrm=nclrm)
    ax.add_collection(clrply)
    dkx = clrbxy[2]
    dky = clrbxy[3]
    for i in range(len(depth)):
        m = marks[i]
        if (dkx < dky):
            plt.text(xkeys[0] + 1.15 * dkx,
                     ykeys[m],
                     str(depth[i]),
                     verticalalignment='center',
                     fontsize=11,
                     color='b')
        else:
            plt.text(xkeys[m],
                     ykeys[0] + 1.15 * dky,
                     str(depth[i]),
                     horizontalalignment='center',
                     fontsize=11,
                     color='b')

    if (dkx < dky):
        plt.text(xkeys[0] + 1.9 * dkx,
                 ykeys[marks[2]],
                 'Depth m',
                 rotation=-90,
                 verticalalignment='center',
                 fontsize=15,
                 color='k')
    else:
        plt.text(xkeys[marks[2]],
                 ykeys[0] + 1.9 * dky,
                 'Depth m',
                 rotation=0,
                 horizontalalignment='center',
                 fontsize=15,
                 color='k')

    # Put cell information inside plot
    tpx = sztpxy[2]
    tpy = sztpxy[3]
    dpy = -0.6

    plt.text(tpx,
             tpy + dpy * 1,
             mdlname + ' Grid',
             horizontalalignment='center',
             fontsize=15,
             color='k')
    plt.text(tpx,
             tpy + dpy * 2,
             'NC=' + str(nc),
             horizontalalignment='center',
             fontsize=13,
             color='r')
    if (Arctic is not None):
        plt.text(tpx,
                 tpy + dpy * 3,
                 'NA=' + str(na),
                 horizontalalignment='center',
                 fontsize=13,
                 color='r')
        plt.text(tpx,
                 tpy + dpy * 4,
                 'NB=' + str(nb),
                 horizontalalignment='center',
                 fontsize=13,
                 color='r')

    # Overlay buoy sits on grid map if buoy file is provided.
    if (buoys is not None):
        hdr, buoyll = readtext(buoys)
        nmbu = int(hdr[0])
        buoyids = buoyll[:, 0].astype(str)
        buoylat = buoyll[:, 1].astype(np.float)
        buoylon = buoyll[:, 2].astype(np.float)

        # Convert slat slon to elat elon with given new pole
        elat, elon, sxc, syc = steromap(buoylat,
                                        buoylon,
                                        plat,
                                        plon,
                                        Pangl=pangle)

        # Mark buoy position on map
        print(' Selected buoys in this plot:')
        for i in range(nmbu):
            if ((elat[i] >= 25.0) and (rngsxy[0] < sxc[i] < rngsxy[1])
                    and (rngsxy[2] < syc[i] < rngsxy[3])):
                print(' {:6} {:8.3f} {:8.3f}'.format(buoyids[i], buoylat[i],
                                                     buoylon[i]))
                txtsz = int(abs(np.sin(elat[i] * d2rad) * 12.0))
                plt.text(sxc[i],
                         syc[i],
                         'r',
                         fontsize=txtsz,
                         horizontalalignment='center',
                         color='r')
                plt.text(sxc[i],
                         syc[i],
                         '.',
                         fontsize=txtsz * 2,
                         horizontalalignment='center',
                         color='r')

    # Save plot as ps file
    print(" Save the smc grid local plot ... ")
    plt.savefig(psfile, dpi=None,facecolor='w',edgecolor='w', \
                orientation=paprorn,papertype=paprtyp,format='ps')
Exemple #18
0
def swhglobl(swhs,
             nvrts,
             ncels,
             svrts,
             scels,
             colrs,
             config,
             mdlname='SMC',
             datx='2018010106',
             psfile='output.ps',
             paprtyp='a3'):
    """
    ##  Draw global swh plot with given polycollections and cell
    ##  array. Output as A3 ps file.        JGLi28Feb2019
    ##
    """

    # Degree to radian conversion parameter.
    d2rad = np.pi / 180.0

    # Global plot configuration parameters.
    rdpols = config[0]
    sztpxy = config[1]
    rngsxy = config[2]
    clrbxy = config[3]
    ncabgm = config[4]

    # Maximum mapping radius.
    radius = rdpols[0]
    pangle = rdpols[1]
    plon = rdpols[2]
    plat = rdpols[3]

    # Outline circle at equator
    ciran = np.arange(1081) * d2rad / 3.0
    xcirc = radius * np.cos(ciran)
    ycirc = radius * np.sin(ciran)

    # Set up wave height scale and marks with colrs.N.
    # colrs.N returns colrs' total number of colors 256.
    waveht, factor, residu, marks, ncstr, nclrm = scale_swh(nclrm=colrs.N)

    resmn1 = residu - 1.0
    nswh0 = ncstr + int(factor * np.log(-resmn1 + residu))
    #print (' factor, residu, resmn1, nswh0 = {} {} {} {: d}'
    #.format(factor, residu, resmn1, nswh0) )

    # Some constant variables for plots.
    xprop = {'xlim': rngsxy[0:2], 'xlabel': ''}
    yprop = {'ylim': rngsxy[2:4], 'ylabel': ''}

    if True:
        # Work out max and min values, excluding missing data (-999.0)
        cmax = swhs.max()
        cmin = swhs[swhs > -999.0].min()
        print(' swh range %f, %f' % (cmin, cmax))
        cmxs = 'SWHmx = %6.2f m' % cmax
        cmns = 'SWHmn = %10.3E' % cmin

        # Reset missing values (-999.0) to be -resmn1
        swhs[swhs < -resmn1] = -resmn1

        # Trim large values into plot range if any
        swhs[swhs > 32.0] = 32.0

        # Convert swhs with logarithm scale.
        icnf = np.rint(factor * np.log(swhs + residu))
        nswh = np.array(icnf, dtype=np.int)

        print(" Drawing " + psfile)
        # Set up first subplot and axis for northern hemisphere
        fig = plt.figure(figsize=sztpxy[0:2])
        ax1 = fig.add_subplot(1, 2, 1)
        ax1.set_aspect('equal')
        ax1.set_autoscale_on(False)
        ax1.set_axis_off()
        plt.subplots_adjust(left=0.02, bottom=0.02, right=0.98, top=0.95)
        plt.subplots_adjust(wspace=0.02, hspace=0.01)

        ax1.set(**xprop)
        ax1.set(**yprop)

        ax1.plot(xcirc, ycirc, 'b-')

        # Use loaded verts to setup PolyCollection.
        polynorth = PolyCollection(nvrts)

        # Create color array for this plot
        pcface = []
        pcedge = []
        for i in ncels:
            if (nswh[i] == nswh0):
                pcface.append(colrs(255))
                pcedge.append(colrs(0))
            else:
                pcface.append(colrs(nswh[i]))
                pcedge.append(colrs(nswh[i]))

        #smcpoly.set_color(pcolr)    ## This line defines both edge and face color.
        polynorth.set_facecolor(pcface)
        polynorth.set_edgecolor(pcedge)
        polynorth.set_linewidth(0.2)
        ax1.add_collection(polynorth)

        # Draw colorbar for ax1.
        xkeys, ykeys, clrply = colrboxy(clrbxy, colrs, marks)
        ax1.add_collection(clrply)
        for i in range(len(waveht)):
            m = marks[i]
            plt.text(xkeys[m],
                     ykeys[0] + 1.18 * (ykeys[1] - ykeys[0]),
                     str(waveht[i]),
                     horizontalalignment='center',
                     fontsize=11,
                     color='b')
            #rotation=-90,verticalalignment='center', fontsize=11, color='b' )

        plt.text(xkeys[marks[0]],
                 ykeys[0] + 2.2 * (ykeys[1] - ykeys[0]),
                 'SWH m',
                 horizontalalignment='left',
                 fontsize=15,
                 color='k')
        #rotation=-90,verticalalignment='center', fontsize=15, color='k' )

        # Southern hemisphere subplot.
        ax2 = fig.add_subplot(1, 2, 2)
        ax2.set_aspect('equal')
        ax2.axis('off')
        plt.subplots_adjust(left=0.02, bottom=0.02, right=0.98, top=0.95)
        plt.subplots_adjust(wspace=0.02, hspace=0.01)
        ax2.set(**xprop)
        ax2.set(**yprop)

        ax2.plot(xcirc, ycirc, 'b-')

        # Use loaded verts to set up PolyCollection.
        polysouth = PolyCollection(svrts)

        # Create color array for this plot
        pcface = []
        pcedge = []
        for i in scels:
            if (nswh[i] == nswh0):
                pcface.append(colrs(255))
                pcedge.append(colrs(0))
            else:
                pcface.append(colrs(nswh[i]))
                pcedge.append(colrs(nswh[i]))

        #   smcpoly.set_color(pcolr)    ## This line defines both edge and face color.
        polysouth.set_facecolor(pcface)
        polysouth.set_edgecolor(pcedge)
        polysouth.set_linewidth(0.2)
        ax2.add_collection(polysouth)

        # Put statistic information inside subplot ax2
        tpx = sztpxy[2]
        tpy = sztpxy[3]
        dpy = 0.6

        plt.text(tpx,
                 9.0,
                 mdlname + ' SWH',
                 horizontalalignment='center',
                 fontsize=19,
                 color='r')
        plt.text(tpx,
                 tpy + dpy * 1.0,
                 cmns,
                 horizontalalignment='center',
                 fontsize=15,
                 color='b')
        plt.text(tpx,
                 tpy + dpy * 2.0,
                 cmxs,
                 horizontalalignment='center',
                 fontsize=15,
                 color='r')
        plt.text(tpx,
                 tpy + dpy * 3.0,
                 datx,
                 horizontalalignment='center',
                 fontsize=17,
                 color='k')

        # Draw colorbar for ax2.
        xkeys, ykeys, clrply = colrboxy(clrbxy, colrs, marks)
        ax2.add_collection(clrply)
        for i in range(len(waveht)):
            m = marks[i]
            plt.text(xkeys[m],
                     ykeys[0] + 1.18 * (ykeys[1] - ykeys[0]),
                     str(waveht[i]),
                     horizontalalignment='center',
                     fontsize=13,
                     color='b')
            #rotation=-90,verticalalignment='center', fontsize=11, color='b' )

        plt.text(xkeys[marks[-1]],
                 ykeys[0] + 2.2 * (ykeys[1] - ykeys[0]),
                 'SWH m',
                 horizontalalignment='right',
                 fontsize=15,
                 color='k')
        #rotation=-90,verticalalignment='center', fontsize=15, color='k' )

        # Refresh subplots and save them.
        plt.subplots_adjust(wspace=0.02, hspace=0.01)

        plt.savefig(psfile,
                    dpi=None,
                    facecolor='w',
                    edgecolor='w',
                    orientation='landscape',
                    papertype=paprtyp,
                    format='ps')

        plt.close()
Exemple #19
0
def plot_3d_sequence(data_classes: List[SyncMeasData], long_mode: int,
                     trans_mode: Union[int, None]) -> plt.axis:
    # Set 3D plot
    fig = plt.figure()
    axis = fig.gca(projection='3d')

    # Store slices to ensure equally size arrays
    cluster_arrays = []
    q_mode_peaks = []
    data_slices = []
    data_slices_range = []
    for data_class in data_classes:
        collection = LabeledPeakCollection(identify_peaks(data_class))
        try:
            cluster_array, value_slice = collection.get_mode_sequence(
                long_mode=long_mode, trans_mode=trans_mode)
            cluster_arrays.append(cluster_array)
            q_mode_peaks.append(collection.q_dict[long_mode])
        except ValueError:
            logging.warning(f'Longitudinal mode {long_mode} not well defined')
            return axis
        data_slice = get_value_to_data_slice(data_class=data_class,
                                             value_slice=value_slice)
        data_slices.append(data_slice)
        data_slices_range.append(get_slice_range(data_slice))  # Store range

    # Prepare plot data
    leading_index = data_slices_range.index(max(data_slices_range))
    leading_slice = data_slices[leading_index]
    for i, slice in enumerate(data_slices):
        range_diff = get_slice_range(leading_slice) - get_slice_range(slice)
        padding = whole_integer_divider(num=range_diff, div=2)
        data_slices[i] = (slice[0] - padding[0], slice[1] + padding[1])

    sliced_xs = data_classes[leading_index].x_boundless_data[
        leading_slice[0]:leading_slice[1]]
    xs = np.arange(get_slice_range(leading_slice))  # sliced_xs  #
    zs = np.arange(len(data_slices))
    verts = []
    peaks = []
    for i, slice in enumerate(data_slices):
        data_class = data_classes[i]
        data_class.slicer = slice
        ys = data_class.y_data
        verts.append(list(zip(xs, ys)))
        # Peak scatter plot
        peak_list = flatten_clusters(data=cluster_arrays[i])
        peaks.append(peak_list)  # Collect peaks for polarisation cross section
        yp = [peak.get_y for peak in peak_list]
        xp = [peak.get_relative_index for peak in peak_list]
        zp = [zs[i] for j in range(len(peak_list))]
        axis.scatter(xp, zp, yp, marker='o')

    # Draw individual measurement polygons
    poly = PolyCollection(verts)
    poly.set_alpha(.7)
    axis.add_collection3d(poly, zs=zs, zdir='y')

    # Draw polarisation cross section
    cross_section_count = len(peaks[0])
    if all(len(peak_array) == cross_section_count
           for peak_array in peaks):  # Able to build consistent cross sections
        cross_peaks = list(
            map(list, zip(*peaks)
                ))  # Transposes peaks-list to allow for cross section ordering
        xc = []
        # Insert 0 bound values
        zc = list(zs)
        zc.insert(0, zc[0])
        zc.append(zc[-1])
        peak_verts = []
        face_colors = [[v, .3, .3]
                       for v in np.linspace(.5, 1., len(cross_peaks))]
        for i, cross_section in enumerate(cross_peaks):
            yc = [peak.get_y for peak in cross_section]
            # Insert 0 bound values
            yc.insert(0, 0)
            yc.append(0)
            xc.append(
                int(
                    np.mean([
                        peak.get_relative_index for peak in cross_section
                    ])))  # np.mean([peak.get_x for peak in cross_section]))  #
            peak_verts.append(list(zip(zc, yc)))

            poly = PolyCollection([list(zip(zc, yc))])  # peak_verts
            poly.set_alpha(1)
            poly.set_facecolor(face_colors[i])
            axis.add_collection3d(poly, zs=xc[-1], zdir='x')

        # poly = PolyCollection(peak_verts)
        # poly.set_alpha(1)
        # axis.add_collection3d(poly, zs=xc, zdir='x')
        print('plotting')
    else:
        logging.warning(f'Cross section (peak) count is not consistent')

    axis.set_xlabel('Relative cavity length [nm]')
    axis.set_xlim3d(0, len(xs))
    # axis.set_xticks(xs)
    axis.set_ylabel('Polarisation [10 Degree]')  # 'Measurement iterations')
    axis.set_ylim3d(-1, len(zs) + 1)
    # axis.set_yticks([str(10 * angle) for angle in zs])
    axis.set_zlabel('Transmission [a.u.]')
    axis.set_zlim3d(0, 1)
    # Set viewport
    axis.view_init(elev=22, azim=-15)
    return axis
Exemple #20
0
fig, ax = plt.subplots()

ax.set_xlim(left=-0.1, right=8)
ax.set_ylim(bottom=-0.1, top=5.8)
ax.set_aspect('equal')

points = ax.scatter(x, y, marker='x', color='black', zorder=2)
orig = ax.scatter(origin, origin, marker='+', color='black', zorder=2)
mid = ax.scatter(*mid, marker='.', color='black', zorder=2)
bounds = ax.scatter((img[0], img[2]), (img[1], img[3]), marker='x', color='black', zorder=2)
hex = Polygon(hex_coords, closed=True, edgecolor='red', fill=False, zorder=1)
r_line = Line2D(*R_line, zorder=1, linestyle='--')
d_line = Line2D(*d_line, zorder=1, linestyle='--')
img = Rectangle((img[0], img[1]), width=(img[2]-img[0]), height=(img[3]-img[1]), fill=False, edgecolor='black', linestyle=':')
hex_grid = PolyCollection(cells, closed=True, edgecolors='red')
hex_grid.set_facecolor(None)

ax.add_artist(hex)
ax.add_artist(img)
ax.add_artist(r_line)
ax.add_artist(d_line)
ax.add_artist(hex_grid)

ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)

for spine in ax.spines.values():
    spine.set_visible(False)


for annotation in annotations:
Exemple #21
0
 def set_facecolor(self, colors):
     PolyCollection.set_facecolor(self, colors)
     self._facecolors3d = PolyCollection.get_facecolor(self)
Exemple #22
0
def plot_geocol_mpl(gc, color=None, facecolor='0.3', edgecolor='0.7',
        alpha=1., linewidth=0.2, marker='o', marker_size=20,
        ax=None, figsize=(9,9)):
    '''
    Plot geographical data from the `geometry` column of a PySAL geotable to a
    matplotlib backend.

    ...

    Arguments
    ---------
    gc          : DataFrame
                  GeoCol with data to be plotted.
    color       : str/tuple/Series
                  [Optional. Default=None] Wrapper that sets both `facecolor`
                  and `edgecolor` at the same time. If set, `facecolor` and
                  `edgecolor` are ignored. It allows for either a single color
                  or a Series of the same length as `gc` with colors, indexed
                  on `gc.index`.
    facecolor   : str/tuple/Series
                  [Optional. Default='0.3'] Color for polygons and points. It
                  allows for either a single color or a Series of the same
                  length as `gc` with colors, indexed on `gc.index`.
    edgecolor   : str/tuple/Series
                  [Optional. Default='0.7'] Color for the polygon and point
                  edges. It allows for either a single color or a Series of
                  the same length as `gc` with colors, indexed on `gc.index`.
    alpha       : float/Series
                  [Optional. Default=1.] Transparency. It allows for either a
                  single value or a Series of the same length as `gc` with
                  colors, indexed on `gc.index`.
    linewidth   : float/Series
                  [Optional. Default=0.2] Width(s) of the lines in polygon and
                  line plotting (not applicable to points). It allows for
                  either a single value or a Series of the same length as `gc`
                  with colors, indexed on `gc.index`.
    marker      : 'o'
    marker_size : int
    ax          : AxesSubplot
                  [Optional. Default=None] Pre-existing axes to which append the
                  collections and setup
    figsize     : tuple
                  w,h of figure
    '''
    geom = type(gc.iloc[0])
    if color is not None:
        facecolor = edgecolor = color
    draw = False
    if not ax:
        f, ax = plt.subplots(1, figsize=figsize)
        draw = True
    # Geometry plotting
    patches = []
    ids = []
    ## Polygons
    if geom == ps.cg.shapes.Polygon:
        for id, shape in gc.iteritems():
            for ring in shape.parts:
                xy = np.array(ring)
                patches.append(xy)
                ids.append(id)
        mpl_col = PolyCollection(patches)
    ## Lines
    elif geom == ps.cg.shapes.Chain:
        for id, shape in gc.iteritems():
            for xy in shape.parts:
                patches.append(xy)
                ids.append(id)
        mpl_col = LineCollection(patches)
        facecolor = 'None'
    ## Points
    elif geom == ps.cg.shapes.Point:
        edgecolor = facecolor
        xys = np.array(zip(*gc)).T
        ax.scatter(xys[:, 0], xys[:, 1], marker=marker,
                s=marker_size, c=facecolor, edgecolors=edgecolor,
                linewidths=linewidth)
        mpl_col = None
    # Styling mpl collection (polygons & lines)
    if mpl_col:
        if type(facecolor) is pd.Series:
            facecolor = facecolor.reindex(ids)
        mpl_col.set_facecolor(facecolor)
        if type(edgecolor) is pd.Series:
            edgecolor = edgecolor.reindex(ids)
        mpl_col.set_edgecolor(edgecolor)
        if type(linewidth) is pd.Series:
            linewidth = linewidth.reindex(ids)
        mpl_col.set_linewidth(linewidth)
        if type(alpha) is pd.Series:
            alpha = alpha.reindex(ids)
        mpl_col.set_alpha(alpha)

        ax.add_collection(mpl_col, autolim=True)
        ax.autoscale_view()
    ax.set_axis_off()
    if draw:
        plt.axis('equal')
        plt.show()
    return None
Exemple #23
0
 def set_facecolor(self, colors):
     PolyCollection.set_facecolor(self, colors)
     self._facecolors3d = PolyCollection.get_facecolor(self)
              else:
                if lat_distance:
                  if geomag_distance:
                    target_mag=aacgm.Convert(target_lat,target_lon,0,year=2010,flag=0)
                    p1color_ax.plot([p.date2num(startday),p.date2num(endday)],
                      [target_mag[0],target_mag[0]],linewidth=4,linestyle="--",color="k",alpha=0.5)
                  else:
                    p1color_ax.plot([p.date2num(startday),p.date2num(endday)],
                      [target_lat,target_lat],linewidth=4,linestyle="--",color="k",alpha=0.5)

            p.axes(p2color_ax)
            pixs=N.array(p2pixels)
            colors=p2values
            coll = PolyCollection(pixs,edgecolors='none',linewidths=0.0,zorder=10)
            coll.set_antialiased(False)
            coll.set_facecolor(colors)
            coll.set_alpha(1)
            p2color_ax.add_collection(coll)
            p2color_ax.autoscale_view() 
            p2color_ax.xaxis.set_major_formatter(dateFmt)
            p2color_ax.set_xlim(p.date2num(startday), p.date2num(endday))
            p2color_ax.set_ylim(plotdict["min_rang"],plotdict["max_rang"])
            p2color_ax.xaxis.set_major_locator(tick2_minute_interval)
            p2color_locator=MaxNLocator(nbins=6,prune='both',integer=True)
            p2color_ax.yaxis.set_major_locator(p2color_locator)
            p2color_ax.set_xticklabels([])
#            p2color_ax.set_xticks([])
            p2color_ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',alpha=0.5)
            p2color_ax.xaxis.grid(True, linestyle='-', which='major', color='lightgrey',alpha=0.5)
            print "pcolor done"