예제 #1
0
def init_points(ax, points):
    pt_coll = PatchCollection(points, alpha=0.6)
    colors = ['limegreen'] * len(points)
    pt_coll.set_facecolors(colors)
    pt_coll.set_edgecolor('black')
    ax.add_collection(pt_coll)
    return pt_coll, colors
예제 #2
0
def add_pmts(ax=None, color='b', linewidth=1):

    x0 = 27  # 9 times the inner radius
    y0 = 6 * 3 * 2 / np.sqrt(3)  # 6 times the outer radius

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

    per_row = [9, 10, 11, 10, 11, 10, 11, 10, 9]

    polys = []
    for row, num_pmts in enumerate(per_row):

        y = row * 3 * np.sqrt(3)
        for pmt in range(num_pmts):
            x = 6 * pmt
            if row in (0, 8):
                x += 3
            elif row % 2 == 0:
                x -= 3

            polys.append(RegularPolygon((x - x0, y - y0), 6,  radius=6 / np.sqrt(3)))

    col = PatchCollection(polys)
    col.set_facecolors('none')
    col.set_edgecolors(color)
    col.set_linewidths(linewidth)
    ax.add_artist(col)

    return col
예제 #3
0
 def Cover(self, Sublist):
     for h in Sublist:
         if (len(h) > 3):
             HullList = self.ListHullPoints(h)
             self.CoverPolyPoints(HullList)
         else:
             self.CoverPolyPoints(h)
     p = PatchCollection(patches, alpha=0.4)
     PatchColor = []
     LegendPatch = []
     i = 1
     for patch in patches:
         c1 = np.random.rand(1, 1)[0]
         c2 = np.random.rand(1, 1)[0]
         c3 = np.random.rand(1, 1)[0]
         c = (c1[0], c2[0], c3[0])
         PatchColor.append(c)
         ax.add_patch(
             Polygon(patch.get_xy(), closed=True, ec=c, lw=1, fill=False))
         PatchPoints = patch.get_xy()
         x = (self.DrawPoints(PatchPoints))[0]
         y = (self.DrawPoints(PatchPoints))[1]
         PointColor = colors.to_rgba_array(c)
         Label = 'Conv ' + str(i)
         LegendPatch.append(mpatches.Patch(color=c, label=Label))
         self.ax.scatter(x, y, s=15, c=PointColor, marker='o', label='Poly')
         i += 1
     p.set_facecolors(PatchColor)
     self.ax.add_collection(p)
     self.ax.legend(handles=LegendPatch)
예제 #4
0
파일: plot.py 프로젝트: alexlib/FlyPlotLib
def get_circles_for_scatter(x, y, color='black', edgecolor='none', colormap='jet', radius=0.01, colornorm=None, alpha=1, radiusnorm=None, maxradius=1, minradius=0):
    cmap = plt.get_cmap(colormap)
    if colornorm is not None:
        colornorm = plt.Normalize(colornorm[0], colornorm[1], clip=True)
    
    # setup normalizing for radius scale factor (if used)
    if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
        if radiusnorm is None:
            radiusnorm = matplotlib.colors.Normalize(np.min(radius), np.max(radius), clip=True)
        else:
            radiusnorm = matplotlib.colors.Normalize(radiusnorm[0], radiusnorm[1], clip=True)

    # make circles
    points = np.array([x, y]).T
    circles = [None for i in range(len(x))]
    for i, pt in enumerate(points):    
        if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
            r = radiusnorm(radius[i])*(maxradius-minradius) + minradius
        else:
            r = radius
        circles[i] = patches.Circle( pt, radius=r )

    # make a collection of those circles    
    cc = PatchCollection(circles, cmap=cmap, norm=colornorm) # potentially useful option: match_original=True
    
    # set properties for collection
    cc.set_edgecolors(edgecolor)
    if type(color) is list or type(color) is np.array or type(color) is np.ndarray:
        cc.set_array(color)
    else:
        cc.set_facecolors(color)
    cc.set_alpha(alpha)
    
    return cc
예제 #5
0
def get_annotations(tiles_w, image_size, indices, coordinates):
	patches = []
	colors = []
	for index in range(canvas.shape[0]):
		x = index % tiles_w
		y = int(np.floor(index / tiles_w))

		tile = int(indices[index])
		if tile == -1:
			continue
		else:
			(lat, lon) = coordinates[tile]
			if np.isnan(lat) or np.isnan(lon):
				continue
			fc = lonlat2rgba(lon, lat)
			rect = mpatches.Rectangle((x * image_size, y * image_size), image_size, image_size)
			patches.append(rect)
			colors.append(fc)
			#image[((y + 1) * image_size, x * image_size):(x + 1) * image_size] = canvas[index]
	#colors = 100 * np.random.rand(len(patches))
	collection = PatchCollection(patches, alpha=0.35)
	collection.set_facecolors(colors)
	collection.set_edgecolors(colors)
	collection.set_linewidth(0.1)
	#collection.set_array(np.array(colors))
	return collection
예제 #6
0
def init_polygons(ax):
    polygons = read.polygons()
    poly_coll = PatchCollection(polygons, alpha=0.6)
    poly_colors = plt.get_cmap('Pastel1')(np.arange(.10, 1.99, .24))
    poly_coll.set_facecolors(poly_colors)
    poly_coll.set_edgecolor('black')
    ax.add_collection(poly_coll)

    return poly_coll, poly_colors
