示例#1
0
文件: uplot.py 项目: mrayson/soda
    def plotcelldata(self, z, xlims=None, ylims=None, colorbar=True, **kwargs):
        """
        Plot cell centered data
        """
        ax=plt.gca()
        fig = plt.gcf()
        # Find the colorbar limits if unspecified
        if self.clim is None:
            self.clim = [z.min(),z.max()]
        # Set the xy limits
        if xlims is None or ylims is None:
            xlims=self.xlims()
            ylims=self.ylims()
        
        collection = PolyCollection(self.xy(),closed=False,**kwargs)
        collection.set_array(z)
        collection.set_clim(vmin=self.clim[0],vmax=self.clim[1])
        collection.set_edgecolors(collection.to_rgba(z))    
        
        ax.add_collection(collection)

        ax.set_aspect('equal')
        ax.set_xlim(xlims)
        ax.set_ylim(ylims)

        axcb=None
        if colorbar:
            axcb = fig.colorbar(collection)

    
        return fig, ax, collection, axcb
示例#2
0
def visualizeHealPixMap(theMap, nest=True, title="map", norm=None, vmin=None, vmax=None, cmap=plt.cm.hot_r):
    
    from matplotlib.collections import PolyCollection
    from matplotlib.colors import Normalize
    nside = hp.npix2nside(theMap.size)
    mapValue = theMap[theMap != hp.UNSEEN]
    indices = np.arange(theMap.size)
    seenInds = indices[theMap != hp.UNSEEN]

    print "Building polygons from HEALPixel map."
    vertices = np.zeros( (seenInds.size, 4, 2) )
    print "Building polygons for "+str(seenInds.size)+" HEALPixels."
    for HPixel,i in zip(seenInds,xrange(seenInds.size)):
        corners = hp.vec2ang( np.transpose(hp.boundaries(nside,HPixel,nest=nest) ) )
        # HEALPix insists on using theta/phi; we in astronomy like to use ra/dec.
        vertices[i,:,0] = corners[1] *180./np.pi
        vertices[i,:,1] = 90.0 - corners[0] * 180/np.pi


    fig, ax = plt.subplots(figsize=(12,12))
    #coll = PolyCollection(vertices, array = mapValue, cmap = plt.cm.seismic, edgecolors='none')
    coll = PolyCollection(vertices, array=mapValue, cmap=cmap, edgecolors='none')
    coll.set_clim(vmin=vmin, vmax=vmax)
    ax.add_collection(coll)
    ax.set_title(title)
    ax.autoscale_view()
    fig.colorbar(coll,ax=ax)

    #ax.set_ylim([-60.2, -43])

    print "Writing to file: "+title+".png"
    fig.savefig(title+".png",format="png")
示例#3
0
 def mapshow(self, map, mask=None, nest=False, **kwargs):
     """ Display a healpix map """
     vmin = kwargs.pop('vmin', None)
     vmax = kwargs.pop('vmax', None)
     defaults = dict(rasterized=True,
                 alpha=0.8,
                 linewidth=0)
     defaults.update(kwargs)
     if mask is None:
         mask = map == map
     v = _boundary(mask, nest)
     coll = PolyCollection(v, array=map[mask], 
             transform=self.transData, **defaults)
     coll.set_clim(vmin=vmin, vmax=vmax)
     self.add_collection(coll)
     return coll
示例#4
0
def plot_trimesh2D(verts, faces, val=None, cmap=plt.cm.get_cmap(), 
        vmin=None, vmax=None, mirror=False, **kw):
    """Plot a mesh of triangles, from directly above, without all this
    3D stuff.
    
    Input   verts   N x 3 array of vertex locations
    
            faces   M x 3 array of vertex indices for each face
            
            val     M list of values for each vertex, used for coloring
            
            cmap    colormap, defaulting to current colormap
            
            vmin    lower limit for coloring, defaulting to min(val)
            
            vmax    upper limit for coloring, defaulting to max(val)
            
            mirror  flag for mirror around x=0
            
            Other keyword pairs are passed to PolyCollection
    """
    
    v = array([[verts[ind,:2] for ind in face] for face in faces])
    if mirror:
        v = r_[v, v * [-1,1]]
    if val is not None:
        val = array(val)
    
    poly = PolyCollection(v, cmap=cmap, norm=Normalize(clip=True), **kw)
    poly.set_array(val)
    poly.set_clim(vmin, vmax)
    poly.set_facecolors(poly.norm(val)) 
    
    ax = plt.gca()
    ax.add_collection(poly)
    ax.axis('image')
    if val is not None:
        # This magic dohickey is used by colorbar() and clim(), for example
        plt.gci._current = poly
    plt.draw() # Seems like should be draw_if_interactive(), but that doesn't
               # work, for some unexplained reason.
    
    return poly
