Beispiel #1
0
def polygon_subplots(polys, names=None, columns=2, figsize=(12, 24), dpi=300):
    if names is None:
        names = range(len(polys))
    colors = colormap.rescale_and_interpolate(colormap.turbo_colormap_data,
                                              range(0, len(polys)))
    fig = plt.figure(figsize=figsize, dpi=dpi)
    rows = len(polys) // columns
    if len(polys) % columns != 0:
        rows += 1
    for i, (poly, name, color) in enumerate(zip(polys, names, colors)):
        try:
            ax = fig.add_subplot(rows, columns, i + 1)
            ax.axis("equal")
            ax.add_patch(PolygonPatch(poly, facecolor=color, linewidth=0.1))
            ax.autoscale()
            ax.set_title(name)
            ax.set_xticks([])
            ax.set_yticks([])
        except ValueError as e:
            continue
    plt.show()
Beispiel #2
0
def plotOne(step):
    fig = plt.figure(figsize=(6, 8))
    ax1 = plt.subplot2grid((4, 3), (0, 0), rowspan=3, colspan=3)
    ax2 = plt.subplot2grid((4, 3), (3, 0), colspan=3)
    for ii, particle in enumerate(box.particleSteps[step]):
        topcolor = "blue"
        pt = Point(particle[2], particle[3]).buffer(particle[1], cap_style=1)
        patch = PolygonPatch(pt, fc=topcolor)
        ax1.add_patch(patch)
    ax1.set_ylim([0, height])
    ax1.set_xlim([0, width])

    # plot histogram of speeds
    speeds = [x[4] for x in box.particleSteps[step]]
    bins = numpy.linspace(0, 3 * v, 50)
    ax2.hist(speeds, bins=bins)
    ax2.set_xlim([0, 3 * v])
    # ax2.set_ylim([0, nParticles*1.1])
    ax2.set_xlabel("velocity")
    plt.savefig("step_%08d.png" % step, dpi=150)
    plt.close()
Beispiel #3
0
def disegna_stanze(stanze, colori, xmin, ymin, xmax, ymax,savefig  =  True, format='pdf', filepath = '.', savename = '8_Stanze', title = False):
	'''
	disegna il layout delle stanze.
	'''
	fig, ax = setup_plot()
	savename = os.path.join(filepath, savename+'.'+format)

	#plt.subplot(224)
	if title :
		ax.set_title('7.stanze')
	
	for index,s in enumerate(stanze):
		f_patch = PolygonPatch(s,fc=colori[index],ec='BLACK') 
		ax.add_patch(f_patch)
		ax.set_xlim(xmin,xmax)
		ax.set_ylim(ymin,ymax)
	if savefig :
		plt.savefig(savename,bbox_inches='tight')
	else :
		plt.show()
	return (fig, ax)
	def draw_concave_hull(cls, xy):
		#pts = [xy[vertice] for vertice in spatial.ConvexHull(xy).vertices]
		#pts = [xy[vertice] for vertice in alphashape.alphashape(xy, 2).vertices]

		# alpha-parameter can be removed to reoptimize alpha
		#print(optimizealpha(xy, max_iterations=100000))
		#pts = alphashape(xy, 2.2)
		print(len(xy))
		pts = alphashape(xy, 4.235604062127975e-05)

		#pts = alphashape(xy, 7.235604062127975e-06)
		#pts = alphashape(xy, 7.235604062127975e-06)
		#pts = alphashape(xy, 1.9846167135906253e-05)

		#pts = alphashape.alphashape(xy, 2)

		# add 10 km buffer zone for error
		plt.gca().add_patch(
			PolygonPatch(
				pts.buffer(10000),
				color='#de9752', alpha=0.5, zorder=3, transform=ccrs.epsg(3067)))
Beispiel #5
0
    def _plot_gdf(self, gdf, kwargs={}, ax=None):
        """
        Plot geodataframe to axis
        This function will plot a default style for all geometry types.

        Paramaters
        ----------
        gdf : geopandas.GeoDataFrame
            geodataframe with data to plot
        kwargs : dictionary
            dictionary with keyword arguments for plotting
        ax : matplotlib.pyplot.axes
            axes to plot to
        """  
        if ax is None:
            ax = self.ax

        # get geometries
        if isinstance(gdf, gpd.GeoSeries):
            geometries = [gdf['geometry']]
        else:
            geometries = gdf['geometry'].values.tolist()

        # for line and pts
        if isinstance(geometries[0], LineString):
            # Create collection
            segments = [np.vstack(geo.coords[:]) for geo in geometries]
            collection = ax.add_collection(LineCollection(segments, **kwargs))

        if isinstance(geometries[0], Polygon):
            # Create collection
            polygons = [PolygonPatch(geo) for geo in geometries]
            collection = ax.add_collection(PatchCollection(polygons, **kwargs))

        if isinstance(geometries[0], Point):
            kwargs['linestyle'] = ''
            crds = np.vstack([pt.coords[0] for pt in geometries])
            collection, = ax.plot(*crds.T, **kwargs)

        return collection