예제 #7
0
파일: plot.py 프로젝트: alexlib/FlyPlotLib
def get_ellipses_for_scatter(ax, x, y, color='black', edgecolor='none', colormap='jet', radius=0.01, colornorm=None, alpha=1, radiusnorm=None, maxradius=1, minradius=0):
    
    # get ellipse size to make it a circle given axes
    x0, y0 = ax.transAxes.transform((ax.get_ylim()[0],ax.get_xlim()[0]))
    x1, y1 = ax.transAxes.transform((ax.get_ylim()[1],ax.get_xlim()[1]))
    dx = x1-x0
    dy = y1-y0
    maxd = max(dx,dy)
    
    cmap = plt.get_cmap(colormap)
    if colornorm is not None:
        colornorm = plt.Normalize(colornorm[0], colornorm[1], clip=True)
    
    # setup normalizing for radius scale factor (if used)
    if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
        if radiusnorm is None:
            radiusnorm = matplotlib.colors.Normalize(np.min(radius), np.max(radius), clip=True)
        else:
            radiusnorm = matplotlib.colors.Normalize(radiusnorm[0], radiusnorm[1], clip=True)

    # make circles
    points = np.array([x, y]).T
    ellipses = [None for i in range(len(x))]
    for i, pt in enumerate(points):    
        if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
            r = radiusnorm(radius[i])*(maxradius-minradius) + minradius
        else:
            r = radius
        width = r*2*maxd/dx
        height = r*2*maxd/dy
        ellipses[i] = patches.Ellipse( pt, width, height)

    # make a collection of those circles    
    cc = PatchCollection(ellipses, cmap=cmap, norm=colornorm) # potentially useful option: match_original=True
    
    # set properties for collection
    cc.set_edgecolors(edgecolor)
    if type(color) is list or type(color) is np.array or type(color) is np.ndarray:
        cc.set_array(color)
    else:
        cc.set_facecolors(color)
    cc.set_alpha(alpha)
    
    return cc
예제 #8
0
    def render(self, patch_size=0.5, alpha=1.0, x_offset=100):
        '''Draws the legend graphic and saves it to a file.'''
        n = len(self.colors)
        s = patch_size

        # This offset is transformed to "data" coordinates (inches)
        left_offset = (-s * 1.5) - (x_offset / self.dpi)

        # Create grid to plot the artists
        grid = np.concatenate((
            np.zeros(n).reshape(n, 1),
            np.arange(-n, 1)[1:].reshape(n, 1)
        ), axis=1)

        plt.text(left_offset, 1.1, 'Legend', family='sans-serif',
            size=14, weight='bold', color='#ffffff')

        patches = []
        for i in range(n):
            # Add a rectangle
            rect = mpatches.Rectangle(grid[i] - [0, 0], s, s, ec='none')
            patches.append(rect)
            self.__label__(grid[i], self.labels[i], x_offset)

        collection = PatchCollection(patches, alpha=alpha)

        # Space the patches and the text labels
        collection.set_offset_position('data')
        collection.set_offsets(np.array([
            [left_offset, 0]
        ]))

        collection.set_facecolors(self.colors)
        #collection.set_edgecolor('#ffffff') # Draw color for box outlines

        self.axis.add_collection(collection)

        plt.axis('equal')
        plt.axis('off')
        plt.savefig(self.file_path, facecolor=self.bg_color, dpi=self.dpi,
            pad_inches=0)

        return self.file_path
예제 #9
0
def scatter(ax, x, y, color='black', colormap='jet', radius=0.01, colornorm=None, alpha=1, radiusnorm=None, maxradius=1, minradius=0, edgecolors='none'): 
    # color can be array-like, or a matplotlib color 
    # I can't figure out how to control alpha through the individual circle patches.. it seems to get overwritten by the collection. low priority!

    cmap = plt.get_cmap(colormap)
    if colornorm is not None:
        colornorm = plt.Normalize(colornorm[0], colornorm[1], clip=True)
    
    # setup normalizing for radius scale factor (if used)
    if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
        if radiusnorm is None:
            radiusnorm = matplotlib.colors.Normalize(np.min(radius), np.max(radius), clip=True)
        else:
            radiusnorm = matplotlib.colors.Normalize(radiusnorm[0], radiusnorm[1], clip=True)

    # make circles
    points = np.array([x, y]).T
    circles = [None for i in range(len(x))]
    for i, pt in enumerate(points):    
        if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
            r = radiusnorm(radius[i])*(maxradius-minradius) + minradius
        else:
            r = radius
        circles[i] = patches.Circle( pt, radius=r )

    # make a collection of those circles    
    cc = PatchCollection(circles, cmap=cmap, norm=colornorm) # potentially useful option: match_original=True
    
    # set properties for collection
    cc.set_edgecolors(edgecolors)
    if type(color) is list or type(color) is np.array or type(color) is np.ndarray:
        cc.set_array(color)
    else:
        cc.set_facecolors(color)
    cc.set_alpha(alpha)

    # add collection to axis    
    ax.add_collection(cc)  
예제 #10
0
def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs):
    """
    Make a scatter of circles plot of x vs y, where x and y are sequence 
    like objects of the same lengths. The size of circles are in data scale.

    Parameters
    ----------
    x,y : scalar or array_like, shape (n, )
        Input data
    s : scalar or array_like, shape (n, ) 
        Radius of circle in data unit.
    c : color or sequence of color, optional, default : 'b'
        `c` can be a single color format string, or a sequence of color
        specifications of length `N`, or a sequence of `N` numbers to be
        mapped to colors using the `cmap` and `norm` specified via kwargs.
        Note that `c` should not be a single numeric RGB or RGBA sequence 
        because that is indistinguishable from an array of values
        to be colormapped. (If you insist, use `color` instead.)  
        `c` can be a 2-D array in which the rows are RGB or RGBA, however. 
    vmin, vmax : scalar, optional, default: None
        `vmin` and `vmax` are used in conjunction with `norm` to normalize
        luminance data.  If either are `None`, the min and max of the
        color array is used.
    kwargs : `~matplotlib.collections.Collection` properties
        Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls), 
        norm, cmap, transform, etc.

    Returns
    -------
    paths : `~matplotlib.collections.PathCollection`

    Examples
    --------
    a = np.arange(11)
    circles(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none')
    plt.colorbar()

    License
    --------
    This code is under [The BSD 3-Clause License]
    (http://opensource.org/licenses/BSD-3-Clause)
    """
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    from matplotlib.collections import PatchCollection

    if np.isscalar(c):
        kwargs.setdefault('color', c)
        c = None
    if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc'))
    if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec'))
    if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls'))
    if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw'))

    patches = [Circle((x_, y_), s_) for x_, y_, s_ in np.broadcast(x, y, s)]
    collection = PatchCollection(patches, **kwargs)
    if c is not None:
        collection.set_array(np.asarray(c))
        collection.set_clim(vmin, vmax)
      
    collection.set_facecolors('none')
    collection.set_facecolor('none')
    if (kwargs['facecolor'] != 'none'):
        collection.set_facecolors(kwargs['facecolor']);
        collection.set_facecolor(kwargs['facecolor']);

    ax = plt.gca()
    ax.add_collection(collection)
    ax.autoscale_view()
    if c is not None:
        plt.sci(collection)
    return collection