示例#5
0
def plotHealpixPolygons(ax, projection, vertices, color=None, vmin=None, vmax=None, **kwargs):
    """Plot Healpix cell polygons onto map.

    Args:
        ax: matplotlib axes
        projection: map projection
        vertices: Healpix cell boundaries in RA/Dec, from getCountAtLocations()
        color: string or matplib color, or numeric array to set polygon colors
        vmin: if color is numeric array, use vmin to set color of minimum
        vmax: if color is numeric array, use vmin to set color of minimum
        **kwargs: matplotlib.collections.PolyCollection keywords
    Returns:
        matplotlib.collections.PolyCollection
    """
    from matplotlib.collections import PolyCollection
    vertices_ = np.empty_like(vertices)
    vertices_[:,:,0], vertices_[:,:,1] = projection(vertices[:,:,0], vertices[:,:,1])
    coll = PolyCollection(vertices_, array=color, **kwargs)
    coll.set_clim(vmin=vmin, vmax=vmax)
    coll.set_edgecolor("face")
    ax.add_collection(coll)
    return coll
示例#6
0
    def vertex(self, vertices, color=None, vmin=None, vmax=None, **kwargs):
        """Plot polygons (e.g. Healpix vertices)

        Args:
            vertices: cell boundaries in RA/Dec, from getCountAtLocations()
            color: string or matplib color, or numeric array to set polygon colors
            vmin: if color is numeric array, use vmin to set color of minimum
            vmax: if color is numeric array, use vmin to set color of minimum
            **kwargs: matplotlib.collections.PolyCollection keywords
        Returns:
            matplotlib.collections.PolyCollection
        """
        vertices_ = np.empty_like(vertices)
        vertices_[:,:,0], vertices_[:,:,1] = self.proj.transform(vertices[:,:,0], vertices[:,:,1])

        from matplotlib.collections import PolyCollection
        zorder = kwargs.pop("zorder", 0) # same as for imshow: underneath everything
        clip_path = kwargs.pop('clip_path', self._edge)
        coll = PolyCollection(vertices_, array=color, zorder=zorder, clip_path=clip_path, **kwargs)
        coll.set_clim(vmin=vmin, vmax=vmax)
        coll.set_edgecolor("face")
        self.ax.add_collection(coll)
        return coll
示例#7
0
def tripcolor(ax, *args, **kwargs):
    """
    Create a pseudocolor plot of an unstructured triangular grid to
    the :class:`~matplotlib.axes.Axes`.

    The triangulation can be specified in one of two ways; either::

      tripcolor(triangulation, ...)

    where triangulation is a :class:`~matplotlib.tri.Triangulation`
    object, or

    ::

      tripcolor(x, y, ...)
      tripcolor(x, y, triangles, ...)
      tripcolor(x, y, triangles=triangles, ...)
      tripcolor(x, y, mask=mask, ...)
      tripcolor(x, y, triangles, mask=mask, ...)

    in which case a Triangulation object will be created.  See
    :class:`~matplotlib.tri.Triangulation` for a explanation of these
    possibilities.

    The next argument must be *C*, the array of color values, one per
    point in the triangulation.  The colors used for each triangle
    are from the mean C of the triangle's three points.

    The remaining kwargs are the same as for
    :meth:`~matplotlib.axes.Axes.pcolor`.

    **Example:**

        .. plot:: mpl_examples/pylab_examples/tripcolor_demo.py
    """
    if not ax._hold: ax.cla()

    alpha = kwargs.pop('alpha', 1.0)
    norm = kwargs.pop('norm', None)
    cmap = kwargs.pop('cmap', None)
    vmin = kwargs.pop('vmin', None)
    vmax = kwargs.pop('vmax', None)
    shading = kwargs.pop('shading', 'flat')

    tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs)
    x = tri.x
    y = tri.y
    triangles = tri.get_masked_triangles()

    # Vertices of triangles.
    verts = np.concatenate((x[triangles][...,np.newaxis],
                            y[triangles][...,np.newaxis]), axis=2)

    C = np.asarray(args[0])
    if C.shape != x.shape:
        raise ValueError('C array must have same length as triangulation x and'
                         ' y arrays')

    # Color values, one per triangle, mean of the 3 vertex color values.
    C = C[triangles].mean(axis=1)

    if shading == 'faceted':
        edgecolors = (0,0,0,1),
        linewidths = (0.25,)
    else:
        edgecolors = 'face'
        linewidths = (1.0,)
    kwargs.setdefault('edgecolors', edgecolors)
    kwargs.setdefault('antialiaseds', (0,))
    kwargs.setdefault('linewidths', linewidths)

    collection = PolyCollection(verts, **kwargs)

    collection.set_alpha(alpha)
    collection.set_array(C)
    if norm is not None: assert(isinstance(norm, Normalize))
    collection.set_cmap(cmap)
    collection.set_norm(norm)
    if vmin is not None or vmax is not None:
        collection.set_clim(vmin, vmax)
    else:
        collection.autoscale_None()
    ax.grid(False)

    minx = tri.x.min()
    maxx = tri.x.max()
    miny = tri.y.min()
    maxy = tri.y.max()
    corners = (minx, miny), (maxx, maxy)
    ax.update_datalim( corners)
    ax.autoscale_view()
    ax.add_collection(collection)
    return collection