Beispiel #6
0
    def get_patches(self,
                    origin=(0, 0),
                    angle_sum=0,
                    angle=0,
                    layers: Optional[List[int]] = None):
        from descartes import PolygonPatch

        def rotate_pos(pos, rotation_angle):
            if rotation_angle is None:
                return pos
            c, s = np.cos(rotation_angle), np.sin(rotation_angle)
            result = np.array([[c, -s], [s, c]]).dot(pos)
            return result

        own_patches = []
        for layer, geometry in self.layer_dict.items():
            if layers is not None and layer not in layers:
                continue
            geometry = geometric_union(geometry)
            if geometry.is_empty:
                continue
            geometry = translate(
                rotate(geometry, angle_sum, use_radians=True, origin=(0, 0)),
                *origin)
            own_patches.append(
                PolygonPatch(geometry,
                             color=['red', 'green', 'blue', 'teal',
                                    'pink'][(layer - 1) % 5],
                             linewidth=0))

        sub_cells_patches = [
            p for cell_dict in self.cells
            for p in cell_dict['cell'].get_patches(
                np.array(origin) + rotate_pos(cell_dict['origin'], angle),
                angle_sum=angle_sum + (cell_dict['angle'] or 0),
                angle=cell_dict['angle'],
                layers=layers)
        ]

        return own_patches + sub_cells_patches
Beispiel #7
0
    def plot_polygon(rec, ax=None, **kwargs):
        """method to plot the polygon intersection results from
        the resulting numpy.recarray.

        Note: only works when recarray has 'intersects' column!

        Parameters
        ----------
        rec : numpy.recarray
            record array containing intersection results
            (the resulting shapes)
        ax : matplotlib.pyplot.axes, optional
            axes to plot onto, if not provided, creates a new figure
        **kwargs:
            passed to the plot function

        Returns
        -------
        ax: matplotlib.pyplot.axes
            returns the axes handle

        """
        try:
            import matplotlib.pyplot as plt
        except ImportError:
            print('This feature requires matplotlib.')
        try:
            from descartes import PolygonPatch
        except ModuleNotFoundError:
            raise ModuleNotFoundError(
                "descartes module needed for plotting polygons")

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

        for i, ishp in enumerate(rec.ixshapes):
            ppi = PolygonPatch(ishp, facecolor="C{}".format(i % 10), **kwargs)
            ax.add_patch(ppi)

        return ax
Beispiel #8
0
def plot_mover(hallway, hallway_set, theta, N, i, hway_num, smooth=True):
    plt.cla()  #clear axis in the case it had already been opened

    if smooth == True:
        try:
            carver = get_carver(hallway_set)
            print("smoothing rotation path")
            hallway = hallway.difference(carver)
        except:
            print("failed to carve")

    mp = round(len(hallway_set) / 2)

    minx, miny, maxx, maxy = hallway.bounds

    plt.style.use('ggplot')
    fig = plt.figure(dpi=200, figsize=(5, 3))
    ax = fig.add_subplot(111)
    ax.grid(False)
    ax.set_xlim([minx - .5, maxx + .5])
    ax.set_ylim([miny - .3, maxy + .5])
    ax.set_aspect(1)

    #uncomment for wireframe display
    #for i in range(1,len(hallway_set)):
    #    hallway_set[i] = rotate(hallway_set[i], 90-a, origin=(0,0))
    #    x,y = hallway_set[i].exterior.xy
    #    plt.plot(x,y,linewidth=.4)

    x, y = hallway_set[hway_num].exterior.xy
    plt.plot(x, y, linewidth=.2, color='grey')

    #plot one hallway

    ax.add_patch(PolygonPatch(hallway, ec="none"))
    plt.title(str(hallway.area) + "N:" + str(N))
    fig.savefig("a:" + str(theta) + "_N:" + str(N) + "_Smth:" + str(smooth) +
                "_j:" + str(hway_num) + ".png",
                dpi=900)
    plt.close()