예제 #11
0
def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs):
    """
    Make a scatter of circles plot of x vs y, where x and y are sequence 
    like objects of the same lengths. The size of circles are in data scale.

    Parameters
    ----------
    x,y : scalar or array_like, shape (n, )
        Input data
    s : scalar or array_like, shape (n, ) 
        Radius of circle in data unit.
    c : color or sequence of color, optional, default : 'b'
        `c` can be a single color format string, or a sequence of color
        specifications of length `N`, or a sequence of `N` numbers to be
        mapped to colors using the `cmap` and `norm` specified via kwargs.
        Note that `c` should not be a single numeric RGB or RGBA sequence 
        because that is indistinguishable from an array of values
        to be colormapped. (If you insist, use `color` instead.)  
        `c` can be a 2-D array in which the rows are RGB or RGBA, however. 
    vmin, vmax : scalar, optional, default: None
        `vmin` and `vmax` are used in conjunction with `norm` to normalize
        luminance data.  If either are `None`, the min and max of the
        color array is used.
    kwargs : `~matplotlib.collections.Collection` properties
        Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls), 
        norm, cmap, transform, etc.

    Returns
    -------
    paths : `~matplotlib.collections.PathCollection`

    Examples
    --------
    a = np.arange(11)
    circles(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none')
    plt.colorbar()

    License
    --------
    This code is under [The BSD 3-Clause License]
    (http://opensource.org/licenses/BSD-3-Clause)
    """
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    from matplotlib.collections import PatchCollection

    if np.isscalar(c):
        kwargs.setdefault('color', c)
        c = None
    if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc'))
    if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec'))
    if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls'))
    if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw'))

    patches = [Circle((x_, y_), s_) for x_, y_, s_ in np.broadcast(x, y, s)]
    collection = PatchCollection(patches, **kwargs)
    if c is not None:
        collection.set_array(np.asarray(c))
        collection.set_clim(vmin, vmax)

    collection.set_facecolors('none')
    collection.set_facecolor('none')
    if (kwargs['facecolor'] != 'none'):
        collection.set_facecolors(kwargs['facecolor'])
        collection.set_facecolor(kwargs['facecolor'])

    ax = plt.gca()
    ax.add_collection(collection)
    ax.autoscale_view()
    if c is not None:
        plt.sci(collection)
    return collection
예제 #12
0
    def plot(self,
             canvas,
             show_balls=True,
             show_adults=True,
             show_hulls=False,
             color='purple'):
        """
        Plot a single level of a `CoverTree`
        
        See the example at example-covertree_ 

        Parameters
        ----------
        canvas : :class:`bokeh.plotting.figure.Figure` 
            as obtained from :code:`canvas = bokeh.plotting.figure()`
        show_balls : bool
            Draw the covering balls at this level.
            Default: True
        show_adults : bool
            Draw the adults at this level.
            Default: True
        show_hulls : bool
            Draw the convex hulls of the childeren of each adult.
            Note -- this works only with matplotlib for now, not bokeh.
            Default: False
        color : str
            Name of color to use for cover-tree balls and hulls.
            Default: 'purple'

        References  
        ----------
        .. _example-covertree: http://nbviewer.jupyter.org/github/geomdata/gda-public/blob/master/examples/example-covertree.ipynb

        """

        # fix the aspect ratio!
        all_xs = self.pointcloud.coords.values[:, 0]
        all_ys = self.pointcloud.coords.values[:, 1]
        xmid = (all_xs.max() + all_xs.min()) / 2.0
        ymid = (all_ys.max() + all_ys.min()) / 2.0
        span = max([
            all_xs.max() - xmid, xmid - all_xs.min(),
            all_ys.max() - ymid, ymid - all_ys.min()
        ])

        if type(canvas).__module__ == 'bokeh.plotting.figure':
            canvas_type = "bokeh"
            from bokeh.models import ColumnDataSource, Range1d
            import bokeh.plotting
        elif type(canvas).__module__ == 'matplotlib.axes._subplots':
            canvas_type = "pyplot"
            import matplotlib.pyplot as plt
            from matplotlib.collections import PolyCollection, PatchCollection
            from matplotlib.patches import Circle, Ellipse, Polygon
            import matplotlib.colors as colors

            # fix the aspect ratio!
            canvas.set_aspect('equal')
            canvas.set_xlim([xmid - span, xmid + span])
            canvas.set_ylim([ymid - span, ymid + span])

        else:
            raise NotImplementedError(
                "canvas must be a bokeh.plotting.figure().  You gave me {}".
                format(type(canvas)))

        pc = self.covertree.pointcloud
        all_xs = pc.coords.values[:, 0]
        all_ys = pc.coords.values[:, 1]
        data, title = self.plot_data_title(show_balls=show_balls,
                                           show_adults=show_adults)

        # fix the aspect ratio!
        xmean = all_xs.mean()
        ymean = all_ys.mean()
        span = max([
            all_xs.max() - xmean, xmean - all_xs.min(),
            all_ys.max() - ymean, ymean - all_ys.min()
        ])

        if canvas_type == "pyplot":
            xs = data['xs']
            ys = data['ys']
            rs = data['rs']
            if show_balls:
                patches = []
                rgbas = []
                cc = colors.ColorConverter()
                for i in range(len(xs)):
                    patches.append(Circle(xy=(xs[i], ys[i]), radius=rs[i]))
                    # have to set the alpha value manually.
                    rgba = list(cc.to_rgba(color))
                    rgba[3] = 0.2
                    rgbas.append(tuple(rgba))
                p = PatchCollection(patches, edgecolor='none')
                p.set_facecolors(rgbas)
                canvas.add_collection(p)

            if show_adults:
                canvas.scatter(x=xs, y=ys, color='blue', alpha=1.)

            if show_hulls:
                from scipy.spatial import ConvexHull
                patches = []
                rgbas = []
                cc = colors.ColorConverter()
                for ai in self.adults:
                    children = pc.coords.values[self.children[ai], :]
                    if children.shape[0] >= 3:
                        hull = ConvexHull(children).vertices
                        poly_data = children[hull, :]
                        patches.append(Polygon(poly_data))
                    elif children.shape[0] == 2:
                        d = cdist(children[[0], :], children[[1], :])[0, 0]
                        patches.append(
                            Circle(xy=pc.coords.values[ai, :], radius=d))
                    else:  # singleton
                        patches.append(
                            Circle(xy=pc.coords.values[ai, :],
                                   radius=0.5 * self.radius))
                    rgba = list(cc.to_rgba(color))
                    rgba[3] = 0.2
                    rgbas.append(tuple(rgba))

                p = PatchCollection(patches, edgecolor=color)
                p.set_facecolors(rgbas)
                canvas.add_collection(p)
                pass

        elif canvas_type == "bokeh":
            source = ColumnDataSource(data=data)
            canvas.title.text = title
            canvas.x_range = Range1d(xmean - span, xmean + span)
            canvas.y_range = Range1d(ymean - span, ymean + span)
            if show_balls:
                canvas.circle('xs',
                              'ys',
                              source=source,
                              radius='rs',
                              color=color,
                              alpha=0.2)

            if show_adults:
                canvas.circle('xs',
                              'ys',
                              source=source,
                              size=4,
                              color='blue',
                              alpha=1.)

            if show_hulls:
                raise NotImplementedError("No hulls in Bokeh yet. Use pyplot.")

            #canvas.circle(all_xs, all_ys, color='black', alpha=0.2, size=0.5)

            return source
