def vennplot(AintB,cardA,RatioBoverA,radB,alpha_value): if AintB > cardA: AintB = cardA radA = math.sqrt(1/RatioBoverA)*radB xpntA= .5+radB+(1-2*(AintB/cardA))*radA B = sg.Point(.5, .5).buffer(radB) A = sg.Point(xpntA, .5).buffer(radA) left = A.difference(B) right = B.difference(A) middle = A.intersection(B) ax = plt.gca() ax.add_patch(descartes.PolygonPatch(left, fc='b', ec='k', alpha=alpha_value)) ax.add_patch(descartes.PolygonPatch(right, fc='r', ec='k', alpha=alpha_value)) ax.add_patch(descartes.PolygonPatch(middle, fc='g', ec='k', alpha=alpha_value)) font = {'family': 'serif', 'color': 'black', 'weight': 'normal', 'size': 18} ax.text(0.5,.5+radB , r'$B$', horizontalalignment='left', verticalalignment='bottom', fontdict=font, usetex=True) ax.text(xpntA+radA, 0.5, r'$A$', horizontalalignment='left', verticalalignment='bottom', fontdict=font, usetex=True) ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.spines['top'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.set_aspect('equal') plt.xticks([]) plt.yticks([]) pltfigpath = '../Paper/Figs/Venn-AintB=%s-Ratio=%s.png' % (AintB,int(RatioBoverA)) plt.savefig(pltfigpath, transparent=True) plt.close()
def plot_circles(x, y, score, ofile, x_hobbies, y_hobbies): plt.figure() # create the circles with shapely x0 = 0 a = sg.Point(x0 - (0.5 - score / 2), 0).buffer(1.) b = sg.Point(x0 + (0.500001 - score / 2), 0).buffer(1.) # a = sg.Point(x0 - 0.5, 0).buffer(1.) # b = sg.Point(x0 + 0.5, 0).buffer(1.) # compute the 3 parts left = a.difference(b) right = b.difference(a) middle = a.intersection(b) # use descartes to create the matplotlib patches ax = plt.gca() ax.add_patch(descartes.PolygonPatch(left, fc='b', ec='k', alpha=0.2)) ax.add_patch(descartes.PolygonPatch(right, fc='r', ec='k', alpha=0.2)) ax.add_patch(descartes.PolygonPatch(middle, fc='g', ec='k', alpha=0.2)) plt.gca().text(-0.7, 1.5, x, fontsize=15, horizontalalignment='center', alpha=0.5, color='b') plt.gca().text(0.7, 1.5, y, fontsize=15, horizontalalignment='center', alpha=0.5, color='r') plt.gca().text(0, -1.5, round(score, 2), fontsize=15, horizontalalignment='center', alpha=0.5, color='g') plt.gca().text(0, 0, '\n'.join(x_hobbies & y_hobbies), fontsize=15, horizontalalignment='center', alpha=0.5, color='g') # control display ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_aspect('equal') plt.savefig(ofile, dpi=300) # plt.show() plt.close()
def plot_map(self, imap): self.ax.clear() # creating end area polygon for drawing ea = [] ea.append((self.dataset["{}".format(imap)].x[0], self.dataset["{}".format(imap)].y[0])) ea.append((self.dataset["{}".format(imap)].x[0], self.dataset["{}".format(imap)].y[1])) ea.append((self.dataset["{}".format(imap)].x[1], self.dataset["{}".format(imap)].y[1])) ea.append((self.dataset["{}".format(imap)].x[1], self.dataset["{}".format(imap)].y[0])) end_area = shapely.geometry.Polygon(ea) # creating map line for drawing verts = [] for i in range(2, len(self.dataset["{}".format(imap)].x)): verts.append([ self.dataset["{}".format(imap)].x[i], self.dataset["{}".format(imap)].y[i] ]) map_line = shapely.geometry.LineString(verts) # initial car and dir line inicar = shapely.geometry.Point( self.dataset["{}".format(imap)].start[0], self.dataset["{}".format(imap)].start[1]).buffer(3) self.dir_point = (4 * (math.cos( self.dataset["{}".format(imap)].start[2] * math.pi / 180)), 4 * (math.sin(self.dataset["{}".format(imap)].start[2] * math.pi / 180))) self.car_center = (self.dataset["{}".format(imap)].start[0], self.dataset["{}".format(imap)].start[1]) # plot on figurecanvas self.ax.plot(*np.array(map_line).T, color='k', linewidth=3, solid_capstyle='round') self.ax.add_patch(descartes.PolygonPatch(end_area, fc='red', alpha=0.7)) self.dir = self.ax.arrow(*self.car_center, *self.dir_point, head_width=1, head_length=1, fc='gold', ec='k') self.car = self.ax.add_patch( descartes.PolygonPatch(inicar, fc='royalblue', alpha=0.5)) self.ax.autoscale(enable=True, axis='both', tight=None) self.draw()
def plot_fetch_pedagogical_example(): import shapely.geometry as sg import descartes print(np.random.get_state()) M = sg.Polygon([(-1.0, -1.0), (-1.0, 1.0), (1.0, 1.0), (1.0, -1.0)]) v = np.random.uniform(-1.0, 1.0, size=2) good_inter = None bad_union = None good_circles = [] bad_circles = [] for i in range(6): u = _sample_color_within_radius(v, 0.5) f = _sample_color_with_min_dist(v, 0.5) good_c = sg.Point(*u).buffer(0.5) good_c = good_c.intersection(M) good_circles.append(good_c) bad_c = sg.Point(*f).buffer(0.5) bad_c = bad_c.intersection(M) bad_circles.append(bad_c) if good_inter is None: good_inter = good_c else: good_inter = good_inter.intersection(good_c) if bad_union is None: bad_union = bad_c else: bad_union = bad_union.union(bad_c) fig, ax = plt.subplots(1) for g in good_circles: ax.add_patch(descartes.PolygonPatch(g, fc='green', ec='green', alpha=0.1)) for b in bad_circles: ax.add_patch(descartes.PolygonPatch(b, fc='pink', ec='pink', alpha=0.3)) # ax.add_patch(descartes.PolygonPatch(bad_union, fc='pink', ec='pink', alpha=0.3)) ax.add_patch(descartes.PolygonPatch(good_inter.difference(bad_union), fc='green', ec='green', alpha=1.0)) plt.plot([v[0]], [v[1]], marker='*', markeredgecolor='gold', markerfacecolor='gold', markersize=20.0) # markersize ax.set_xlim([-1.0,1.0]) ax.set_ylim([-1.0,1.0]) ax.set_aspect('equal') plt.savefig('plots/junk_vis/fetch/img_%d.png'%i, bbox_inches='tight', dpi=150) plt.close()
def overlay_primus(PRIMUS_tab0, ax): ''' Overlay PRIMUS pointings Parameters ---------- Returns ------- ax with Circle patch added Notes ----- Created by Chun Ly, 19 March 2018 - Use shapely and descartes to plot PRIMUS pointing as intersection of square (27.2') and circle (radius=14.94') Modified by Chun Ly, 21 March 2018 - Plotting aesthetics (transparent field boundaries) ''' c_ra = PRIMUS_tab0['RACEN'].data c_dec = PRIMUS_tab0['DECCEN'].data bsz = 0.453 / 2.0 # in degree for ii in range(len(PRIMUS_tab0)): coord = [c_ra[ii], c_dec[ii]] circ = sg.Point(coord[0], coord[1]).buffer(0.249) #30.0/60.0) box = sg.box(c_ra[ii] - bsz, c_dec[ii] - bsz, c_ra[ii] + bsz, c_dec[ii] + bsz) int0 = circ.intersection(box) ax.add_patch( descartes.PolygonPatch(int0, fc='none', ec='purple', alpha=0.3)) #endfor return ax
def plot_polygons(ax, polygon_dict, color_dict, zorder_dict, legend=True, **legend_kwargs): """ Plot the polygon on a matplotlib Axes. ------------ INPUT |---- ax (matplotlib.Axes) the axes on which to plot |---- polygon_dict (dict) dictionnary of shapely.MultiPolygon for each classe by name |---- color_dict (dict) the color associated with each classes |---- legend (bool) whether to add a legend to the plot |---- zorder_dict (dict) the order of stacking the classes |---- legend_kwargs (kwargs) keywords arguments for the legend OUTPUT |---- None """ for class_name in list(zorder_dict.keys()): ax.add_patch(descartes.PolygonPatch(polygon_dict[class_name], \ color=color_dict[class_name], \ zorder=zorder_dict[class_name], \ linewidth=0, label=class_name)) if legend: ax.legend(**legend_kwargs)
def show_polygons(rgb, fp, poly_list): ''' Display polygons from a polygon list in a array linked to the adapted footprint Parameters ---------- rgb : np.ndarray image in rgb format (n,d,3) fp : footprint footprint linked to the array poly_list : list of shapely.geometry.polygons objects list of polygons to display ''' # Show image with matplotlib and descartes fig = plt.figure(figsize=(5. / fp.height * fp.width, 5)) plt.title('Roof boundary') ax = fig.add_subplot(111) ax.imshow(rgb, extent=[fp.lx, fp.rx, fp.by, fp.ty]) for poly in poly_list: ax.add_patch( descartes.PolygonPatch(poly, fill=False, ec='#ff0000', lw=3, ls='--')) plt.show()
def plot_cb_poly(cb_poly, opts): w_cb, h_cb = opts['width_cb'], opts['height_cb'] plt.figure(figsize=(10, 10)) plt.gca().add_patch(descartes.PolygonPatch(cb_poly)) plt.gca().set_xlim((-w_cb / 2, w_cb / 2)) plt.gca().set_ylim((-h_cb / 2, h_cb / 2)) plt.gca().set_aspect(1)
def show_prediction(name, x, y): print("Predicting {}".format(name), x.shape, y.shape) hm = m.m.predict(np.asarray([x]), 1, True)[0] print(f'heat-map min{hm.min()} max{hm.max()} mean{hm.mean()}') hm = accuracy.Heatmap(hm, True) centroids = [np.flipud(cen) for cen in hm.centroids_yx] print(f'{len(centroids)} centroids -> {centroids}') imgs = [y, x] + [img for (img, _) in hm.images] patchess = [()] * len(imgs) patchess[-1] = ([ descartes.PolygonPatch(sg.Point(cen).buffer(15), alpha=0.4, zorder=1, fc='white', ec='red', lw=2) for cen in centroids ]) tags = ['x', 'y'] + [title for (_, title) in hm.images] show_many_images( imgs, tags, patchess, )
def plot_polygon(self, axes=None): """ Plots the polygon used for the Dymaxion projection This is really just to check that I've got my vertex ordering all sorted """ axes = axes or plt.gca() cmap = plt.get_cmap('coolwarm') for idx, face in enumerate(self.faces): color = cmap(idx / len(self.faces)) shape = shapely.geometry.Polygon(self.vertices[face][:, :2]) axes.add_patch( descartes.PolygonPatch(shape, alpha=0.5, linewidth=2, facecolor=color, edgecolor='black')) face_axis = numpy.vstack(([0, 0], self.face_centres[idx][:2])).T axes.plot(*face_axis, marker='o', linewidth=3, color=color, markerfacecolor=color, markeredgecolor=color, alpha=0.4) axes.set_xlim(-1, 1) axes.set_ylim(-1, 1) axes.set_aspect("equal") axes.set_axis_off()
def _addPolygonForRoi(self, roiFile: pwsdt.RoiFile): roi = roiFile.getRoi() if roi.verts is not None: poly: PathPatch = descartes.PolygonPatch(roi.polygon, facecolor=(1, 0, 0, 0.5), linewidth=1, edgecolor=(0, 1, 0, 0.9)) poly.set_picker(0) # allow the polygon to trigger a pickevent self._plotWidget.ax.add_patch(poly) self.rois.append(RoiParams(roiFile, poly, False))
def plot_multipolygon(ax, mp, **kwargs): area_limit = 0.9 q = [ descartes.PolygonPatch(p, **kwargs) for p in mp if p.area > area_limit ] for p in q: ax.add_patch(p)
def display_results(file, gt_train="AerialImageDataset/train/gt/", images_train="AerialImageDataset/train/images/", polygons_path="geoJSON/", downsampling_factor=1): geojson_file = polygons_path + file.split('.')[0] + '.geojson' ds = buzz.DataSource(allow_interpolation=True) ds.open_raster('rgb', images_train + file) ds.open_vector('roofs', geojson_file, driver='geoJSON') # Build a low resolution Footprint to perform quicker calculations fp = buzz.Footprint( tl=ds.rgb.fp.tl, size=ds.rgb.fp.size, rsize=ds.rgb.fp.rsize // downsampling_factor, ) polygons = ds.roofs.iter_data(None) rgb = ds.rgb.get_data(band=(1, 2, 3), fp=fp).astype('uint8') fig = plt.figure(figsize=(5. / fp.height * fp.width, 5)) plt.title('Roof boundary') ax = fig.add_subplot(111) ax.imshow(rgb, extent=[fp.lx, fp.rx, fp.by, fp.ty]) for polygon_roof in polygons: ax.add_patch( descartes.PolygonPatch(polygon_roof, fill=False, ec='#ff0000', lw=3, ls='--')) plt.show()
def plot_polygon(p, mac, ts): ax = fig.add_subplot(1, 1, 1) ax.set_title(mac + '\n' + str(ts) + '\n' + str(p.centroid)) ax.set_xlim(-100, 100) ax.set_ylim(-50, 100) ax.add_patch(descartes.PolygonPatch(p, fc='b', ec='k', alpha=0.2)) plt.pause(2)
def plot_idealized_projection( self, ax, cmap=palettable.matplotlib.Magma_16.mpl_colormap, vmin=None, vmax=None, log_color_scale=False, patch_kwargs=None, **kwargs): '''Plot the full idealized projection. Args: ax (matplotlib.axes): Axes to plot the projection on. cmap : Colormap to use for the colors of the different shapes. vmin (float): Lower limit for the color axis. vmax (float): Upper limit for the color axis. ''' # Create the most up-to-date projection first self.generate_idealized_projection(**kwargs) values = self.ip_values if log_color_scale: values = np.log10(values) # Colorlimits if vmin is None: vmin = values.min() / 1.2 if vmax is None: vmax = 1.2 * values.max() def color_chooser(value): # Choose the patch color color_value = ((value - vmin) / (vmax - vmin)) color = cmap(color_value) return color self.color_chooser = color_chooser used_patch_kwargs = { 'linewidth': 0, } if patch_kwargs is not None: used_patch_kwargs.update(patch_kwargs) for i, s in enumerate(self.ip): color = color_chooser(values[i]) # Add the patch patch = descartes.PolygonPatch(s, zorder=i, fc=color, **used_patch_kwargs) ax.add_patch(patch) ax.set_xlim(self.x_min, self.x_max) ax.set_ylim(self.y_min, self.y_max)
def _outer_border(ax, emotion_score, color, angle, highlight, offset = .15, height_width_ratio = 1, normalize = False): """ Draw a the outer border of a petal. Required arguments: ---------- *ax*: Axes to draw the coordinates. *emotion_score*: Score of the emotion. Values range from 0 to 1. *color*: Color of the petal. See emo_params(). *angle*: Rotation angle of the petal. See emo_params(). *highlight*: String. 'opaque' if the petal must be shadowed, 'regular' is default. *offset*: Central neutral circle has radius = .15, and petals must start from there. *height_width_ratio*: Ratio between height and width of the petal. Lower the ratio, thicker the petal. Default is 1. *normalize*: Either False or the highest value among emotions. If not False, must normalize all petal lengths. """ if normalize: emotion_score /= normalize # Computing proportions. h = 1*emotion_score + offset x = height_width_ratio*emotion_score y = h/2 r = sqrt(x**2 + y**2) # Computing rotated centers x_right, y_right = _rotate_point((x, y), angle) x_left, y_left = _rotate_point((-x, y), angle) # Circles and intersection right = sg.Point(x_right, y_right).buffer(r) left = sg.Point(x_left, y_left).buffer(r) petal = right.intersection(left) # alpha and color alpha = 1 if highlight == 'regular' else .8 ecol = (colors.to_rgba(color)[0], colors.to_rgba(color)[1], colors.to_rgba(color)[2], alpha) ax.add_patch(descartes.PolygonPatch(petal, fc=(0, 0, 0, 0), ec = ecol, lw= 1))
def plot_shapes(objects, outdir="out/", random_color=False, title="plot"): """Plots shapely shapes.""" fig = plt.figure() ax = fig.add_subplot(111) # calculate plot bounds min_x = min_y = float('inf') max_x = max_y = float('-inf') for obj in objects: color = None if isinstance(obj, tuple): obj, color = obj if not color and random_color: color = (random.random(), random.random(), random.random()) patch = descartes.PolygonPatch(obj, color=color, ec=(0, 0, 0)) elif color: patch = descartes.PolygonPatch(obj, color=color, ec=(0, 0, 0)) else: patch = descartes.PolygonPatch(obj, ec=(0, 0, 0)) ax.add_patch(patch) min_x = min(min_x, obj.bounds[0]) min_y = min(min_y, obj.bounds[1]) max_x = max(max_x, obj.bounds[2]) max_y = max(max_y, obj.bounds[3]) ax.set_xlim(min_x - (max_x - min_x) * 0.1, max_x + (max_x - min_x) * 0.1) ax.set_ylim(min_y - (max_y - min_y) * 0.1, max_y + (max_y - min_y) * 0.1) plt.title(title) ax.set_aspect(1) if outdir: with cd(outdir): plt.savefig('plot.png') os.chmod('plot.png', 0o666) else: plt.show()
def geom_to_fig(geom, xrange=None, yrange=None, axis_visible=True, patchkws={}, aspect=1, linewidth=0.01, fig=None): """ convert a shapely geometry to a matplotlib figure If xrange and yrange are given, use them. If not, the bounds of the geometry are used xrange: a number (xmax) or a tuple (xmin, xmax) defining the range to plot in the x coord yrange: the same in the y coord. If these are not given, they are deduced from the coordinates of the geometry axis_visible: show the axis and labels patchkws: passed as kws to descartes.PolygonPatch aspect: parameter passed to axis.set_aspect (possible values: 'auto', or a number defining the ratio y/x) fig: used internally when called recursively for multi-geometries NB: This function relies on functionality provided by `descartes` (https://bitbucket.org/sgillies/descartes/) """ try: import descartes except ImportError: raise ImportError("descartes are needed to plot geometries") x0, y0, x1, y1 = util.geom_getbounds(geom, xrange, yrange) if fig is None: #fig = pyplot.figure(1, figsize=(xsize, ysize)) fig = pyplot.figure() ax = fig.add_subplot(111) else: ax = fig.gca() if isinstance(geom, Polygon): p = geom.__geo_interface__ else: geom0 = geom.buffer(linewidth) if isinstance(geom0, Polygon): p = geom0.__geo_interface__ else: for subgeom in geom.geoms: fig = geom_to_fig(subgeom, xrange=(x0, x1), yrange=(y0, y1), show=False, axis_visible=axis_visible, patchkws=patchkws, aspect=aspect, fig=fig) return fig if not axis_visible: ax.get_yaxis().set_visible(False) ax.get_xaxis().set_visible(False) ax.axis('off') ax.set_xlim(x0, x1) ax.set_ylim(y0, y1) ax.set_aspect(aspect) pa = descartes.PolygonPatch(p, **patchkws) ax.add_patch(pa) return fig
def hull_jet(ax, eventWise, jet_name, jet_index, _, colour, hatch, label=None, max_alpha=0.1, min_alpha=0.001): if jet_index is not None: child1 = getattr(eventWise, jet_name + "_Child1")[jet_index] mask = child1 == -1 inside_idxs = eventWise.JetInputs_SourceIdx[getattr( eventWise, jet_name + "_Label")[jet_index][mask]] inside_points = np.array([ list(eventWise.Rapidity[inside_idxs]), list(eventWise.Phi[inside_idxs]) ]).T outside_idxs = [ i for i in eventWise.JetInputs_SourceIdx if i not in inside_idxs ] outside_points = np.array([ list(eventWise.Rapidity[outside_idxs]), list(eventWise.Phi[outside_idxs]) ]).T else: inside_points = np.empty((0, 2)) outside_points = np.empty((0, 2)) split_phi = largest_gap(inside_points[:, 1]) if split_phi is None: insides = [inside_points] outsides = [outside_points] else: insides = cycle_about(inside_points, split_phi) outsides = cycle_about(outside_points, split_phi) for inside_points, outside_points in zip(insides, outsides): if len(inside_points) < 3: ax.plot(inside_points[:, 0], inside_points[:, 1], color=colour, label=label, alpha=0.5) label = None continue shape = hull_about(inside_points, outside_points, max_alpha, min_alpha) ax.add_patch( descartes.PolygonPatch( shape, facecolor="none", edgecolor=colour, # hatch=hatch, alpha=0.5, label=label)) label = None
def draw_scap(capture, width, height, show_text=False): # Construct paths paths = [] colors = [] for stroke in capture: verts = [(p[0] + border_offset, height - p[1] + border_offset) for p in stroke] paths.append(verts) if stroke.group_ind >= 0: colors.append(palette_large[stroke.group_ind % len(palette_large)]) else: colors.append('#b3b3b330') paths = [shapely.geometry.LineString(p) for p in paths] poly = [p.buffer(capture[0].thickness / 2) for p in paths] patches = [ descartes.PolygonPatch(p, fc=colors[i], ec=colors[i], zorder=0) for i, p in enumerate(poly) ] fig = plt.figure(figsize=(width / 80, height / 80), dpi=80) # https://stackoverflow.com/questions/19306510/determine-matplotlib-axis-size-in-pixels/19306776 ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) for i, patch in enumerate(patches): ax.add_artist(patch) if show_text: stroke = capture[i] if stroke.group_ind >= 0: p = list(stroke.points[0]) p[0] += border_offset p[1] -= border_offset ax.annotate('{}'.format(stroke.stroke_ind), xy=(p[0], height - p[1]), xytext=(p[0] + 10, height - p[1] + 10), arrowprops=dict(facecolor='black', shrink=0.05, width=1, headwidth=3, headlength=4)) ax.set_aspect('equal') ax.set_xlim(0, width + border_offset * 2) ax.set_ylim(0, height + border_offset * 2) return ax
def debug_page(page, text_highlights, selection_highlights): """Plot the word boxes and highlights for a particular page. After calling this, you must still use plt.show() to see the result! We don't call it here to avoid blocking on each page, although that is still possible to do if you want. """ # pylint: disable=import-outside-toplevel,too-many-locals import matplotlib.pyplot as plt import descartes _, _, page_width, page_height = page.CropBox fig = plt.figure() ax = fig.gca() ax.set_xlim((0, page_width)) ax.set_ylim((0, page_height)) ax.set_aspect("equal") flip = coordinate_transformer(page) words = page.getText("words") word_boxes = [ box(x0, y0, x1, y1) for x0, y0, x1, y1, word, _, _, _ in words ] for word_box in word_boxes: word_patch = descartes.PolygonPatch(flip(word_box)) ax.add_patch(word_patch) for text_highlight in text_highlights: highlight_patch = descartes.PolygonPatch(flip(text_highlight), fc="yellow", alpha=0.5) ax.add_patch(highlight_patch) for selection_highlight in selection_highlights: selection_patch = descartes.PolygonPatch(flip(selection_highlight), fc="orange", alpha=0.7) ax.add_patch(selection_patch)
def print_to_pdf(shapley_list, filename, random_colours=True, **kwargs): scale = kwargs['scale'] pylab.rcParams['savefig.dpi'] = 254 x_min = [] x_max = [] y_min = [] y_max = [] for shape in shapley_list: bound = shape.bounds x_min.append(bound[0]) y_min.append(bound[1]) x_max.append(bound[2]) y_max.append(bound[3]) x_limits = [np.min(x_min), np.max(x_max)] y_limits = [np.min(y_min), np.max(y_max)] fig_width = np.ptp(x_limits) fig_height = np.ptp(y_limits) fig = plt.figure(figsize=(fig_width / 2.54, fig_height / 2.54)) fig.subplots_adjust(left=0, right=1, top=1, bottom=0) ax = fig.add_subplot(111) for shape in shapley_list: if random_colours: colours = np.append(np.random.uniform(size=3), 0.3) else: colours = [0, 0, 0, 0.3] scaled_shape = aff.scale(shape, xfact=scale, yfact=scale) patch = des.PolygonPatch(scaled_shape, fc=colours) ax.add_patch(patch) ax.set_xlim(x_limits) ax.set_ylim(y_limits) plt.grid(True) plt.savefig("temp.png") subprocess.call([ "convert", "-units", "PixelsPerInch", "temp.png", "-density", "254", "temp.pdf" ]) os.rename("temp.pdf", filename) os.remove("temp.png")
def circles_plot(c_plot, intersection_area, center_intersection, obj_area): '''Plot circles and intersection dots c_plot: list of Circle instances data_intersect: list, result of intersection function center_intersection: list, intersection coordinates of two intersection lines ''' fig, ax = plt.subplots() # plot circles for c in c_plot: ax.add_patch(plt.Circle((c.x, c.y), c.r, color='#000000', alpha=0.5)) plt.plot(c.x, c.y, 'yo') ax.set_aspect('equal', adjustable='datalim') ax.plot() ax.add_patch( descartes.PolygonPatch(intersection_area, fc='g', ec='k', alpha=0.2)) plt.plot(center_intersection[0], center_intersection[1], 'bo') ax.add_patch(descartes.PolygonPatch(obj_area, fc='r', ec='k', alpha=1)) plt.show()
def label_districts(plot, label_dict=None, shade=False, typ=None): df = get_district_df(HOUSE_SHAPE) i = 1 prj_name = 'shapefiles/2013_precincts_proj.prj' full_name = os.path.join(os.getcwd(), prj_name) prj = open(full_name) proj4 = osr.SpatialReference(prj.read()).ExportToProj4() for geo in df.geometry.to_crs(proj4): if i in names.LOW_DISTRICTS_ANCH: plot.add_patch(descartes.PolygonPatch(geo, fc='m', alpha=0.3)) elif i in names.HIGH_DISTRICTS_MATSU: plot.add_patch(descartes.PolygonPatch(geo, fc='b', alpha=0.3)) if typ == legislators.SEN: txt = label.sen_label(i) else: txt = str(i) text = label.annotate_label(plot=plot, text=txt, i=i, centroid=geo.centroid, label_dict=label_dict) text.set_fontsize(9) i = i + 1 return plot
def display_shapely(shape, ax=None, random_colours=True, alpha=0.3): if ax is None: fig = plt.figure() ax = fig.add_subplot(111) if random_colours: colours = np.append(np.random.uniform(size=3), alpha) else: colours = [0, 0, 0, alpha] patch = des.PolygonPatch(shape, fc=colours) ax.add_patch(patch) ax.axis("equal") plt.grid(True)
def get_matplotlib_patches(self, map_obj, attr_key='class'): """ :return: """ patches_dict = {value: [] for value in self.prioritized_values} for poly, value in zip(self.shapes['geometry'], self.shapes[attr_key]): if int(value) == 0: # Dummy value '0' is regarded as a DUMMY value :) continue if poly.geom_type == 'Polygon': mpoly = shapely.ops.transform(map_obj.map, poly) patches_dict[value].append(descartes.PolygonPatch(mpoly, lw=0.15, ec=map_obj.colormap_properties[value], color=map_obj.colormap_properties[value])) elif poly.geom_type == 'MultiPolygon': for subpoly in poly: # mpoly = shapely.ops.transform(map_obj.map, poly) mpoly = shapely.ops.transform(map_obj.map, subpoly) # correct? patches_dict[value].append(descartes.PolygonPatch(mpoly, lw=0.15, ec=map_obj.colormap_properties[value], color=map_obj.colormap_properties[value])) else: print('Not working......') patches_list = [] # Extend patches_list accoring to backward class priority. # This way geometries for the last class is plotted on top of all other classes. for i in self.prioritized_values: patches_list.extend(patches_dict[i]) return patches_list
def patches_from_geometry(geo, **kwargs): """Convert an iterable of geometry to `matplotlib` patches. :param geo: An iterable of geometry items. If `descartes` cannot parse an item, it is ignored. :param **kwargs: Any key-word arguments to forward on to the `patch` constructor. :return: A list of `matplotlib.patches.Patch` objects. """ patches = [] for x in geo: try: patches.append(descartes.PolygonPatch(x, **kwargs)) except: pass return patches
def vector_in_polygon(vector, polygon, draw=False): vector = LineString(vector) polygon = Polygon(polygon) # Drawing function if draw: fig = plt.figure() ax = fig.add_subplot(111) ax.plot(*np.array(vector).T, color='blue', linewidth=3, solid_capstyle='round') ax.add_patch(descartes.PolygonPatch(polygon, fc='blue', alpha=0.5)) ax.axis('equal') plt.show() return vector.intersects(polygon)
def render(self): """ Renders all layers and sets the extents be the most extreme points found across all layers """ all_x = [] all_y = [] z = 0 for layer in self.layers: z += 1 print("rendering %s" % layer["path"]) if (layer["type"] == "csv"): kwargs = layer["kwargs"] kwargs["zorder"] = z kwargs["lw"] = 0 if (self.point_transform): kwargs["transform"] = self.point_transform self.axis.scatter(**kwargs) elif (layer["type"] == "shapes"): for shape in layer["shapes"]: kwargs = shape["kwargs"] kwargs["zorder"] = z patch = descartes.PolygonPatch( shape["shape"], **kwargs ) if (self.polygon_transform): patch.set_transform(self.polygon_transform) self.axis.add_patch(patch) all_x.append(layer["extents"][0]) all_y.append(layer["extents"][1]) all_x.append(layer["extents"][2]) all_y.append(layer["extents"][3]) self.axis.set_extent([ min(all_x), max(all_x), min(all_y), max(all_y) ])
def render_poly(poly: shapely.geometry.Polygon, ax: plt.Axes, kw=None): """Render an individual shapely shapely.geometry.Polygon. Args: poly (shapely.geometry.Polygon): Poly or multipoly to render. ax (plt.Axes): Matplotlib axis to render to. kw (dict): Dictionary of kwargs for the plotting. Defaults to None. Returns: patch: ax.add_patch result """ # TODO: maybe if done in batch we can speed this up? kw = kw or {} return ax.add_patch( descartes.PolygonPatch(poly, **{ **style_config.poly, **kw }))