Beispiel #9
0
def plotRedistrictingGroups(redistrictingGroups,
                            showPopulationCounts=False,
                            showGraphIds=False,
                            showDistrictNeighborConnections=False):
    fig = pyplot.figure()
    ax = fig.gca()

    colorIndex = 0
    for redistrictingGroup in redistrictingGroups:
        if showDistrictNeighborConnections:
            for neighborGroup in redistrictingGroup.allNeighbors:
                if neighborGroup in redistrictingGroups:
                    ax.add_line(
                        getLineForPair(redistrictingGroup, neighborGroup,
                                       grayColor))

        ax.add_patch(
            PolygonPatch(redistrictingGroup.geometry,
                         fc=getColor(colorIndex),
                         ec=getColor(colorIndex),
                         alpha=0.5,
                         zorder=2))

        if showPopulationCounts:
            centerOfGroup = redistrictingGroup.geometry.centroid
            ax.text(x=centerOfGroup.x,
                    y=centerOfGroup.y,
                    s=redistrictingGroup.population,
                    fontdict=font)

        if showGraphIds:
            centerOfGroup = redistrictingGroup.geometry.centroid
            ax.text(x=centerOfGroup.x,
                    y=centerOfGroup.y,
                    s=redistrictingGroup.graphId,
                    fontdict=font)
        colorIndex += 1

    ax.axis('scaled')
    pyplot.show()
Beispiel #10
0
def catchment_plot_2sided(data,datacid,shpname,joinid_index,fn,maxcolorval):
    #make a plot with 10 color gradations and a colorbar to go with it
    base=plt.cm.get_cmap('seismic')
    color_list=base(np.linspace(0,1,21))
    seis21=base.from_list('seis21',color_list,21)
    #cmap=jet
    #ncar=plt.get_cmap('gist_ncar')
    #define 10 colors in the list
    #cmaplist=[jet(0),jet(25),jet(50),jet(75),jet(100),jet(125),jet(150),jet(175),jet(250),ncar(195)]
    #cmap=cmap.from_list('Custom cmap',cmaplist,10)
    fig=plt.figure()
    ax=fig.add_axes([0,0,1,1])
    #ax=fig.add_subplot(221)
    data=np.squeeze(data)
    #cmap=plt.cm.jet
    polys=shp.Reader(shpname)
    mymax=float(maxcolorval)
    for r1,r2 in zip(polys.shapeRecords(),polys.records()):
	shpcid=int(float(r2[joinid_index]))
        val=data[datacid==shpcid]
        poly=r1.shape.__geo_interface__
        f=val/mymax
        patch=PolygonPatch(poly,fc=seis21(f[0]),ec=seis21(f[0]),alpha=0.8)
        ax.add_patch(patch)
    ax.axis('scaled')
    plt.savefig(fn,dpi=200)
    plt.close()
#Plot colorbar
    fig2=plt.figure()
    ax2=fig2.add_axes([0.1,0.1,.8,0.2])
    m=np.zeros((1,10))
    for i in range(0,10):
        m[0,i]=(i)/10.0
    xtickvals=[k*mymax for k in [0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1]]
    ax2.imshow(m,cmap=jet10,interpolation='nearest',vmin=0,vmax=1,aspect=1)
    ax2.set_yticks(np.arange(0))
    ax2.set_xticks(np.linspace(-0.5,9.5,11))
    ax2.set_xticklabels(xtickvals)
    plt.savefig(fn+'_cbar.png',dpi=200)
    plt.close()
Beispiel #11
0
def vis_polygon(ax,type,region,commune,color_type=''):

    path = path_data+'{}/json/{}/'.format(type,region)

    if not isinstance(commune,list):
        communes = [commune]

    filenames = []
    for commune in communes:
        filenames += glob.glob(path+'{}*'.format(commune))

    for filename in filenames:
        print(filename[-20:])
        file = open(filename,'r')
        json_data = json.load(file)
        if color_type == 'greenspace':
            greens = json_data['properties']['greenspace']
            factor = 0.0
            for green in greens:
                if green[1] != 0:
                    factor += green[0]/(green[1]*green[1])
            cmap = matplotlib.cm.get_cmap('viridis')
            color = cmap(factor/1.0)
        elif color_type == 'area':
            cmap = matplotlib.cm.get_cmap('viridis')
            area = json_data['properties']['area']
            if area > 0.00001:
                color = '#ff0000'
            else:
                color = '#00ff00'
        else:
            color = '#ffffff'

        poly = json_data['geometry']

        ax.add_patch(PolygonPatch(poly, fc=color, ec='#000000', lw=0.2, zorder=2))
        ax.add_patch(Circle(json_data['properties']['center'], radius=0.00005, fc='#000000', ec='#000000', lw=0.2, zorder=2))
        ax.axis('scaled')
        ax.set_xlabel('lng')
        ax.set_ylabel('lat')