예제 #13
0
def plot_counties(
        ax,
        counties,
        values=None,
        edgecolors=None,
        contourcolor="white",
        hatch_surround=None,
        xlim=None,
        ylim=None,
        background=True,
        xticks=True,
        yticks=True,
        grid=True,
        frame=True,
        xlabel="Longitude [in dec. degrees]",
        ylabel="Latitude [in dec. degrees]",
        lw=1):
    polygons = [r["shape"] for r in counties.values()]
    # extend german borders :S and then shrink them again after unifying
    # gets rid of many holes at the county boundaries
    contour = cascaded_union([pol.buffer(0.01)
                              for pol in polygons]).buffer(-0.01)

    xmin, ymin, xmax, ymax = contour.bounds
    if xlim is None:
        xlim = [xmin, xmax]
    if ylim is None:
        ylim = [ymin, ymax]

    surround = PolygonPatch(Polygon([(xlim[0], ylim[0]), (xlim[0], ylim[1]), (
        xlim[1], ylim[1]), (xlim[1], ylim[0])]).difference(contour))
    contour = PolygonPatch(contour, lw=lw)

    pc = PatchCollection([PolygonPatch(p, lw=lw)
                          for p in polygons], cmap=matplotlib.cm.magma, alpha=1.0)


    

    

    if values is not None:
        if isinstance(values, (dict, OrderedDict)):
            values = np.array([values.setdefault(r, np.nan)
                               for r in counties.keys()])
        elif isinstance(values, str):
            values = np.array([r.setdefault(values, np.nan)
                               for r in counties.values()])
        else:
            assert np.size(values) == len(counties), "Number of values ({}) doesn't match number of counties ({})!".format(
                np.size(values), len(counties))
        pc.set_clim(0, 10)
        nans = np.isnan(values)
        values[nans] = 0

        values = np.ma.MaskedArray(values, mask=nans)
        pc.set(array=values, cmap='magma')
    else:
        pc.set_facecolors("none")

    if edgecolors is not None:
        if isinstance(edgecolors, (dict, OrderedDict)):
            edgecolors = np.array([edgecolors.setdefault(r, "none")
                                   for r in counties.keys()])
        elif isinstance(edgecolors, str):
            edgecolors = np.array([r.setdefault(edgecolors, "none")
                                   for r in counties.values()])
        pc.set_edgecolors(edgecolors)
    else:
        pc.set_edgecolors("none")

    if hatch_surround is not None:
        surround.set_hatch(hatch_surround)
        surround.set_facecolor("none")
        ax.add_patch(surround)

    cb = plt.colorbar(pc, shrink=0.6)
    cb.set_ticks([0,5,10])
    #cb.set_yticks([0.00004])
    ax.add_collection(pc)
    

    if contourcolor is not None:
        contour.set_edgecolor(contourcolor)
        contour.set_facecolor("none")
        ax.add_patch(contour)

    if isinstance(background, bool):
        ax.patch.set_visible(background)
    else:
        ax.patch.set_color(background)

    ax.grid(grid)

    ax.set_frame_on(frame)

    ax.set_xlim(*xlim)
    ax.set_ylim(*ylim)
    ax.set_aspect(1.43)
    if xlabel:
        ax.set_xlabel(xlabel, fontsize=14)
    if ylabel:
        ax.set_ylabel(ylabel, fontsize=14)

    ax.tick_params(axis="x", which="both", bottom=xticks, labelbottom=xticks)
    ax.tick_params(axis="y", which="both", left=yticks, labelleft=yticks)

    #plt.colorbar()
    

    return pc, contour, surround