Beispiel #12
0
def test_gml_repository():
    if "RASPUTIN_DATA_DIR" not in os.environ:
        raise RuntimeError("Please set RASPUTIN_DATA_DIR")
    path = Path(os.environ["RASPUTIN_DATA_DIR"]) / "corine"
    input_crs = pyproj.CRS.from_string("+init=EPSG:4326")
    target_crs = pyproj.CRS.from_epsg(32633)

    x = np.array([8.5, 8.52, 8.52, 8.5])
    y = np.array([60.55, 60.55, 60.50, 60.50])

    x, y = pyproj.Transformer.from_crs(input_crs, target_crs).transform(x, y)
    domain = GeoPolygon(polygon=Polygon(shell=list(zip(x, y))), crs=target_crs)

    repos = GMLRepository(path=path)
    plot = False
    if plot:
        response = repos.read(domain=domain)
        fig = plt.figure()
        ax = fig.gca()
        for key in response:
            color = [c / 255 for c in LandCoverType.color(land_cover_type=key)]
            for p in response[key]:
                ax.add_patch(PolygonPatch(p, fc=color, alpha=0.5))
        ax.set_xbound(min(x), max(x))
        ax.set_ybound(min(y), max(y))
        plt.show()

    dem_archive = Path(os.environ["RASPUTIN_DATA_DIR"]) / "dem_archive"
    rr = RasterRepository(directory=dem_archive)
    raster_domain = domain.transform(
        target_crs=pyproj.CRS.from_proj4(rr.coordinate_system(domain=domain)))
    raster_data_list = rr.read(domain=raster_domain)
    mesh = Mesh.from_raster(data=raster_data_list, domain=raster_domain)

    cmesh = mesh.simplify(ratio=0.1)
    geo_cell_centers = GeoPoints(xy=cmesh.cell_centers[:, :2], crs=target_crs)
    terrain_cover = repos.land_cover(land_types=None,
                                     geo_points=geo_cell_centers,
                                     domain=domain)
    assert terrain_cover is not None
def show_results_for_antenna_circle_cover(fileName) :
    plt.figure(dpi=90)
    # get the current axes.
    ax = plt.gca()
    f = open(fileName)
    result = json.load(f)
    coverage_filename = result["detection_coverage_file"]
    indexes = result["indexes"]
    angles = result["angles"]
    center = result["center"]
    points_to_cover = result["points_to_cover"]
    detection_coverage = antennacover.read_detection_coverage(coverage_filename)
    circ = None
    for k in range(0,len(indexes)):
        polygon = detection_coverage[indexes[k]][1]
        rotated_cover = antennacover.rotate(polygon,angles[k])
        rotated_translated_cover = antennacover.translate(rotated_cover,center)
        if circ is None:
            circ = rotated_translated_cover
        else:
            circ = circ.union(rotated_translated_cover)
        p = PolygonPatch(rotated_translated_cover, fc=GRAY, ec=GRAY, alpha=0.5, zorder=2)
        ax.add_patch(p)

    for p in points_to_cover:
        plot_point(ax,p,RED)
    
    xmin = float(circ.bounds[0])
    ymin = float(circ.bounds[1])
    xmax = float(circ.bounds[2])
    ymax = float(circ.bounds[3])
    ax.set_xlim([xmin,xmax])
    ax.set_ylim([ymin,ymax])
    
    if os.path.dirname(fileName) != '':
        mpl.rcParams["savefig.directory"] = os.chdir(os.path.dirname(fileName))
    else:
        mpl.rcParams["savefig.directory"] = os.chdir("./")

    plt.show()
    def plot_field(self):

        lot_polygons = []
        landuse = []
        colours = []

        for i in list(set(self.g.vs.select()['lot_number'])):

            lots = self.g.vs.select(lot_number=i)
            landuse = lots[0]['landuse']
            colours.append(self.landuse_color_dic[landuse])

            points = lots['coords']
            polygons = []

            for lot in points:

                polygon = Polygon(lot)
                polygons.append(polygon)

            merge = cascaded_union(polygons)
            merge_patch = PolygonPatch(merge)
            lot_polygons.append(merge_patch)

        pc = plt_c.PatchCollection(lot_polygons,
                                   edgecolor='black',
                                   facecolor=colours)

        fig, ax = plt.subplots(figsize=(30, 50))
        ax.set_aspect("equal")

        ax.add_collection(pc)
        ax.set_title('Fakefield City')
        xrange = [-1, max(self.x_coords)]
        yrange = [min(self.y_coords), -1]
        ax.set_xlim(xrange)

        ax.set_ylim(yrange)

        ax.set_aspect(1)