예제 #14
0
파일: plot.py 프로젝트: alexlib/FlyPlotLib
def get_wedges_for_heading_plot(x, y, color, orientation, size_radius=0.1, size_angle=20, colormap='jet', colornorm=None, size_radius_range=(0.01,.1), size_radius_norm=None, edgecolor='none', alpha=1, flip=True, deg=True, nskip=0, center_offset_fraction=0.75):
    '''
    Returns a Patch Collection of Wedges, with arbitrary color and orientation
    
    Outputs:
    Patch Collection
    
    Inputs:
    x, y        - x and y positions (np.array or list, each of length N)
    color       - values to color wedges by (np.array or list, length N), OR color string. 
       colormap - specifies colormap to use (string, eg. 'jet')
       norm     - specifies range you'd like to normalize to, 
                  if none, scales to min/max of color array (2-tuple, eg. (0,1) )
    orientation - angles are in degrees, use deg=False to convert radians to degrees
    size_radius - radius of wedge, in same units as x, y. Can be list or np.array, length N, for changing sizes
       size_radius_norm - specifies range you'd like to normalize size_radius to, if size_radius is a list/array
                  should be tuple, eg. (0.01, .1)
    size_angle  - angular extent of wedge, degrees. Can be list or np.array, length N, for changing sizes
    edgecolor   - color for lineedges, string or np.array of length N
    alpha       - transparency (single value, between 0 and 1)
    flip        - flip orientations by 180 degrees, default = True
    nskip       - allows you to skip between points to make the points clearer, nskip=1 skips every other point
    center_offset_fraction  - (float in range (0,1) ) - 0 means (x,y) is at the tip, 1 means (x,y) is at the edge
    '''
    cmap = plt.get_cmap(colormap)
    
    # norms
    if colornorm is None and type(color) is not str:
        colornorm = plt.Normalize(np.min(color), np.max(color))
    elif type(color) is not str:
        colornorm = plt.Normalize(colornorm[0], colornorm[1])
    if size_radius_norm is None:
        size_radius_norm = plt.Normalize(np.min(size_radius), np.max(size_radius), clip=True)
    else:
        size_radius_norm = plt.Normalize(size_radius_norm[0], size_radius_norm[1], clip=True)
        
    indices_to_plot = np.arange(0, len(x), nskip+1)
        
    # fix orientations
    if type(orientation) is list:
        orientation = np.array(orientation)
    if deg is False:
        orientation = orientation*180./np.pi
    if flip:
        orientation += 180
    
    flycons = []
    n = 0
    for i in indices_to_plot:
        # wedge parameters
        if type(size_radius) is list or type(size_radius) is np.array or type(size_radius) is np.ndarray: 
            r = size_radius_norm(size_radius[i])*(size_radius_range[1]-size_radius_range[0]) + size_radius_range[0] 
        else: r = size_radius
        
        if type(size_angle) is list or type(size_angle) is np.array or type(size_angle) is np.ndarray: 
            angle_swept = size_radius[i]
        else: angle_swept = size_radius
        theta1 = orientation[i] - size_angle/2.
        theta2 = orientation[i] + size_angle/2.
        
        center = [x[i], y[i]]
        center[0] -= np.cos(orientation[i]*np.pi/180.)*r*center_offset_fraction
        center[1] -= np.sin(orientation[i]*np.pi/180.)*r*center_offset_fraction
        
        wedge = patches.Wedge(center, r, theta1, theta2)
        flycons.append(wedge)
        
    # add collection and color it
    pc = PatchCollection(flycons, cmap=cmap, norm=colornorm)
    
    # set properties for collection
    pc.set_edgecolors(edgecolor)
    if type(color) is list or type(color) is np.array or type(color) is np.ndarray:
        if type(color) is list:
            color = np.asarray(color)
        pc.set_array(color[indices_to_plot])
    else:
        pc.set_facecolors(color)
    pc.set_alpha(alpha)
    
    return pc
예제 #15
0
def plot_hexa_im(im,
                 cmap=matplotlib.cm.gray,
                 hex_shape=False,
                 ax=None,
                 zigzag=False,
                 minv=None,
                 maxv=None):
    """
    Plot a hexagonal image. The image is assumed to be represented with the zig-zag parameterization.

    :param im: the image; 2D ndarray
    """
    im[im == im.min()] = np.median(im)

    if zigzag:
        m1, m2 = centered_meshgrid(im.shape[1], im.shape[0])
        x, y = zigzaghexa2cartesian(m1, m2)
    else:
        # a bit strage to use centered_*zigzag*hexa_grid here, but it works
        m1, m2 = centered_meshgrid(im.shape[1], im.shape[0])
        x, y = hexa2cartesian(m1, m2)

    r = (np.minimum(im.shape[0], im.shape[1]) - 1) / 2.

    if ax is None:
        fig, ax = plt.subplots()

    x = x.flatten()
    y = y.flatten()
    m1 = m1.flatten()
    m2 = m2.flatten()
    r = r.flatten()
    im = im.flatten()

    if hex_shape:
        # Circular image; remove hexagons outside radius of the largest circle insribed in the grid
        if zigzag:
            n1, n2 = zigzaghexa2hexa(m1, m2)
        else:
            n1 = m1
            n2 = m2
        dist = hexa_manhattan_dist(n1, n2, 0, 0)
        x = x[dist <= r]
        y = y[dist <= r]
        im = im[dist <= r]

    # Flip the y-axis; in matplotlib's patches code, the y axis points up but we want it to point down
    # as is common in image processing.
    y = np.max(y) - y

    patch_list = [_hex_at(x[i], y[i]) for i in range(x.size)]
    p = PatchCollection(
        patch_list,
        cmap=cmap,
        linewidths=0,
        antialiaseds=10,
    )

    colors = im.reshape(-1, 3) - im.min()
    colors /= colors.max()

    p.set_facecolors(colors)  # set colors
    if minv or maxv:
        p.set_clim([minv, maxv])  # scale color range

    ax.add_collection(p)

    ax.set_xlim(np.min(x) - 0.5, np.max(x) + 0.5)
    ax.set_ylim(np.min(y) - 0.5, np.max(y) + 0.5)
    # plt.axis('equal')
    plt.axis('off')
    plt.tight_layout()