Beispiel #15
0
def _plot_geometry(geom, fill='#ffcccc', stroke='#333333', alpha=1, msg=None):
    from matplotlib import pyplot
    from matplotlib.figure import SubplotParams
    from descartes import PolygonPatch

    if isinstance(geom, (Polygon, MultiPolygon)):
        b = geom.bounds
        geoms = hasattr(geom, 'geoms') and geom.geoms or [geom]
        w, h = (b[2] - b[0], b[3] - b[1])
        ratio = w / h
        pad = 0.15
        fig = pyplot.figure(1, figsize=(5, 5 / ratio), dpi=110, subplotpars=SubplotParams(left=pad, bottom=pad, top=1 - pad, right=1 - pad))
        ax = fig.add_subplot(111, aspect='equal')
        for geom in geoms:
            patch1 = PolygonPatch(geom, linewidth=0.5, fc=fill, ec=stroke, alpha=alpha, zorder=0)
            ax.add_patch(patch1)
    p = (b[2] - b[0]) * 0.03  # some padding
    pyplot.axis([b[0] - p, b[2] + p, b[3] + p, b[1] - p])
    pyplot.grid(True)
    if msg:
        fig.suptitle(msg, y=0.04, fontsize=9)
    pyplot.show()
Beispiel #16
0
def add_ring(ax=None, radius=None, mapping=False, color=None, lw=1):

    from shapely.geometry import Polygon
    from descartes import PolygonPatch

    if mapping:
        m = mapping[0]
        olat = mapping[1]
        olon = mapping[2]
        c = Circlem.circle(m, olat, olon, radius * 1000.)
        circraw = Polygon(c)
        circ = PolygonPatch(circraw, fc='none', ec=color)
    else:
        circ = plt.Circle((0, 0),
                          radius,
                          fill=False,
                          color=color,
                          linewidth=lw)

    ax.add_patch(circ)

    return circ
Beispiel #17
0
def plot_bootstrapped_attributes_diagram(figure_object, axes_object,
                                         ci_bottom_dict, ci_mean_dict,
                                         ci_top_dict, num_examples_by_bin):
    """Bootstrapped version of plot_attributes_diagram.

    :param figure_object: Instance of `matplotlib.figure.Figure`.
    :param axes_object: Instance of `matplotlib.axes._subplots.AxesSubplot`.
    :param ci_bottom_dict: See doc for `plot_bootstrapped_reliability_curve`.
    :param ci_mean_dict: Same.
    :param ci_top_dict: Same.
    :param num_examples_by_bin: See doc for `plot_attributes_diagram`.
    """

    plot_attributes_diagram(
        figure_object=figure_object,
        axes_object=axes_object,
        mean_forecast_by_bin=ci_mean_dict[model_eval.MEAN_FORECAST_BY_BIN_KEY],
        event_frequency_by_bin=ci_mean_dict[model_eval.EVENT_FREQ_BY_BIN_KEY],
        num_examples_by_bin=num_examples_by_bin)

    polygon_object = _confidence_interval_to_polygon(
        x_coords_bottom=ci_bottom_dict[model_eval.MEAN_FORECAST_BY_BIN_KEY],
        y_coords_bottom=ci_bottom_dict[model_eval.EVENT_FREQ_BY_BIN_KEY],
        x_coords_top=ci_top_dict[model_eval.MEAN_FORECAST_BY_BIN_KEY],
        y_coords_top=ci_top_dict[model_eval.EVENT_FREQ_BY_BIN_KEY])

    if polygon_object is None:
        return

    polygon_colour = matplotlib.colors.to_rgba(
        plotting_utils.colour_from_numpy_to_tuple(RELIABILITY_COLOUR),
        POLYGON_OPACITY)

    polygon_patch = PolygonPatch(polygon_object,
                                 lw=0,
                                 ec=polygon_colour,
                                 fc=polygon_colour)

    axes_object.add_patch(polygon_patch)