예제 #16
0
			kyst2[:,0][i],kyst2[:,1][i],zzz= lla2ecef(kyst2[:,0][i],kyst2[:,1][i],0)

		tmp = np.copy(-kyst2[:,0])
		kyst2[:,0]=kyst2[:,1]
		kyst2[:,1]=tmp

		polygon = Polygon(kyst2, True)
		patches_flds.append(polygon)
		kyst2 = np.array([])
		kll = np.array([])
		klo = np.array([])
#----------------------------------------------------------

#--
p_blks = PatchCollection(patches_blks,alpha=0.2)
p_blks.set_facecolors('none')#(1, 1, 0, 0.0))
p_blks.set_edgecolors((0, 0, 0, 1.0))
ax.add_collection(p_blks)
#--
#--
p_flds = PatchCollection(patches_flds,alpha=0.4)
p_flds.set_facecolors((.5, .5, .5, .5))
p_flds.set_edgecolors((0, 0, 0, 1.0))
ax.add_collection(p_flds)
#--
colors = 100*np.random.rand(len(patches))
p = PatchCollection(patches, alpha=0.4)
p.set_array(np.array(colors))
p.set_edgecolors((0, 0, 0, 1.0))
ax.add_collection(p)
예제 #17
0
    def plot(self, canvas, style="covertree"):
        r""" Plot a CDER model, using matplotlib or bokeh

        There are several options to help visualize various aspects of the
        model.  Typically, one wants to overlay this with the plots from the
        underlying :class:`multidim.PointCloud` and 
        :class:`multidim.covertree.CoverTree` objects.

        Parameters
        ----------
        canvas : object
            An instance of 
            `bokeh.plotting.figure.Figure` as in
            :code:`canvas = bokeh.plotting.figure()`
            or an instance of :class:`matplotlib.axes._subplots.AxesSubplot` as 
            in :code:`axes,canvas = matplotlib.pyplot.subplots()`

        style : str
            options are "gaussians", "covertree", "heatmap", "hulls", 
            "expatriots", and "predictions".  Colors are generally obtained
            from the label names.

        See Also
        --------
        :func:`multidim.PointCloud.plot`
        :func:`multidim.covertree.CoverTree.plot`


        """
        if self.covertree is None or self.gaussians is None:
            raise RuntimeError("You must 'fit' first, before plotting.")

        # fix the aspect ratio!
        all_xs = self.covertree.pointcloud.coords.values[:, 0]
        all_ys = self.covertree.pointcloud.coords.values[:, 1]
        xmid = (all_xs.max() + all_xs.min()) / 2.0
        ymid = (all_ys.max() + all_ys.min()) / 2.0
        span = max([
            all_xs.max() - xmid, xmid - all_xs.min(),
            all_ys.max() - ymid, ymid - all_ys.min()
        ])

        if type(canvas).__module__ == 'bokeh.plotting.figure':
            canvas_type = "bokeh"
            import bokeh.plotting
            from bokeh.models import ColumnDataSource, Range1d

            # fix the aspect ratio!
            canvas.x_range = Range1d(xmid - span, xmid + span)
            canvas.y_range = Range1d(ymid - span, ymid + span)

        elif type(canvas).__module__ == 'matplotlib.axes._subplots':
            canvas_type = "pyplot"
            import matplotlib.pyplot as plt
            from matplotlib.collections import PolyCollection, PatchCollection
            from matplotlib.patches import Circle, Ellipse, Polygon
            import matplotlib.colors as colors

            # fix the aspect ratio!
            canvas.set_aspect('equal')
            canvas.set_xlim([xmid - span, xmid + span])
            canvas.set_ylim([ymid - span, ymid + span])

        else:
            raise NotImplementedError(
                "canvas must be a bokeh.plotting.figure() or a matplotlib.pyplot.subplots()[1].  You gave me {}"
                .format(type(canvas)))

        if style == "gaussians":
            Xms = []
            Yms = []
            R1s = []
            R2s = []
            As = []
            Cs = []
            Ws = []
            for g in self.gaussians:
                Xms.append(g['mean'][0])
                Yms.append(g['mean'][1])
                R1s.append(g['std'][0] * 2 /
                           0.75)  # 0.75 bokeh oval distortion
                R2s.append(g['std'][1] * 2)
                As.append(np.arctan2(g['rotation'][0, 1], g['rotation'][0, 0]))
                Cs.append(g['label'])
                Ws.append(g['weight'])
            Ws = np.array(Ws)
            # Ws = np.log2(numpy.array(Ws)+1)
            Wmax = Ws.max()
            if canvas_type == "bokeh":
                canvas.oval(Xms,
                            Yms,
                            angle=As,
                            width=R1s,
                            height=R2s,
                            alpha=Ws / Wmax,
                            color=Cs,
                            line_width=0,
                            line_color='black')

            elif canvas_type == "pyplot":
                patches = []
                rgbas = []
                CC = colors.ColorConverter()
                for i in range(len(Xms)):
                    patches.append(
                        Ellipse(xy=(Xms[i], Yms[i]),
                                width=R1s[i] * 0.75,
                                height=R2s[i],
                                angle=As[i] * 180 / np.pi))
                    # have to manually set the alpha value
                    rgba = list(CC.to_rgba(Cs[i]))
                    rgba[3] = Ws[i] / Wmax
                    rgbas.append(tuple(rgba))

                p = PatchCollection(patches, edgecolor='none')
                p.set_facecolors(rgbas)
                canvas.add_collection(p)
            pass

        elif style == "heatmap":
            # This could probably use self.runit instead.
            xy = []

            min_x = xmid - span
            max_x = xmid + span
            min_y = ymid - span
            max_y = ymid + span

            dx = (max_x - min_x) / 64.
            dy = (max_y - min_y) / 64.
            for x in np.arange(min_x, max_x, dx):
                for y in np.arange(min_y, max_y, dy):
                    xy.append((x + dx / 2, y + dy / 2))
            xy = np.array(xy)

            z_by_label = np.ndarray(shape=(xy.shape[0],
                                           self.all_labels.shape[0]))

            for i, point in enumerate(xy):
                integrals, labels = self.evaluate(xy[[i], :])
                for j, label in enumerate(self.all_labels):
                    z_by_label[i,
                               j] = np.linalg.norm(integrals[labels == label],
                                                   1)

            # z_by_label = np.log2(z_by_label + 1)
            # z_by_label = z_by_label - z_by_label.min()
            z_by_label = z_by_label / z_by_label.max()
            # z_by_label = z_by_label**0.5

            if canvas_type == "bokeh":
                for j, label in enumerate(self.all_labels):
                    canvas.rect(xy[:, 0] - dx / 2,
                                xy[:, 1] - dy / 2,
                                width=dx,
                                height=dy,
                                color=label,
                                alpha=z_by_label[:, j])

            elif canvas_type == "pyplot":
                patches = []
                rgbas = []
                CC = colors.ColorConverter()
                for j, label in enumerate(self.all_labels):
                    for i in range(xy.shape[0]):
                        corners = np.array(
                            [[xy[i, 0] - dx / 2, xy[i, 1] - dx / 2],
                             [xy[i, 0] + dx / 2, xy[i, 1] - dx / 2],
                             [xy[i, 0] + dx / 2, xy[i, 1] + dy / 2],
                             [xy[i, 0] - dx / 2, xy[i, 1] + dy / 2]])
                        patches.append(Polygon(corners))
                        # have to manually set the alpha value
                        rgba = list(CC.to_rgba(label))
                        rgba[3] = z_by_label[i, j]
                        rgbas.append(tuple(rgba))

                p = PatchCollection(patches, edgecolor='none')
                p.set_facecolors(rgbas)
                canvas.add_collection(p)

            pass

        elif style == "hulls":
            from scipy.spatial import ConvexHull
            if canvas_type == "bokeh":
                raise NotImplementedError("No hulls in Bokeh yet. Use pyplot.")
            elif canvas_type == "pyplot":
                maxwt = max([g['weight'] for g in self.gaussians])
                patches = []
                rgbas = []
                cc = colors.ColorConverter()

                for i, g in enumerate(self.gaussians):
                    if g['count'] > 3:
                        a = g['index']
                        l = g['level']
                        cl = self.covertree[l]
                        label = g['label']
                        children = self.covertree.pointcloud.coords.values[
                            cl.children[a], :]
                        hull = ConvexHull(children).vertices
                        poly_data = children[hull, :]
                        patches.append(Polygon(poly_data))
                        # have to manually set the alpha value
                        rgba = list(cc.to_rgba(label))
                        rgba[3] = g['weight'] * 1.0 / maxwt
                        rgbas.append(tuple(rgba))

                p = PatchCollection(patches, edgecolor='none')
                p.set_facecolors(rgbas)
                canvas.add_collection(p)
                pass

        elif style == "entropy":
            N = len(self.covertree)
            C = np.zeros(shape=(N, ))
            Q = np.zeros(shape=(N, ))
            for g in self.gaussians:
                C[g['level']:] = C[g['level']:] + 1.0
                Q[g['level']:] = Q[g['level']:] + (1.0 - g['entropy'])
            canvas.scatter(range(N), C, color="red", legend="coords", size=4)
            canvas.line(range(N), C, color="red")
            canvas.scatter(range(N), Q, color="blue", legend="bits", size=2)
            canvas.line(range(N), Q, color="blue")
            canvas.legend.location = "top_left"
            pass

        elif style == "expatriots":
            Xms = []
            Yms = []
            R1s = []
            R2s = []
            As = []
            Cs = []
            Ws = []
            for g in self.gaussians:
                Xms.append(g['mean'][0])
                Yms.append(g['mean'][1])
                R1s.append(g['std'][0] * 2 /
                           0.75)  # 0.75 bokeh oval distortion
                R2s.append(g['std'][1] * 2)
                As.append(np.arctan2(g['rotation'][0, 1], g['rotation'][0, 0]))
                Cs.append(g['label'])
                Ws.append(g['weight'])
            Ws = np.log2(np.array(Ws) + 1)
            Wmax = Ws.max()
            if canvas_type == "bokeh":
                canvas.oval(Xms,
                            Yms,
                            angle=As,
                            width=R1s,
                            height=R2s,
                            alpha=Ws / Wmax,
                            color=Cs,
                            line_width=0,
                            line_color='black')

            elif canvas_type == "pyplot":
                patches = []
                rgbas = []
                CC = colors.ColorConverter()
                for i in range(len(Xms)):
                    patches.append(
                        Ellipse(xy=(Xms[i], Yms[i]),
                                width=R1s[i] * 0.75,
                                height=R2s[i],
                                angle=As[i] * 180 / np.pi))
                    # have to manually set the alpha value
                    rgba = list(CC.to_rgba(Cs[i]))
                    rgba[3] = Ws[i] / Wmax
                    rgbas.append(tuple(rgba))

                p = PatchCollection(patches, edgecolor='none')
                p.set_facecolors(rgbas)
                canvas.add_collection(p)
            pass

        elif style == "predictions":
            pass
        elif style == "covertree":
            Xs = []
            Ys = []
            Rs = []
            Cs = []
            Ws = []
            for g in self.gaussians:
                Xs.append(g['adult'][0])
                Ys.append(g['adult'][1])
                Rs.append(g['radius'])
                Cs.append(g['label'])
                Ws.append(1.0 - g['entropy'])
            Ws = np.array(Ws)
            # Ws = np.log2(np.array(Ws)+1)
            Wmax = Ws.max()
            if canvas_type == "bokeh":
                canvas.circle(Xs,
                              Ys,
                              radius=Rs,
                              alpha=Ws / Wmax,
                              color=Cs,
                              line_width=0,
                              line_color='black')
            elif canvas_type == "pyplot":
                patches = []
                rgbas = []
                cc = colors.ColorConverter()
                for i in range(len(Xs)):
                    patches.append(Circle(xy=(Xs[i], Ys[i]), radius=Rs[i]))
                    # have to manually set the alpha value
                    rgba = list(cc.to_rgba(Cs[i]))
                    rgba[3] = Ws[i] / Wmax
                    rgbas.append(tuple(rgba))

                p = PatchCollection(patches, edgecolor='none')
                p.set_facecolors(rgbas)
                canvas.add_collection(p)
            pass

        else:
            raise ValueError("Wrong plot style.")