Beispiel #18
0
def getShapefile(excelFileName, excelSheetName, plotFlag):

    # wb = load_workbook('MapLimitPoint.xlsx')
    wb = load_workbook(excelFileName)
    for i in range(len(excelSheetName)):
        ws = wb[excelSheetName[i]]
        print excelSheetName[i]
        pointsArea = []
        for row in ws.iter_rows(min_row=ws['A1'].value,
                                min_col=ws['B1'].value,
                                max_col=ws['C1'].value,
                                max_row=ws['D1'].value):
            onePoint = []
            for cell in row:
                onePoint.append(cell.value)
            pointsArea.append(onePoint)

        # writing region boundary into a shape file
        print 'shapefiles/CDShapeFiles/' + excelSheetName[i]
        w = sf.Writer()
        w.poly(parts=[pointsArea])
        w.field('FIRST_FLD', 'C')
        w.save('shapefiles/CDShapeFiles/' + excelSheetName[i])

    # plot the shapefile
    if plotFlag == 1:
        fig = plt.figure()
        BLUE = '#6699cc'
        for i in range(len(excelSheetName)):
            polys = sf.Reader("shapefiles/CDShapeFiles/" + excelSheetName[i] +
                              ".shp")
            poly = polys.iterShapes().next().__geo_interface__
            ax = fig.gca()
            ax.add_patch(
                PolygonPatch(poly, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2))
            ax.axis('scaled')
        plt.show()

    return
def show_ship_polygons(img, polygons):
    patches = []
    for polygon in polygons:
        patches.append(PolygonPatch(polygon))
    patch_collection = PatchCollection(patches)
    patch_collection.set_color('yellow')

    fig, ax = plt.subplots(1, 1, figsize=(20, 20))
    ax.imshow(img)
    ax.set_xticks([])
    ax.set_yticks([])
    plt.savefig('./proc_img.png')
    plt.show()

    fig, ax = plt.subplots(1, 1, figsize=(20, 20))
    ax.imshow(img)
    ax.add_collection(patch_collection)
    ax.autoscale()
    ax.set_xticks([])
    ax.set_yticks([])
    plt.savefig('./masked_img.png')
    plt.show()
Beispiel #20
0
def drawBBox(min_lon, min_lat, max_lon, max_lat, base_map, **kwargs):
    """
    Draw bounding box on a basemap

    :param min_lon: Minimum longitude
    :type min_lon: float
    :param min_lat: Minimum latitude
    :type min_lat: float
    :param max_lon: Maximum longitude
    :type max_lon: float
    :param max_lat: Maximum latitude
    :type max_lat: float
    :param base_map: Basemap on which to draw the bounding box
    :type base_map: mpl_toolkits.basemap.Basemap
    """
    bblons = np.array([min_lon, max_lon, max_lon, min_lon, min_lon])
    bblats = np.array([min_lat, min_lat, max_lat, max_lat, min_lat])

    x, y = base_map(bblons, bblats)
    xy = zip(x, y)
    poly = Polygon(xy)
    base_map.ax.add_patch(PolygonPatch(poly, **kwargs))
Beispiel #21
0
def plot_gdf(gdf, margin=0.1):
    """
    Plot GeoDataFrame and set the correst aspect ratio.

    :param gdf: A :py:class:`Polygon` or :py:class:`MultiPolygon`
    """
    ax = pyplot.gca()
    ax.set_facecolor(COLOR_BACKGROUND)

    polygon = gdf["geometry"].unary_union

    patch = PolygonPatch(polygon, fc=COLOR_GROUND, ec=COLOR_GROUND, zorder=-1)
    ax.add_patch(patch)

    west, south, east, north = polygon.bounds

    margin_ns = (north - south) * margin
    margin_ew = (east - west) * margin

    ax.set_xlim((west - margin_ew, east + margin_ew))
    ax.set_ylim((south - margin_ns, north + margin_ns))
    ax.set_aspect("equal")
Beispiel #22
0
    def plot_environment(self):
        minx, miny, maxx, maxy = self.env.bounds

        max_width, max_height = 5, 5
        figsize = (max_width, max_height)
        f = plt.figure(figsize=figsize)
        ax = f.add_subplot(111)
        for i, obs in enumerate(self.env.obstacles):
            patch = PolygonPatch(obs,
                                 fc='blue',
                                 ec='blue',
                                 alpha=0.5,
                                 zorder=20)
            ax.add_patch(patch)

        plt.xlim([minx, maxx])
        plt.ylim([miny, maxy])
        ax.set_aspect('equal', adjustable='box')
        # Cancel coordinate axis display
        ax.set_xticks([])
        ax.set_yticks([])
        return ax
Beispiel #23
0
def plotDebug(polygons, layerName, xrange, yrange):
    """
    Plots the set of given polygons and gives the plot a title of layerName
    :type polygons: list
    :type layerName: str
    :type xrange: tuple
    :type yrange: tuple
    """

    fig = pyplot.figure(1, figsize=(10, 10), dpi=90)
    ax = fig.add_subplot(111)

    for ob in polygons:
        p = PolygonPatch(ob, fc='g', ec='g', alpha=0.5, zorder=1)
        ax.add_patch(p)

    ax.set_xlim(*xrange)
    ax.set_ylim(*yrange)
    ax.set_aspect(1)
    ax.set_title(layerName)

    pyplot.show()
def plot_polygon_data(
    poly: Union[Polygon, MultiPolygon],
    points: Union[MultiPoint, np.ndarray],
    color_labels: np.ndarray,
    bounds: Optional[Tuple] = None,
    title: str = "",
) -> None:
  points = maybe_to_array(points)

  fig, ax = plt.subplots(dpi=120)

  path = PolygonPatch(poly, fc=BLUE, ec=BLUE, alpha=0.4)
  ax.add_patch(path)

  gray = "#E6E6E3"
  palette = sns.husl_palette(n_colors=max(color_labels)).as_hex()
  if min(color_labels) == -1:
    palette.append(gray)
    color_labels[color_labels == -1] = max(color_labels) + 1
  cmap = ListedColormap(palette)

  ax.scatter(
      x=points[:, 0],
      y=points[:, 1],
      alpha=0.8,
      s=4 * 2,
      c=color_labels,
      cmap=cmap)

  if title:
    ax.set_title(title)

  if bounds:
    bounds = tuple(int(p) for p in bounds)
    set_limits(ax, bounds[0], bounds[2], bounds[1], bounds[3])
  else:
    ax.autoscale_view()
  plt.show()
Beispiel #25
0
def assign_neighborhood(lat, lon):
    # Read in neighborhood shape file
    hood_shapefilename = '/Users/sydneydecoto/Documents/PythonScripts/Neighborhoods/WGS84/Neighborhoods'
    hood_coords = parse_shapes(hood_shapefilename)

    w, h = hood_coords[2] - hood_coords[0], hood_coords[3] - hood_coords[1]
    extra = 0.005

    m = Basemap(projection='tmerc',
                ellps='WGS84',
                lon_0=np.mean([hood_coords[0], hood_coords[2]]),
                lat_0=np.mean([hood_coords[1], hood_coords[3]]),
                llcrnrlon=hood_coords[0] - extra * w,
                llcrnrlat=hood_coords[1] - (extra * h),
                urcrnrlon=hood_coords[2] + extra * w,
                urcrnrlat=hood_coords[3] + (extra * h),
                resolution='i',
                suppress_ticks=True)

    # get dataframe for plotting
    _out, df_map = plot_prepper(m, hood_shapefilename, 'S_HOOD')
    nbr_names = df_map['name'].unique()

    # map neighborhoods to polygon patches
    df_map['patches'] = df_map['poly'].map(
        lambda x: PolygonPatch(x, ec='#111111', lw=.8, alpha=1., zorder=4))

    # convert latitude and longitude to point on basemap
    xpt, ypt = m(lon, lat)
    pt = Point(xpt, ypt)

    # loop through neighborhoods until neighborhood containing point is found
    for polygon in df_map['poly']:
        hood_name = df_map.loc[df_map['poly'] == polygon, 'name'].iloc[0]
        if len(hood_name.strip()) < 4:
            continue
        if polygon.contains(pt):
            return hood_name