예제 #18
0
        votpts[0, 0] = 0.0
        votpts[nx - 1, 1] = batmax + tol
        votpts[0, 1] = batmax + tol
        sshpts[0, 1] = sshpts[1, 1]
        for pt in range(nx):
            sshpts[pt + nx, 0] = batpts[nx + 1 - pt, 0]
            sshpts[pt + nx, 1] = batpts[nx + 1 - pt, 1]

        xs, ys = zip(*votpts)
        fig, ax = plt.subplots()

        patches = []
        polygon = Polygon(batpts, True)
        patches.append(polygon)
        p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=1.0)
        p.set_facecolors(['#f1a9a9'])

        patches = []
        polygon2 = Polygon(sshpts, True)
        patches.append(polygon2)
        p2 = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=1.0)
        p2.set_facecolors(['#44a1ff'])

        # Maximum depth set here to -10m
        ax.set_ylim([-10., 6.0])
        ax.set_xlim([0., 51.0])
        ax.add_collection(p2)
        ax.add_collection(p)
        ax.plot(xs, ys, '--', color='black', ms=10)

        plt.annotate(hour, xy=(2, batmin + 0.1 * brange))
예제 #19
0
def make_piechart(slices, colors, ecolors, outname, showtext=True, groups=[[0,1],[2,3]], radfraction=0.2, transparent=False):
    assert len(groups) == 2
    plt.close('all')
    fig, ax = plt.subplots(figsize=(5,5))
    wedgeprops = {'edgecolor':'k', 'linewidth':6}

    patches, texts, pcts = ax.pie(slices, labeldistance=1.15, colors=colors, autopct=lambda p: '{:1.1f}\%'.format(p), wedgeprops=wedgeprops)
    [pct.set_fontsize(20) for pct in pcts]
    ax.axis('equal')

    for patch, ecolor in zip(patches, ecolors):
        patch.set_edgecolor(ecolor)

    fig.savefig('{}'.format(outname), transparent=True)
    plt.close('all')


    fig, ax = plt.subplots(figsize=(5,5))
    ax.axis('equal')
    ax.axis('off')
    #embed()
    i = groups[0]
    ang = np.deg2rad((patches[i[-1]].theta2 + patches[i[0]].theta1)/2.0)
    wedges = []
    for j in i:
        patch = patches[j]
        center = (radfraction*patch.r*np.cos(ang), radfraction*patch.r*np.sin(ang))
        wedges.append(mpatches.Wedge(center, patch.r, patch.theta1, patch.theta2, edgecolor=patch.get_edgecolor(), facecolor=patch.get_facecolor()))
        text_ang = np.deg2rad((patch.theta1 + patch.theta2)/2.0)
        pct = pcts[j].get_text()
        if slices[j] == 0:
            pct = ''
            fontsize = 10
        elif slices[j] < 0.01:
            fontsize = 10
        elif slices[j] < 0.1:
            fontsize = 15
        else:
            fontsize = 20
        if text_ang > np.pi and text_ang < (3*np.pi)/2.0:
            align='top'
            text_pos = np.array(((1.12)*patch.r*np.cos(text_ang), (1.12)*patch.r*np.sin(text_ang))) + np.array(center)
        else:
            align='baseline'
            text_pos = np.array(((1.08)*patch.r*np.cos(text_ang), (1.08)*patch.r*np.sin(text_ang))) + np.array(center)
        if showtext:
            ax.text(*text_pos, s=pct, fontsize=fontsize, verticalalignment=align)
    i = groups[1]
    for j in i:
        try:
            patch = patches[j]
        except:
            embed()
        center = patch.center
        
        wedges.append(mpatches.Wedge(center, patch.r, patch.theta1, patch.theta2, edgecolor=patch.get_edgecolor(), facecolor=patch.get_facecolor()))
        text_ang = np.deg2rad((patch.theta1 + patch.theta2)/2.0)
        pct = pcts[j].get_text()
        if slices[j] == 0:
            pct = ''
            fontsize = 10
        elif slices[j] < 0.01:
            fontsize = 10
        elif slices[j] < 0.1:
            fontsize = 15
        else:
            fontsize = 20
        if text_ang > np.pi and text_ang < (3*np.pi)/2.0:
            align='top'
            text_pos = np.array(((1.12)*patch.r*np.cos(text_ang), (1.12)*patch.r*np.sin(text_ang))) + np.array(center)
        else:
            align='baseline'
            text_pos = np.array(((1.08)*patch.r*np.cos(text_ang), (1.08)*patch.r*np.sin(text_ang))) + np.array(center)
        if showtext:
            ax.text(*text_pos, s=pct, fontsize=fontsize, verticalalignment=align)

    collection = PatchCollection(wedges)
    collection.set_facecolors(colors)
    collection.set_linewidths(6)
    collection.set_edgecolors(ecolors)

    #collection.set_array(np.array(colors))
    ax.add_collection(collection)
    ax.autoscale(True)
    #ax.text(*pcts[0].get_position(), s=pcts[0].get_text())

    fig.savefig('{}_nolabel'.format(outname), transparent=transparent)

    plt.close('all')