Beispiel #26
0
    def __init__(self, delta_state, start_angle = 0, isbackward=False):
        length = 3.0
        width = 2.0
        self.delta_state = delta_state
        self.start_angle = start_angle
        self.cost = dubins.path_length((0,0,self.start_angle), delta_state, motion_primitive.turning_radius)
        path_list, _ = dubins.path_sample((0,0,self.start_angle), self.delta_state, 
            motion_primitive.turning_radius, 0.1)
        self.path = np.array(path_list)

        self.isbackward = isbackward
        if self.isbackward:
            self.delta_state[:2] = -self.delta_state[:2] #(-0.25*np.cos(start_angle),-0.25*np.sin(start_angle),start_angle)
            self.path[:,0:2] = -1*self.path[:,0:2]
            #self.path = [(-xx,-yy,tth) for (xx,yy,tth) in self.path]
            #self.cost *= 2

        box_angle_tuples = [(box(x - length/2, y - width/2, x + length/2, y + width/2), theta) for (x,y,theta) in self.path]
        polygons = [affinity.rotate(a_box, theta, origin = 'centroid', use_radians = True) for (a_box, theta) in box_angle_tuples]
        
        if False:
            fig = plt.figure(10)
            fig.clear()
            plt.ion()
            ax = fig.add_subplot(111, aspect = 'equal')
            for poly in polygons:
                P = PolygonPatch(poly, fc = 'k', zorder = 2)
                ax.add_patch(P)
            ax.set_xlim(-5,5)
            ax.set_ylim(-5,5)
            fig.show()
            

        polygons = [poly.buffer(0.1) for poly in polygons]
        try:
            self.bounding_poly = cascaded_union(polygons).simplify(0.05)
        except:
            raise Exception('No bounding poly for primitive')
Beispiel #27
0
def init_map(size_field, ax, radius):

    size_field = 40

    pos = []
    polygons = []
    for x in range(5, 40, 5):
        for y in range(5, 40, 5):
            pos.append((x, y))

    for coord in pos:
        dd = Point(coord[0], coord[1]).buffer(1)
        rrwe = PolygonPatch(dd,
                            facecolor='#8A2BE2',
                            edgecolor='#8A2BE2',
                            alpha=0.9,
                            zorder=2)
        ax.add_patch(rrwe)
        polygons.append(dd)

    ax.axis([0, size_field, 0, size_field], 'equal')

    return polygons
def plot_polys(spatial_dict, axes, geojson=True):
    '''
    plot image with layer of spatial objects from dictionary
    args:
        spatial_dict:  Keys are the class labels and values are polygons
        axes: matplotlib axes object on which to plot
    '''

    if not bool(spatial_dict):
        print("no polygons to plot")
    else:

        for class_label in spatial_dict.keys():
            if geojson:
                color_mapped = mapping_dict[class_label]
            else:
                color_mapped = class_label
            for geom in spatial_dict[class_label]:
                axes.add_patch(
                    PolygonPatch(geom,
                                 alpha=0.65,
                                 ec=colors[color_mapped],
                                 fc=colors[color_mapped]))
def PlotDistrict(district, dims, filename):
    minx, miny, maxx, maxy = dims
    fig = plt.figure()
    if isinstance(district['geom'], Polygon):
        this_shape = MultiPolygon([district['geom']])
    else:
        this_shape = district['geom']
    ax = fig.add_subplot(1, 1, 1)
    w, h = maxx - minx, maxy - miny
    ax.set_xlim(minx - 0.0 * w, maxx + 0.0 * w)
    ax.set_ylim(miny - 0.0 * h, maxy + 0.0 * h)
    ax.set_aspect(1)
    ax.axis('off')
    patches = [
        PolygonPatch(p, fc="black", ec='#555555', alpha=1., zorder=1)
        for p in this_shape
    ]
    ax.add_collection(PatchCollection(patches, match_original=True))
    print("Saving {0}".format(filename))
    plt.savefig(filename, alpha=True, dpi=300, bbox_inches='tight')
    plt.clf()
    plt.cla()
    plt.close()
Beispiel #30
0
 def plot_solution_space(self):
     
     # figure formatting
     fig, ax = plt.subplots()
     ax.axis('square')
     ax.set_xlim(self.x_lim[0], self.x_lim[1])
     ax.set_ylim(self.y_lim[0], self.y_lim[1])
     ax.set_xlabel('x')
     ax.set_ylabel('y')
     ax.set_title('Possible Hand Endpoint Locations')
     
     # add the possible hand endpoints
     ax.scatter(*zip(*self.possible_endpoints), 0.1)
     
     # add a circle to show where the shoulder is
     circle = patches.Circle((self.joints[0].location[0], self.joints[0].location[1]), 
                             0.015, fill=True)
     ax.add_patch(circle)
     plt.annotate('shoulder', 
                  (self.joints[0].location[0], self.joints[0].location[1]))
     
     # add the alpha shape
     ax.add_patch(PolygonPatch(self.alpha_shape, alpha=0.2))