def __plot_all(self): total = len(self.data) count = 0.0 for timeStamp in self.data: if len(self.data[timeStamp]) < 2: self.parent.threadPlot = None return None, None if self.fade: alpha = (total - count) / total else: alpha = 1 data = self.data[timeStamp].items() peakF, peakL = self.extent.get_peak_fl() segments, levels = self.__create_segments(data) lc = LineCollection(segments) lc.set_array(numpy.array(levels)) lc.set_norm(self.__get_norm(self.autoL, self.extent)) lc.set_cmap(self.colourMap) lc.set_linewidth(self.lineWidth) lc.set_gid('plot') lc.set_alpha(alpha) self.axes.add_collection(lc) count += 1 return peakF, peakL
def export_diffusion_extra(self, phase: SimPhase, conf: SimConfExportPlotCells) -> None: ''' Plot all logarithm-scaled extracellular diffusion weights for the environment at the last time step. ''' # Prepare to export the electric plot. self._export_prep(phase) fig = pyplot.figure() ax99 = pyplot.subplot(111) pyplot.imshow( np.log10(phase.sim.D_env_weight.reshape(phase.cells.X.shape)), origin='lower', extent=phase.cache.upscaled.extent, cmap=phase.p.background_cm, ) pyplot.colorbar() cell_edges_flat = mathunit.upscale_coordinates( phase.cells.mem_edges_flat) coll = LineCollection(cell_edges_flat, colors='k') coll.set_alpha(1.0) ax99.add_collection(coll) pyplot.title('Logarithm of Environmental Diffusion Weight Matrix') # Export this plot to disk and/or display. self._export(phase=phase, basename='env_diffusion_weights')
def plot(ax, x, y, time, sim_type): assert(len(x) == len(y) == len(time)) l = len(time) if use_hf_coloration: time_to_grayscale = 0.8 / 23.6 # for HF coloring else: time_to_grayscale = 0.8 / time[l-1] colors = [] for i in range(l-1): if use_hf_coloration: color = get_hf_color(time[i]) # time[] is really HF else: g = 0.8 - (time[i] * time_to_grayscale)**2.0 if sim_type == 'driven': color = (g, 1.0, g, 0.8) else: color = (g, g, 1.0, 1.0) colors.append(color) points = zip(x,y) segments = zip(points[:-1], points[1:]) lc = LineCollection(segments, colors=colors) lc.set_alpha(1.0) lc.set_linewidth(1.0) lc.set_antialiased(True) ax.add_collection(lc) if use_hf_coloration: end_points.append((x[l-1], y[l-1], get_hf_color(time[l-1]))) else: end_points.append((x[l-1], y[l-1], COLOR[sim_type]))
def plot(ax, x, y, time, sim_type): assert (len(x) == len(y) == len(time)) l = len(time) if use_hf_coloration: time_to_grayscale = 0.8 / 23.6 # for HF coloring else: time_to_grayscale = 0.8 / time[l - 1] colors = [] for i in range(l - 1): if use_hf_coloration: color = get_hf_color(time[i]) # time[] is really HF else: g = 0.8 - (time[i] * time_to_grayscale)**2.0 if sim_type == 'driven': color = (g, 1.0, g, 0.8) else: color = (g, g, 1.0, 1.0) colors.append(color) points = zip(x, y) segments = zip(points[:-1], points[1:]) lc = LineCollection(segments, colors=colors) lc.set_alpha(1.0) lc.set_linewidth(1.0) lc.set_antialiased(True) ax.add_collection(lc) if use_hf_coloration: end_points.append((x[l - 1], y[l - 1], get_hf_color(time[l - 1]))) else: end_points.append((x[l - 1], y[l - 1], COLOR[sim_type]))
def __plot_all(self, spectrum): total = len(spectrum) count = 0.0 for timeStamp in spectrum: if self.settings.fadeScans: alpha = (total - count) / total else: alpha = 1 data = spectrum[timeStamp].items() peakF, peakL = self.extent.get_peak_fl() segments, levels = self.__create_segments(data) if segments is not None: lc = LineCollection(segments) lc.set_array(numpy.array(levels)) lc.set_norm(self.__get_norm(self.settings.autoL, self.extent)) lc.set_cmap(self.colourMap) lc.set_linewidth(self.lineWidth) lc.set_gid('plot') lc.set_alpha(alpha) self.axes.add_collection(lc) count += 1 return peakF, peakL
def smoth_paths(G, fig, ax, pos, leaf_nodes, l_width=1, l_alpha=1, res=50, d=3): node_a, node_b = np.meshgrid(leaf_nodes, leaf_nodes) node_a = sum([r[i + 1:].tolist() for i, r in enumerate(node_a)], []) node_b = sum([r[i + 1:].tolist() for i, r in enumerate(node_b)], []) all_paths = [nx.shortest_path(G, a, b) for a, b in zip(node_a, node_b)] all_paths_pos = [] for i, path in enumerate(tqdm(all_paths)): path_pos = [pos[i] for i in path] all_paths_pos.append(path_pos) x, y = bspline(path_pos, n=res, degree=d, periodic=False).T c_first_node = nx.get_node_attributes(G, 'color')[path[0]] c_last_node = nx.get_node_attributes(G, 'color')[path[-1]] l_first = nx.get_node_attributes(G, 'loss')[path[0]] l_last = nx.get_node_attributes(G, 'loss')[path[-1]] cmap = LinearSegmentedColormap.from_list( "reye", [c_first_node, c_last_node]) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) norm = plt.Normalize(0, 2) lc = LineCollection(segments, cmap=cmap) lc.set_array(np.arange(len(x))) lc.set_linewidth(l_width) lc.set_alpha(l_alpha) line = ax.add_collection(lc) line.set_zorder(-i - 5000 * (not bool(l_first)) - 5000 * (not bool(l_first))) return fig, ax
def plot_roads( network: RoadNetwork, z_order=None, color_roads=True, alpha=1, default_road_color="#000000", ) -> LineCollection: """ Plot a RoadNetwork using matplotlib. Returns a Collection object that can be added to a matplotlib Axes object to draw roads. """ segments = [] colors = [] for link in network: segments.append(link.pts_) if color_roads: colors.append(to_rgba(COLORS.get(link.type, default_road_color))) else: colors.append(to_rgba(default_road_color)) lines = LineCollection(segments, colors=colors, zorder=z_order) lines.set_alpha(alpha) return lines
def loadlines(self, name, curdir='beijingJson', zorder=None, linewidth=0.5, color='k', antialiased=1, ax=None, default_encoding='utf-8', linestyle='-', linesalpha=1): # get current axes instance (if none specified). filename = curdir + '/' + name + '.json' coords = json.load(codecs.open(filename, 'r', 'utf-8')) coords = self.projectcoords(coords) ax = ax or self._check_ax() # make LineCollections for each polygon. lines = LineCollection(coords, antialiaseds=(1, )) lines.set_color(color) lines.set_linewidth(linewidth) lines.set_linestyle(linestyle) lines.set_alpha(linesalpha) lines.set_label('_nolabel_') if zorder is not None: lines.set_zorder(zorder) ax.add_collection(lines) # set axes limits to fit map region. self.set_axes_limits(ax=ax) # clip boundaries to map limbs lines, c = self._cliplimb(ax, lines) self.__dict__[name] = coords return lines
def line_plot_3d(): fig = plt.figure() ax = fig.gca(projection='3d') def cc(arg): return mcolors.to_rgba(arg, alpha=0.6) xs = np.arange(0, 10, 0.4) verts = [] zs = [0.0, 2.0, 4.0, 6.0] for z in zs: ys = np.random.rand(len(xs)) # ys[0], ys[-1] = 0, 0 verts.append(list(zip(xs, ys))) # poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'), cc('y')]) poly = LineCollection(verts, colors=[cc('r'), cc('g'), cc('b'), cc('y')]) poly.set_alpha(1) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel('X') ax.set_xlim3d(0, 10) ax.set_ylabel('Y') ax.set_ylim3d(-1, 7) ax.set_zlabel('Z') ax.set_zlim3d(0, 1) plt.show()
def _plotpartial(ax, partial, downsample=1, cmap='inferno', exp=1, linewidth=1, avg=True): # columns: time, freq, amp, phase, bw segments, Z = _segmentsZ(partial, downsample=downsample, exp=exp, avg=avg) lc = LineCollection(segments, cmap=cmap) # Set the values used for colormapping lc.set_array(Z) lc.set_linewidth(linewidth) lc.set_alpha(None) ax.add_collection(lc, autolim=True)
def voronoi_plot_2d(vor, ax=None, **kw): from matplotlib.collections import LineCollection if vor.points.shape[1] != 2: raise ValueError("Voronoi diagram is not 2-D") if kw.get('show_points', True): ax.plot(vor.points[:, 0], vor.points[:, 1], '.') if kw.get('show_vertices', True): ax.plot(vor.vertices[:, 0], vor.vertices[:, 1], 'o') line_colors = kw.get('line_colors', 'k') line_width = kw.get('line_width', 1.0) line_alpha = kw.get('line_alpha', 1.0) line_segments = [] for simplex in vor.ridge_vertices: simplex = np.asarray(simplex) if np.all(simplex >= 0): line_segments.append([(x, y) for x, y in vor.vertices[simplex]]) lc = LineCollection(line_segments, colors=line_colors, lw=line_width, linestyle='solid') lc.set_alpha(line_alpha) ax.add_collection(lc) ptp_bound = vor.points.ptp(axis=0) line_segments = [] center = vor.points.mean(axis=0) for pointidx, simplex in zip(vor.ridge_points, vor.ridge_vertices): simplex = np.asarray(simplex) if np.any(simplex < 0): i = simplex[simplex >= 0][0] # finite end Voronoi vertex t = vor.points[pointidx[1]] - vor.points[pointidx[0]] # tangent t /= np.linalg.norm(t) n = np.array([-t[1], t[0]]) # normal midpoint = vor.points[pointidx].mean(axis=0) direction = np.sign(np.dot(midpoint - center, n)) * n far_point = vor.vertices[i] + direction * ptp_bound.max() line_segments.append([(vor.vertices[i, 0], vor.vertices[i, 1]), (far_point[0], far_point[1])]) lc = LineCollection(line_segments, colors=line_colors, lw=line_width, linestyle='dashed') lc.set_alpha(line_alpha) ax.add_collection(lc) _adjust_bounds(ax, vor.points) return ax.figure
def plot(self, ax=None, cmapname=None, cmap=None, linewidth=1, edgecolor='grey', facecolor=None, alpha=1): """Plot the geometries on the basemap using the defined colors Parameters: ----------- ax : matplotlib.axis object An axis object for plots. Overwrites the self.ax attribute. cmapname : string Name of the color map from matplotlib (LINK!) (default: 'seismic') cmap : matplotlib colormap You can create you own colormap and pass it to the plot. linewidth : float Width of the lines. edgecolor : string, float or iterable Definition of the edge color. Can be an iterable with a color definition for each geometry, a string with one color for all geometries or a float to define one color for all geometries from the cmap. facecolor : string, float or iterable Definition of the face color. See edgecolor. alpha : float Level of transparency. """ if ax is not None: self.ax = ax n = 0 if facecolor is None: facecolor = self.color if edgecolor is None: edgecolor = self.color if cmapname is not None: self.cmapname = cmapname if self.data is not None: self.data = np.array(self.data) if cmap is None: cmap = plt.get_cmap(self.cmapname) for geo in self.geometries: vectors = self.get_vectors_from_postgis_map(geo) lines = LineCollection(vectors, antialiaseds=(1, )) lines.set_facecolors(self.select_color(facecolor, cmap, n)) lines.set_edgecolors(self.select_color(edgecolor, cmap, n)) lines.set_linewidth(linewidth) lines.set_alpha(alpha) self.ax.add_collection(lines) n += 1
def plotBoundCells(points_flat, bflags, cells, p, fig=None, ax=None): """ Plot elements tagged on the boundary as red points. Parameters ---------- points_flat A flat array of points corresponding to the bflags data structure bflags A nested array of boolean flags indicating boundary tagging Returns ------- fig, ax Matplotlib plotting objects Note ------ This particular plot is extremely slow -- intended for cross-checking purposes only! """ if fig is None: fig = plt.figure() # define the figure and axes instances if ax is None: ax = plt.subplot(111) #ax = plt.axes() points_flat = np.asarray(points_flat) bflags = np.asarray(bflags) bpoints = points_flat[bflags] ax.plot(p.um * points_flat[:, 0], p.um * points_flat[:, 1], 'k.') ax.plot(p.um * bpoints[:, 0], p.um * bpoints[:, 1], 'r.') # cell_edges_flat, _ , _= tb.flatten(cells.mem_edges) cell_edges_flat = p.um * cells.mem_edges_flat coll = LineCollection(cell_edges_flat, colors='k') coll.set_alpha(0.5) ax.add_collection(coll) ax.axis('equal') xmin = cells.xmin * p.um xmax = cells.xmax * p.um ymin = cells.ymin * p.um ymax = cells.ymax * p.um ax.axis([xmin, xmax, ymin, ymax]) return fig, ax
def plot_cubical_2D_cell_complex(K): fig, axes = configure_2D_plot(K) verts = np.array([cell.cube_map for cell in K(0)]) / 2 edges = np.array([edge_vertices(cell) for cell in K(1)]) faces = np.array([face_vertices(cell) for cell in K(2)]) axes.scatter(verts[:, 1], verts[:, 0], alpha=0.5) edges_coll = LineCollection(edges) edges_coll.set_color('green') edges_coll.set_alpha(0.5) faces_coll = PolyCollection(faces, ) faces_coll.set_color('pink') axes.add_collection(edges_coll) axes.add_collection(faces_coll) return fig, axes
def generate_boundary_artist(vertices, color): if DIM == 2: artist = LineCollection(vertices) artist.set_color(color) artist.set_linewidth(2.5) elif DIM == 3: artist = Poly3DCollection(vertices, linewidths=1) # transparency alpha must be set BEFORE face/edge color artist.set_alpha(0.5) artist.set_facecolor(color) artist.set_edgecolor('k') else: raise ValueError( "%d dimensions needs special attention for plotting." % int(DIM)) return artist
def _add_plot(fig, ax, plot_data, color_data, pkeys, lw=1, cmap='_auto', alpha=1.0): colors = color_data.color if cmap == '_auto': cmap = None if color_data.is_categorical: colors = np.take(COLOR_CYCLE, colors, mode='wrap') if plot_data.scatter: data, = plot_data.trajs artist = ax.scatter(*data.T, marker='o', c=colors, edgecolor='none', s=lw*20, cmap=cmap, alpha=alpha, picker=5) else: # trajectory plot if hasattr(colors, 'dtype') and np.issubdtype(colors.dtype, np.number): # delete lines with NaN colors mask = np.isfinite(colors) if mask.all(): trajs = plot_data.trajs else: trajs = [t for i,t in enumerate(plot_data.trajs) if mask[i]] colors = colors[mask] artist = LineCollection(trajs, linewidths=lw, cmap=cmap) artist.set_array(colors) else: artist = LineCollection(plot_data.trajs, linewidths=lw, cmap=cmap) artist.set_color(colors) artist.set_alpha(alpha) artist.set_picker(True) artist.set_pickradius(5) ax.add_collection(artist, autolim=True) ax.autoscale_view() # Force ymin -> 0 ax.set_ylim((0, ax.get_ylim()[1])) def on_pick(event): if event.artist is not artist: return label = pkeys[event.ind[0]] ax.set_title(label) fig.canvas.draw_idle() # XXX: hack, make this more official if hasattr(fig, '_superman_cb'): fig.canvas.mpl_disconnect(fig._superman_cb[0]) cb_id = fig.canvas.mpl_connect('pick_event', on_pick) fig._superman_cb = (cb_id, on_pick) return artist
def generate_boundary_artist(vertices, color): ndim = len(next(iter(vertices[0]))) vertices = tuple(map(tuple, vertices)) if ndim == 2: artist = LineCollection(vertices) artist.set_color(color) artist.set_linewidth(2.5) elif ndim == 3: artist = Poly3DCollection(vertices, linewidth=1) # transparency alpha must be set BEFORE face/edge color artist.set_alpha(0.5) artist.set_facecolor(color) artist.set_edgecolor('k') else: raise ValueError("{:d} dimensions needs special attention for plotting".format(ndim)) return artist
def plot_trajectory_ellipse(frame, varx="attr_VARX", vary="attr_VARY", covxy="attr_COVXY", opacity_factor=1): """ Draw the trajectory and uncertainty ellipses around teach point. 1) Scatter of points 2) Trajectory lines 3) Ellipses :param frame: Trajectory :param opacity_factor: all opacity values are multiplied by this. Useful when used to plot multiple Trajectories in an overlay plot. :return: axis """ ellipses = [] segments = [] start_point = None for i, pnt in frame.iterrows(): # The ellipse U, s, V = np.linalg.svd(np.array([[pnt[varx], pnt[covxy]], [pnt[covxy], pnt[vary]]]), full_matrices=True) w, h = s**.5 theta = np.arctan(V[1][0]/V[0][0]) # == np.arccos(-V[0][0]) ellipse = {"xy":pnt[list(frame.geo_cols)].values, "width":w, "height":h, "angle":theta} ellipses.append(Ellipse(**ellipse)) # The line segment x, y = pnt[list(frame.geo_cols)][:2] if start_point: segments.append([start_point, (x, y)]) start_point = (x, y) ax = plt.gca() ellipses = PatchCollection(ellipses) ellipses.set_facecolor('none') ellipses.set_color("green") ellipses.set_linewidth(2) ellipses.set_alpha(.4*opacity_factor) ax.add_collection(ellipses) frame.plot(kind="scatter", x=frame.geo_cols[0], y=frame.geo_cols[1], marker=".", ax=plt.gca(), alpha=opacity_factor) lines = LineCollection(segments) lines.set_color("gray") lines.set_linewidth(1) lines.set_alpha(.2*opacity_factor) ax.add_collection(lines) return ax
def plotclustering(label, zipcodes, nameee): # print len(zipcodes) label = np.array(label) zipcodes = np.array(zipcodes) cluster1 = zipcodes[label == 1] cluster2 = zipcodes[label == 2] cluster0 = zipcodes[label == 0] cluster3 = zipcodes[label == 3] fig = plt.figure(figsize =(15, 15)) ax = plt.subplot(111) lllat = 40.473; urlat = 40.93; lllon = -74.27; urlon = -73.69 # define the boundary of the map m = Basemap(ax=ax, projection = 'stere', lon_0 = (urlon + lllon)/2, lat_0 = (urlat +lllat)/2, llcrnrlon = lllon, llcrnrlat = lllat, urcrnrlon = urlon, urcrnrlat = urlat, resolution= 'l')# create the basemap # m.drawcoastlines() m.drawcountries() shp = ShapeFile('c:/Users/gang/Desktop/nyczipregion') dbf = dbflib.open('c:/Users/gang/Desktop/nyczipregion') for npoly in range(shp.info()[0]): shpsegs = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons , lats = zip(*verts[ring]) x, y = m(lons, lats) shpsegs.append(zip(x, y)) if ring ==0: shapedict = dbf.read_record(npoly) name = shapedict['Zcta5ce00'] lines = LineCollection(shpsegs, antialiaseds=(1,)) if name in cluster0: lines.set_facecolors('b') if name in cluster1: lines.set_facecolors('g') if name in cluster2: lines.set_facecolors('r') if name in cluster3: lines.set_facecolors('y') lines.set_alpha(1) lines.set_edgecolors('k') ax.add_collection(lines) plt.title('Box Clustering Based On Taxi Trips') plt.savefig(nameee+'_box_trip_Clustering.png', dpi=300) plt.show()
def algo (region,output, word): reg = [0 for i in range(0,23)] total = 0 for line in region: #reg_num number items = line.rstrip('\n').split('\t') reg[int(items[0])]=int(items[1]) total = total+int(items[1]) reg=np.array(reg) max_percent=np.max(reg) plt.figure(figsize=(15,15)) ax = plt.subplot(111) m = Basemap(projection='merc', lat_0=45, lon_0=0, resolution = 'h', area_thresh = 10.0, llcrnrlat=41.33, llcrnrlon=-5, urcrnrlat=51.5, urcrnrlon=9.7) m.drawcoastlines() #m.drawcountries() # french border does not fit with region ones m.fillcontinents(color='lightgrey',lake_color='white') m.drawmapboundary(fill_color='white') sf = shapefile.Reader("./geodata/FRA_adm1") shapes = sf.shapes() records = sf.records() for record, shape in zip(records,shapes): lons,lats = zip(*shape.points) data = np.array(m(lons, lats)).T if len(shape.parts) == 1: segs = [data,] else: segs = [] for i in range(1,len(shape.parts)): index = shape.parts[i-1] index2 = shape.parts[i] segs.append(data[index:index2]) segs.append(data[index2:]) lines = LineCollection(segs,antialiaseds=(1,)) lines.set_edgecolors('k') lines.set_linewidth(0.5) lines.set_facecolors('brown') lines.set_alpha(float(reg[record[3]])/max_percent) #record[3] est le numero de region ax.add_collection(lines) plt.savefig(word+'-'+str(total)+'.png',dpi=300) return 0
def getCollection(length=None, samples=samples, cmap='magma_r'): """Creates a collection from sample chain of shape: (length,dims) Optional Inputs length :: int :: the include this many chain samples """ if length is None: length = samples[:, 1].size x, y = samples[:, 0], samples[:, 1] points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=plt.get_cmap(cmap), norm=plt.Normalize(250, 1500)) lc.set_array(np.arange(length)) lc.set_linewidth(1.) lc.set_alpha(0.3) return lc
def plotCountry(m, ax, id, path='gadm0'): country, lonlat = merged[id] r = shapefile.Reader(r"%s/%s_adm0" % (path, country)) shapes = r.shapes() records = r.records() for record, shape in zip(records, shapes): lons, lats = zip(*shape.points) data = np.array(m(lons, lats)).T if len(shape.parts) == 1: segs = [ data, ] else: segs = [] for i in range(1, len(shape.parts)): index = shape.parts[i - 1] index2 = shape.parts[i] segs.append(data[index:index2]) segs.append(data[index2:]) lines = LineCollection(segs, antialiaseds=(1, )) lines.set_facecolors('lightgreen') lines.set_edgecolors('k') lines.set_linewidth(0.1) lines.set_alpha(0.5) ax.add_collection(lines) # Add country centroid lon, lat = lonlat xpt, ypt = m(lon, lat) txt = ax.annotate(id, (xpt, ypt), color='r', size='medium', ha='center', va='center', path_effects=[ PathEffects.withStroke(linewidth=3, foreground="w"), PathEffects.withSimplePatchShadow() ])
def plot_sparse_trajectory(trajectory, r=50, opacity_factor=1, plot_text=True, num_col="segment_sparcify_n", min_static=100): """ Plots a sparsified trajectory as circles with the number of points they represent as a number inside. :param trajectory: Trajectory object :param r: the radius of circles :param num_col: where to find the number to put in the circles :param min_static: minimum count to change color of circle :param plot_text: put the text with num of points in the circle? :return: ax """ ax = plt.gca() trajectory.plot(kind="scatter", x=trajectory.geo_cols[0], y=trajectory.geo_cols[1], marker=".", ax=plt.gca(), alpha=0.0*opacity_factor) circles = [] segments = [] start_point = None for i, pnt in trajectory.iterrows(): circles.append(Circle(pnt[list(trajectory.geo_cols)].values, radius=r)) if plot_text: plt.text(*pnt[list(trajectory.geo_cols)], s=str(int(pnt[num_col])), fontsize=12) x, y = pnt[list(trajectory.geo_cols)][:2] if start_point: segments.append([start_point, (x, y)]) start_point = (x, y) circles = PatchCollection(circles) circles.set_facecolor(['none' if cnt < min_static else 'red' for cnt in trajectory[num_col].values]) circles.set_alpha(.5*opacity_factor) ax.add_collection(circles) lines = LineCollection(segments) lines.set_color("gray") lines.set_alpha(.2*opacity_factor) ax.add_collection(lines) return ax
def drawcountry(self, ax, base_map, iso2, color, alpha = 1): if iso2 not in self.countries: raise ValueError, "Where is that country ?" vertices = self.countries[iso2] shape = [] for vertex in vertices: longs, lats = zip(*vertex) # conversion to plot coordinates x,y = base_map(longs, lats) shape.append(zip(x,y)) lines = LineCollection(shape,antialiaseds=(1,)) lines.set_facecolors(cm.hot(np.array([color,]))) lines.set_edgecolors('white') lines.set_linewidth(0.5) lines.set_alpha(alpha) ax.add_collection(lines)
def odometry_error_bar(fig_num, info, pred_mean, sampling_time='1s', color_bar='Reds'): ######################## # Plot Bar ######################## matplotlib.rcParams.update({'font.size': 15, 'font.weight': 'bold'}) fig, ax = plt.subplots() resample_info = info.resample(resampling_time).mean() x = resample_info.index.to_pydatetime() x[:] = [(i-x[0]).total_seconds() for i in x] y = info.inliers_matches_ratio_th # Display Odometry error information from numpy import linalg as la y = np.ones(len(x)) sd = la.norm(pred_mean, axis=1) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm from matplotlib.colors import LinearSegmentedColormap as lscm cmap = plt.get_cmap(color_bar) norm = plt.Normalize(0.00, 0.0634491701615) lc = LineCollection(segments, cmap=cmap, norm=norm) lc.set_array(sd) lc.set_linewidth(100) lc.set_alpha(0.8) plt.gca().add_collection(lc) ax.tick_params('y', colors='k') ax.set_xlabel(r'Time [$s$]', fontsize=25, fontweight='bold') ax.tick_params('x', colors='k') ax.set_ylim([0.5, 1.5]) ax.set_xlim([x[0], x[len(x)-1]]) plt.show(block=True)
def waterfall(arrs, colors=None): fig = plt.figure(figsize=plt.figaspect(0.5)) ax = fig.gca(projection='3d') def cc(arg): return mcolors.to_rgba(arg, alpha=0.6) verts = [zip(np.arange(len(a)), a) for a in arrs] zs = np.arange(len(verts)) poly = LineCollection(verts, colors=colors) poly.set_alpha(0.8) ax.add_collection3d(poly, zs=zs, zdir='y') #ax.set_xlabel('X') ax.set_xlim3d(0, max([len(a) for a in arrs]) - 1) #ax.set_ylabel('Y') ax.set_ylim3d(0, len(arrs)) #ax.set_zlabel('Z') ax.set_zlim3d(0, max([max(a) for a in arrs]) * 3) plt.show()
def env_mesh(data, ax, cells, p, clrmap, ignore_showCells=False): """ Sets up a mesh plot for environmental data on an existing axis. Parameters ----------- data Data defined on environmental grid cells Instance of cells module p Instance of parameters module ax Existing figure axis to plot currents on Returns -------- mesh_plot Container for mesh plot ax Modified axis """ # if p.plotMask is True: # data = ma.masked_array(data, np.logical_not(cells.maskM)) mesh_plot = ax.imshow(data, origin='lower', extent=[ p.um * cells.xmin, p.um * cells.xmax, p.um * cells.ymin, p.um * cells.ymax ], cmap=clrmap) if p.showCells is True and ignore_showCells is False: cell_edges_flat = p.um * cells.mem_edges_flat coll = LineCollection(cell_edges_flat, colors='k') coll.set_alpha(0.5) ax.add_collection(coll) return mesh_plot, ax
def plot_waterfall(Z, pY, fig, title): from matplotlib.collections import PolyCollection, LineCollection #READ MIC DATA FROM FILES N = 1000 X = np.linspace(-10, 10, N) ax = fig.gca(projection='3d') verts = [] evenly_spaced_interval = np.linspace(0, 1, len(pY)) colors = [cm.viridis(x) for x in evenly_spaced_interval] for i, y in enumerate(pY): verts.append(list(zip(X, Z[i]))) poly = PolyCollection(verts, facecolors=colors) line = LineCollection(verts, colors='k') line.set_alpha(0.4) ax.add_collection3d(poly, zdir='y', zs=pY) # zs=Y, zdir='y') ax.add_collection3d(line, zdir='y', zs=pY) # zs=Y, zdir='y') ax.set_xlabel('log$_2$ MIC', rotation=45) ax.set_xlim3d(-10, 10) ax.set_ylabel('Year', rotation=45) ax.set_ylim3d(pY[0], pY[-1]) ax.set_zlabel('probability estimate', rotation=90) ax.view_init(30, 290) ax.set_title(title) return ax
def arl_dem_figure(self, fig_num, method_name, pred_mean, pred_var, train_sampling_time, test_sampling_time, ground_truth=False): ################# # RE-SAMPLE ################# reference = self.test_reference.resample(test_sampling_time).mean() ################# # RE-SHAPE (optional) ################# ## Equalize the length of data reference = reference[0:self.testing_mask.shape[0]] ## Sync index with odometry reference.index = self.testing_mask.index ## Apply the mask reference = reference[self.testing_mask] ######################################################## #rotate and translate the trajectory wrt the world frame ######################################################## position = np.column_stack((reference.x.values, reference.y.values, reference.z.values )) position[:] = [self.test_navigation_orient.data[0].rot(x) + self.test_navigation_position.data[0] for x in position] ############ ### PLOT ### ############ matplotlib.rcParams.update({'font.size': 30, 'font.weight': 'bold'}) fig = plt.figure(fig_num, figsize=(28, 16), dpi=120, facecolor='w', edgecolor='k') ax = fig.add_subplot(111) # Display the DEM plt.rc('text', usetex=False)# activate latex text rendering CS = plt.contour(self.dem_xi, self.dem_yi, self.dem_zi, 15, linewidths=0.5, colors='k') CS = plt.contourf(self.dem_xi, self.dem_yi, self.dem_zi, 15, cmap=plt.cm.gray, vmax=abs(self.dem_zi).max(), vmin=-abs(self.dem_zi).max()) # plot data points. plt.xlim(min(self.dem_px), max(self.dem_xi)) plt.ylim(min(self.dem_py), max(self.dem_yi)) # Display Ground Truth trajectory from numpy import linalg as la x = position[:,0] y = position[:,1] sd = la.norm(pred_mean, axis=1) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm from matplotlib.colors import LinearSegmentedColormap as lscm cmap = plt.get_cmap('Reds') #cmap = lscm.from_list('temp', colors) norm = plt.Normalize(0.00, 0.0634491701615) #norm = plt.Normalize(min(sd), max(sd)) lc = LineCollection(segments, cmap=cmap, norm=norm) lc.set_array(sd) lc.set_linewidth(40) lc.set_alpha(0.8) plt.gca().add_collection(lc) #color bar of the covarianve #cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) h_cbar = plt.colorbar(lc)#, orientation='horizontal') h_cbar.ax.set_ylabel(r' residual[$m/s$]') # Color bar of the dem cbar = plt.colorbar() # draw colorbar cbar.ax.set_ylabel(r' terrain elevation[$m$]') #Q = ax.plot(x, y, marker='o', linestyle='-', color=[0.3,0.2,0.4], alpha=0.5, lw=40) import os from matplotlib.cbook import get_sample_data from matplotlib._png import read_png import matplotlib.image as image from scipy import ndimage from matplotlib.offsetbox import OffsetImage, AnnotationBbox fn = get_sample_data(os.getcwd()+"/data/img/exoter.png", asfileobj=False) exoter = image.imread(fn) exoter = ndimage.rotate(exoter, 180) imexoter = OffsetImage(exoter, zoom=0.5) ab = AnnotationBbox(imexoter, xy=(x[0], y[0]), xybox=None, xycoords='data', boxcoords="offset points", frameon=False) ax.annotate(r'ExoTeR', xy=(x[0], y[0]), xycoords='data', xytext=(-30, 60), textcoords='offset points', fontsize=20, #arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2", lw=2.0) zorder=101 ) ax.annotate(r'Start', xy=(x[0], y[0]), xycoords='data', xytext=(-5, 5), textcoords='offset points', fontsize=20, horizontalalignment='left', verticalalignment='bottom', zorder=101 ) ax.scatter(x[0], y[0], marker='o', facecolor='k', s=100, alpha=1.0, zorder=103) ax.arrow(x[130], y[130], x[135]-x[130], y[135]-y[130], width=0.04, head_width=0.10, head_length=0.1, fc='k', ec='k', zorder=104) ax.annotate(r'End', xy=(x[x.shape[0]-1], y[y.shape[0]-1]), xycoords='data', xytext=(-5, 5), textcoords='offset points', fontsize=20, horizontalalignment='left', verticalalignment='bottom', zorder=101 ) ax.scatter(x[x.shape[0]-1], y[y.shape[0]-1], marker='o', facecolor='k', s=100, alpha=1.0, zorder=103) ax.add_artist(ab) plt.xlabel(r'X [$m$]', fontsize=35, fontweight='bold') plt.ylabel(r'Y [$m$]', fontsize=35, fontweight='bold') plt.grid(True) #ax.legend(handles=[exoter], loc=1, prop={'size':30}) if ground_truth: ax.set_title(r'Odometry', fontsize=35, fontweight='bold') title_str = "arl_dem_ground_truth_test_at_"+test_sampling_time else: ax.set_title(r'GP Estimate', fontsize=35, fontweight='bold') title_str = "arl_dem_" + method_name + "_train_at_"+train_sampling_time+"_test_at_"+test_sampling_time #plt.show(block=False) fig.savefig(title_str+".png", dpi=fig.dpi) return None
def plotter(choice, numNeurons, numTimeSteps, maxNeurons, maxTimeSteps, reverse, numInputNeurons, colorNeurons, redStart, redEnd, greenStart, greenEnd, blueStart, blueEnd, eatNeuron, mateNeuron, fightNeuron, moveNeuron, yawNeuron, label, behaviorLabels, inputLabels): rhythm_file = open_file(choice, "r") line = next_line(rhythm_file) line = next_line(rhythm_file) figwidth = 12.0 figheight = 8.0 fig = pylab.figure(figsize=(figwidth,figheight)) ax = fig.add_subplot(111) ax.set_xlim(0.5, maxTimeSteps+0.5) ax.set_ylim(maxNeurons-0.5, -0.5) pylab.title(label) pylab.ylabel('Neuron Index') pylab.xlabel('Time Step') linewidth = 0.715 * fig.get_figwidth() * fig.get_dpi() / maxTimeSteps for time in range(numTimeSteps): x = [] y = [] colors = [] for neuron in range(numNeurons): activ = line.split() x.append(time+1) y.append(neuron-0.5) activation = float(activ[1]) if reverse: activation = 1.0 - activation if colorNeurons: if neuron in range(redStart, redEnd+1): colors.append((activation, activation*ALT_COLOR_MAX, activation*ALT_COLOR_MAX, 1.0)) elif neuron in range(greenStart, greenEnd+1): colors.append((activation*ALT_COLOR_MAX, activation, activation*ALT_COLOR_MAX, 1.0)) elif neuron in range(blueStart, blueEnd+1): colors.append((activation*ALT_COLOR_MAX, activation*ALT_COLOR_MAX, activation, 1.0)) elif neuron == eatNeuron: colors.append((activation*ALT_COLOR_MAX, activation, activation*ALT_COLOR_MAX, 1.0)) elif neuron == mateNeuron: colors.append((activation*ALT_COLOR_MAX, activation*ALT_COLOR_MAX, activation, 1.0)) elif neuron == fightNeuron: colors.append((activation, activation*ALT_COLOR_MAX, activation*ALT_COLOR_MAX, 1.0)) elif neuron == yawNeuron: colors.append((activation, activation, activation*ALT_COLOR_MAX, 1.0)) else: colors.append((activation, activation, activation, 1.0)) else: colors.append((activation, activation, activation, 1.0)) line = next_line(rhythm_file) x.append(time+1) y.append(neuron+0.5) colors.append((activation, activation, activation, 1.0)) points = zip(x, y) segments = zip(points[:-1], points[1:]) lc = LineCollection(segments, colors=colors) lc.set_alpha(1.0) lc.set_linewidth(linewidth) lc.set_antialiased(False) ax.add_collection(lc) rhythm_file.close() if behaviorLabels: matplotlib.pyplot.text(maxTimeSteps+1.5, eatNeuron, "Eat", weight="ultralight", size="small", va="center") matplotlib.pyplot.text(maxTimeSteps+1.5, mateNeuron, "Mate", weight="ultralight", size="small", va="center") matplotlib.pyplot.text(maxTimeSteps+1.5, fightNeuron, "Fight", weight="ultralight", size="small", va="center") matplotlib.pyplot.text(maxTimeSteps+1.5, moveNeuron, "Move", weight="ultralight", size="small", va="center") matplotlib.pyplot.text(maxTimeSteps+1.5, yawNeuron, "Turn", weight="ultralight", size="small", va="center") matplotlib.pyplot.text(maxTimeSteps+1.5, yawNeuron+1, "Light", weight="ultralight", size="small", va="center") matplotlib.pyplot.text(maxTimeSteps+1.5, yawNeuron+2, "Focus", weight="ultralight", size="small", va="center") if inputLabels: matplotlib.pyplot.text(maxTimeSteps+1.5, 0, "Random", weight="ultralight", size="small", va="center") matplotlib.pyplot.text(maxTimeSteps+1.5, 1, "Health", weight="ultralight", size="small", va="center") for neuron in range(redStart, redEnd+1): matplotlib.pyplot.text(maxTimeSteps+1.5, neuron, "R", weight="ultralight", size="small", va="center") for neuron in range(greenStart, greenEnd+1): matplotlib.pyplot.text(maxTimeSteps+1.5, neuron, "G", weight="ultralight", size="small", va="center") for neuron in range(blueStart, blueEnd+1): matplotlib.pyplot.text(maxTimeSteps+1.5, neuron, "B", weight="ultralight", size="small", va="center")
def draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=1.0, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, label=None, **kwds): """Draw the edges of the graph G. This draws only the edges of the graph G. Parameters ---------- G : graph A networkx graph pos : dictionary A dictionary with nodes as keys and positions as values. Positions should be sequences of length 2. edgelist : collection of edge tuples Draw only specified edges(default=G.edges()) width : float, or array of floats Line width of edges (default=1.0) edge_color : color string, or array of floats Edge color. Can be a single color format string (default='r'), or a sequence of colors with the same length as edgelist. If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters. style : string Edge line style (default='solid') (solid|dashed|dotted,dashdot) alpha : float The edge transparency (default=1.0) edge_ cmap : Matplotlib colormap Colormap for mapping intensities of edges (default=None) edge_vmin,edge_vmax : floats Minimum and maximum for edge colormap scaling (default=None) ax : Matplotlib Axes object, optional Draw the graph in the specified Matplotlib axes. arrows : bool, optional (default=True) For directed graphs, if True draw arrowheads. label : [None| string] Label for legend Returns ------- matplotlib.collection.LineCollection `LineCollection` of the edges Notes ----- For directed graphs, "arrows" (actually just thicker stubs) are drawn at the head end. Arrows can be turned off with keyword arrows=False. Yes, it is ugly but drawing proper arrows with Matplotlib this way is tricky. Examples -------- >>> G = nx.dodecahedral_graph() >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G)) Also see the NetworkX drawing examples at https://networkx.github.io/documentation/latest/auto_examples/index.html See Also -------- draw() draw_networkx() draw_networkx_nodes() draw_networkx_labels() draw_networkx_edge_labels() """ try: import matplotlib import matplotlib.pyplot as plt import matplotlib.cbook as cb from matplotlib.colors import colorConverter, Colormap from matplotlib.collections import LineCollection import numpy as np except ImportError: raise ImportError("Matplotlib required for draw()") except RuntimeError: print("Matplotlib unable to open display") raise if ax is None: ax = plt.gca() if edgelist is None: edgelist = list(G.edges()) if not edgelist or len(edgelist) == 0: # no edges! return None # set edge positions edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist]) if not cb.iterable(width): lw = (width,) else: lw = width if not cb.is_string_like(edge_color) \ and cb.iterable(edge_color) \ and len(edge_color) == len(edge_pos): if np.alltrue([cb.is_string_like(c) for c in edge_color]): # (should check ALL elements) # list of color letters such as ['k','r','k',...] edge_colors = tuple([colorConverter.to_rgba(c, alpha) for c in edge_color]) elif np.alltrue([not cb.is_string_like(c) for c in edge_color]): # If color specs are given as (rgb) or (rgba) tuples, we're OK if np.alltrue([cb.iterable(c) and len(c) in (3, 4) for c in edge_color]): edge_colors = tuple(edge_color) else: # numbers (which are going to be mapped with a colormap) edge_colors = None else: raise ValueError('edge_color must consist of either color names or numbers') else: if cb.is_string_like(edge_color) or len(edge_color) == 1: edge_colors = (colorConverter.to_rgba(edge_color, alpha), ) else: raise ValueError( 'edge_color must be a single color or list of exactly m colors where m is the number or edges') edge_collection = LineCollection(edge_pos, colors=edge_colors, linewidths=lw, antialiaseds=(1,), linestyle=style, transOffset=ax.transData, ) edge_collection.set_zorder(1) # edges go behind nodes edge_collection.set_label(label) ax.add_collection(edge_collection) # Note: there was a bug in mpl regarding the handling of alpha values for # each line in a LineCollection. It was fixed in matplotlib in r7184 and # r7189 (June 6 2009). We should then not set the alpha value globally, # since the user can instead provide per-edge alphas now. Only set it # globally if provided as a scalar. if cb.is_numlike(alpha): edge_collection.set_alpha(alpha) if edge_colors is None: if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap)) edge_collection.set_array(np.asarray(edge_color)) edge_collection.set_cmap(edge_cmap) if edge_vmin is not None or edge_vmax is not None: edge_collection.set_clim(edge_vmin, edge_vmax) else: edge_collection.autoscale() arrow_collection = None if G.is_directed() and arrows: # a directed graph hack # draw thick line segments at head end of edge # waiting for someone else to implement arrows that will work arrow_colors = edge_colors a_pos = [] p = 1.0 - 0.25 # make head segment 25 percent of edge length for src, dst in edge_pos: x1, y1 = src x2, y2 = dst dx = x2 - x1 # x offset dy = y2 - y1 # y offset d = np.sqrt(float(dx**2 + dy**2)) # length of edge if d == 0: # source and target at same position continue if dx == 0: # vertical edge xa = x2 ya = dy * p + y1 if dy == 0: # horizontal edge ya = y2 xa = dx * p + x1 else: theta = np.arctan2(dy, dx) xa = p * d * np.cos(theta) + x1 ya = p * d * np.sin(theta) + y1 a_pos.append(((xa, ya), (x2, y2))) arrow_collection = LineCollection(a_pos, colors=arrow_colors, linewidths=[4 * ww for ww in lw], antialiaseds=(1,), transOffset=ax.transData, ) arrow_collection.set_zorder(1) # edges go behind nodes arrow_collection.set_label(label) ax.add_collection(arrow_collection) # update view minx = np.amin(np.ravel(edge_pos[:, :, 0])) maxx = np.amax(np.ravel(edge_pos[:, :, 0])) miny = np.amin(np.ravel(edge_pos[:, :, 1])) maxy = np.amax(np.ravel(edge_pos[:, :, 1])) w = maxx - minx h = maxy - miny padx, pady = 0.05 * w, 0.05 * h corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady) ax.update_datalim(corners) ax.autoscale_view() # if arrow_collection: return edge_collection
def draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=1.0, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, **kwds): """Draw the edges of the graph G This draws only the edges of the graph G. pos is a dictionary keyed by vertex with a two-tuple of x-y positions as the value. See networkx_v099.layout for functions that compute node positions. edgelist is an optional list of the edges in G to be drawn. If provided, only the edges in edgelist will be drawn. edgecolor can be a list of matplotlib color letters such as 'k' or 'b' that lists the color of each edge; the list must be ordered in the same way as the edge list. Alternatively, this list can contain numbers and those number are mapped to a color scale using the color map edge_cmap. For directed graphs, "arrows" (actually just thicker stubs) are drawn at the head end. Arrows can be turned off with keyword arrows=False. See draw_networkx_v099 for the list of other optional parameters. """ if ax is None: ax=matplotlib.pylab.gca() if edgelist is None: edgelist=G.edges() if not edgelist or len(edgelist)==0: # no edges! return None # set edge positions edge_pos=asarray([(pos[e[0]],pos[e[1]]) for e in edgelist]) if not cb.iterable(width): lw = (width,) else: lw = width if not cb.is_string_like(edge_color) \ and cb.iterable(edge_color) \ and len(edge_color)==len(edge_pos): if matplotlib.numerix.alltrue([cb.is_string_like(c) for c in edge_color]): # (should check ALL elements) # list of color letters such as ['k','r','k',...] edge_colors = tuple([colorConverter.to_rgba(c,alpha) for c in edge_color]) elif matplotlib.numerix.alltrue([not cb.is_string_like(c) for c in edge_color]): # numbers (which are going to be mapped with a colormap) edge_colors = None else: raise ValueError('edge_color must consist of either color names or numbers') else: if len(edge_color)==1: edge_colors = ( colorConverter.to_rgba(edge_color, alpha), ) else: raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges') edge_collection = LineCollection(edge_pos, colors = edge_colors, linewidths = lw, antialiaseds = (1,), linestyle = style, transOffset = ax.transData, ) edge_collection.set_alpha(alpha) # need 0.87.7 or greater for edge colormaps mpl_version=matplotlib.__version__ if mpl_version.endswith('svn'): mpl_version=matplotlib.__version__[0:-3] if mpl_version.endswith('pre'): mpl_version=matplotlib.__version__[0:-3] if map(int,mpl_version.split('.'))>=[0,87,7]: if edge_colors is None: if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap)) edge_collection.set_array(asarray(edge_color)) edge_collection.set_cmap(edge_cmap) if edge_vmin is not None or edge_vmax is not None: edge_collection.set_clim(edge_vmin, edge_vmax) else: edge_collection.autoscale() matplotlib.pylab.sci(edge_collection) # else: # sys.stderr.write(\ # """matplotlib version >= 0.87.7 required for colormapped edges. # (version %s detected)."""%matplotlib.__version__) # raise UserWarning(\ # """matplotlib version >= 0.87.7 required for colormapped edges. # (version %s detected)."""%matplotlib.__version__) arrow_collection=None if G.directed and arrows: # a directed graph hack # draw thick line segments at head end of edge # waiting for someone else to implement arrows that will work arrow_colors = ( colorConverter.to_rgba('k', alpha), ) a_pos=[] p=1.0-0.25 # make head segment 25 percent of edge length for src,dst in edge_pos: x1,y1=src x2,y2=dst dx=x2-x1 # x offset dy=y2-y1 # y offset d=sqrt(float(dx**2+dy**2)) # length of edge if d==0: # source and target at same position continue if dx==0: # vertical edge xa=x2 ya=dy*p+y1 if dy==0: # horizontal edge ya=y2 xa=dx*p+x1 else: theta=arctan2(dy,dx) xa=p*d*cos(theta)+x1 ya=p*d*sin(theta)+y1 a_pos.append(((xa,ya),(x2,y2))) arrow_collection = LineCollection(a_pos, colors = arrow_colors, linewidths = [4*ww for ww in lw], antialiaseds = (1,), transOffset = ax.transData, ) # update view minx = amin(ravel(edge_pos[:,:,0])) maxx = amax(ravel(edge_pos[:,:,0])) miny = amin(ravel(edge_pos[:,:,1])) maxy = amax(ravel(edge_pos[:,:,1])) w = maxx-minx h = maxy-miny padx, pady = 0.05*w, 0.05*h corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady) ax.update_datalim( corners) ax.autoscale_view() edge_collection.set_zorder(1) # edges go behind nodes ax.add_collection(edge_collection) if arrow_collection: arrow_collection.set_zorder(1) # edges go behind nodes ax.add_collection(arrow_collection) return edge_collection
def run(self): if self.data is None: self.parent.threadPlot = None return peakF = None peakL = None total = len(self.data) if total > 0: self.parent.clear_plots() lc = None if self.average: avg = OrderedDict() count = len(self.data) for timeStamp in self.data: if len(self.data[timeStamp]) < 2: return for x, y in self.data[timeStamp].items(): if x in avg: avg[x] = (avg[x] + y) / 2 else: avg[x] = y data = avg.items() peakF, peakL = max(data, key=lambda item: item[1]) segments, levels = self.create_segments(data) lc = LineCollection(segments) lc.set_array(numpy.array(levels)) lc.set_norm(self.get_norm(self.autoL, self.extent)) lc.set_cmap(self.colourMap) lc.set_linewidth(self.lineWidth) lc.set_gid('plot') self.axes.add_collection(lc) self.parent.lc = lc else: count = 0.0 for timeStamp in self.data: if len(self.data[timeStamp]) < 2: self.parent.threadPlot = None return if self.fade: alpha = (total - count) / total else: alpha = 1 data = self.data[timeStamp].items() peakF, peakL = self.extent.get_peak_fl() segments, levels = self.create_segments(data) lc = LineCollection(segments) lc.set_array(numpy.array(levels)) lc.set_norm(self.get_norm(self.autoL, self.extent)) lc.set_cmap(self.colourMap) lc.set_linewidth(self.lineWidth) lc.set_gid('plot') lc.set_alpha(alpha) self.axes.add_collection(lc) count += 1 if self.annotate: self.annotate_plot(peakF, peakL) if total > 0: self.parent.scale_plot() self.parent.redraw_plot() self.parent.threadPlot = None
def draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=1.0, arrowstyle='-|>', arrowsize=10, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, label=None, node_size=300, nodelist=None, node_shape="o", connectionstyle=None, **kwds): """Draw the edges of the graph G. This draws only the edges of the graph G. Parameters ---------- G : graph A networkx graph pos : dictionary A dictionary with nodes as keys and positions as values. Positions should be sequences of length 2. edgelist : collection of edge tuples Draw only specified edges(default=G.edges()) width : float, or array of floats Line width of edges (default=1.0) edge_color : color string, or array of floats Edge color. Can be a single color format string (default='r'), or a sequence of colors with the same length as edgelist. If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters. style : string Edge line style (default='solid') (solid|dashed|dotted,dashdot) alpha : float The edge transparency (default=1.0) edge_ cmap : Matplotlib colormap Colormap for mapping intensities of edges (default=None) edge_vmin,edge_vmax : floats Minimum and maximum for edge colormap scaling (default=None) ax : Matplotlib Axes object, optional Draw the graph in the specified Matplotlib axes. arrows : bool, optional (default=True) For directed graphs, if True draw arrowheads. Note: Arrows will be the same color as edges. arrowstyle : str, optional (default='-|>') For directed graphs, choose the style of the arrow heads. See :py:class: `matplotlib.patches.ArrowStyle` for more options. arrowsize : int, optional (default=10) For directed graphs, choose the size of the arrow head head's length and width. See :py:class: `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale` for more info. connectionstyle : str, optional (default=None) Pass the connectionstyle parameter to create curved arc of rounding radius rad. For example, connectionstyle='arc3,rad=0.2'. See :py:class: `matplotlib.patches.ConnectionStyle` and :py:class: `matplotlib.patches.FancyArrowPatch` for more info. label : [None| string] Label for legend Returns ------- matplotlib.collection.LineCollection `LineCollection` of the edges list of matplotlib.patches.FancyArrowPatch `FancyArrowPatch` instances of the directed edges Depending whether the drawing includes arrows or not. Notes ----- For directed graphs, arrows are drawn at the head end. Arrows can be turned off with keyword arrows=False. Be sure to include `node_size` as a keyword argument; arrows are drawn considering the size of nodes. Examples -------- >>> G = nx.dodecahedral_graph() >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G)) >>> G = nx.DiGraph() >>> G.add_edges_from([(1, 2), (1, 3), (2, 3)]) >>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G)) >>> alphas = [0.3, 0.4, 0.5] >>> for i, arc in enumerate(arcs): # change alpha values of arcs ... arc.set_alpha(alphas[i]) Also see the NetworkX drawing examples at https://networkx.github.io/documentation/latest/auto_examples/index.html See Also -------- draw() draw_networkx() draw_networkx_nodes() draw_networkx_labels() draw_networkx_edge_labels() """ try: import matplotlib import matplotlib.pyplot as plt import matplotlib.cbook as cb from matplotlib.colors import colorConverter, Colormap, Normalize from matplotlib.collections import LineCollection from matplotlib.patches import FancyArrowPatch import numpy as np except ImportError: raise ImportError("Matplotlib required for draw()") except RuntimeError: print("Matplotlib unable to open display") raise if ax is None: ax = plt.gca() if edgelist is None: edgelist = list(G.edges()) if not edgelist or len(edgelist) == 0: # no edges! return None if nodelist is None: nodelist = list(G.nodes()) # set edge positions edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist]) if not cb.iterable(width): lw = (width,) else: lw = width if not is_string_like(edge_color) \ and cb.iterable(edge_color) \ and len(edge_color) == len(edge_pos): if np.alltrue([is_string_like(c) for c in edge_color]): # (should check ALL elements) # list of color letters such as ['k','r','k',...] edge_colors = tuple([colorConverter.to_rgba(c, alpha) for c in edge_color]) elif np.alltrue([not is_string_like(c) for c in edge_color]): # If color specs are given as (rgb) or (rgba) tuples, we're OK if np.alltrue([cb.iterable(c) and len(c) in (3, 4) for c in edge_color]): edge_colors = tuple(edge_color) else: # numbers (which are going to be mapped with a colormap) edge_colors = None else: raise ValueError('edge_color must contain color names or numbers') else: if is_string_like(edge_color) or len(edge_color) == 1: edge_colors = (colorConverter.to_rgba(edge_color, alpha), ) else: msg = 'edge_color must be a color or list of one color per edge' raise ValueError(msg) if (not G.is_directed() or not arrows): edge_collection = LineCollection(edge_pos, colors=edge_colors, linewidths=lw, antialiaseds=(1,), linestyle=style, transOffset=ax.transData, ) edge_collection.set_zorder(1) # edges go behind nodes edge_collection.set_label(label) ax.add_collection(edge_collection) # Note: there was a bug in mpl regarding the handling of alpha values # for each line in a LineCollection. It was fixed in matplotlib by # r7184 and r7189 (June 6 2009). We should then not set the alpha # value globally, since the user can instead provide per-edge alphas # now. Only set it globally if provided as a scalar. if isinstance(alpha, Number): edge_collection.set_alpha(alpha) if edge_colors is None: if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap)) edge_collection.set_array(np.asarray(edge_color)) edge_collection.set_cmap(edge_cmap) if edge_vmin is not None or edge_vmax is not None: edge_collection.set_clim(edge_vmin, edge_vmax) else: edge_collection.autoscale() return edge_collection arrow_collection = None if G.is_directed() and arrows: # Note: Waiting for someone to implement arrow to intersection with # marker. Meanwhile, this works well for polygons with more than 4 # sides and circle. def to_marker_edge(marker_size, marker): if marker in "s^>v<d": # `large` markers need extra space return np.sqrt(2 * marker_size) / 2 else: return np.sqrt(marker_size) / 2 # Draw arrows with `matplotlib.patches.FancyarrowPatch` arrow_collection = [] mutation_scale = arrowsize # scale factor of arrow head arrow_colors = edge_colors if arrow_colors is None: if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap)) else: edge_cmap = plt.get_cmap() # default matplotlib colormap if edge_vmin is None: edge_vmin = min(edge_color) if edge_vmax is None: edge_vmax = max(edge_color) color_normal = Normalize(vmin=edge_vmin, vmax=edge_vmax) for i, (src, dst) in enumerate(edge_pos): x1, y1 = src x2, y2 = dst arrow_color = None line_width = None shrink_source = 0 # space from source to tail shrink_target = 0 # space from head to target if cb.iterable(node_size): # many node sizes src_node, dst_node = edgelist[i][:2] index_node = nodelist.index(dst_node) marker_size = node_size[index_node] shrink_target = to_marker_edge(marker_size, node_shape) else: shrink_target = to_marker_edge(node_size, node_shape) if arrow_colors is None: arrow_color = edge_cmap(color_normal(edge_color[i])) elif len(arrow_colors) > 1: arrow_color = arrow_colors[i] else: arrow_color = arrow_colors[0] if len(lw) > 1: line_width = lw[i] else: line_width = lw[0] arrow = FancyArrowPatch((x1, y1), (x2, y2), arrowstyle=arrowstyle, shrinkA=shrink_source, shrinkB=shrink_target, mutation_scale=mutation_scale, color=arrow_color, linewidth=line_width, connectionstyle=connectionstyle, zorder=1) # arrows go behind nodes # There seems to be a bug in matplotlib to make collections of # FancyArrowPatch instances. Until fixed, the patches are added # individually to the axes instance. arrow_collection.append(arrow) ax.add_patch(arrow) # update view minx = np.amin(np.ravel(edge_pos[:, :, 0])) maxx = np.amax(np.ravel(edge_pos[:, :, 0])) miny = np.amin(np.ravel(edge_pos[:, :, 1])) maxy = np.amax(np.ravel(edge_pos[:, :, 1])) w = maxx - minx h = maxy - miny padx, pady = 0.05 * w, 0.05 * h corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady) ax.update_datalim(corners) ax.autoscale_view() plt.tick_params( axis='both', which='both', bottom=False, left=False, labelbottom=False, labelleft=False) return arrow_collection
standard_deviation = fabs(standard_deviation.sum(axis=1)) standard_deviation = np.row_stack(standard_deviation) sd = la.norm(standard_deviation, axis=1) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm from matplotlib.colors import LinearSegmentedColormap as lscm cmap = plt.get_cmap('Greens') #cmap = lscm.from_list('temp', colors) norm = plt.Normalize(min(sd), max(sd)) lc = LineCollection(segments, cmap=cmap, norm=norm) lc.set_array(sd) lc.set_linewidth(40) lc.set_alpha(0.8) plt.gca().add_collection(lc) #color bar of the covariamve #cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) h_cbar = plt.colorbar(lc)#, orientation='horizontal') h_cbar.ax.set_ylabel(r' ground truth residual [$m/s$]') # Color bar of the dem cbar = plt.colorbar() # draw colorbar cbar.ax.set_ylabel(r' terrain elevation[$m$]') #Q = ax.plot(x, y, marker='o', linestyle='-', color=[0.3,0.2,0.4], alpha=0.5, lw=40) import os
def draw_edges(G, segments, pos=None, edgelist=None, width=1.0, color='k', style='solid', alpha=None, ax=None, **kwds): """Draw the edges of the graph G. This draws the edge segments given by a separation of the links in `data` of the graph G. Parameters ---------- G : graph A networkx graph segments : L x M array The segmentation of each link. (segments.sum(axis=1) == 1).all() pos : dictionary A dictionary with nodes as keys and positions as values. Positions should be sequences of length 2. (default=nx.get_node_attributes(G, 'pos')) edgelist : collection of edge tuples Draw only specified edges(default=G.edges()) width : float or array of floats Line width of edges (default =1.0) color : tuple of color strings Edge Segments color. Can be a single color format string (default='r'), or a sequence of colors with the same length as data.shape[1]. style : string Edge line style (default='solid') (solid|dashed|dotted,dashdot) alpha : float The edge transparency (default=1.0) ax : Matplotlib Axes object, optional Draw the graph in the specified Matplotlib axes. Returns ------- matplotlib.collection.LineCollection `LineCollection` of the edge segments """ if not np.allclose(segments.sum(axis=1), 1): segments = segments / segments.sum(axis=1, keepdims=True) if ax is None: ax = plt.gca() if pos is None: pos = nx.get_node_attributes(G, 'pos') if edgelist is None: edgelist = G.edges() if not edgelist or len(edgelist) == 0: # no edges! return None if not cb.iterable(width): lw = (width, ) else: lw = width if cb.iterable(color) \ and len(color) == segments.shape[1]: if np.alltrue([cb.is_string_like(c) for c in color]): # (should check ALL elements) # list of color letters such as ['k','r','k',...] edge_colors = tuple( [colorConverter.to_rgba(c, alpha) for c in color]) elif (np.alltrue([not cb.is_string_like(c) for c in color]) and np.alltrue( [cb.iterable(c) and len(c) in (3, 4) for c in color])): edge_colors = tuple(color) else: raise ValueError( 'color must consist of either color names or numbers') else: if cb.is_string_like(color) or len(color) == 1: edge_colors = (colorConverter.to_rgba(edge_color, alpha), ) else: raise ValueError( 'color must be a single color or list of exactly m colors where m is the number of segments' ) assert len(edgelist) == segments.shape[ 0], "Number edges and segments have to line up" # set edge positions edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist]) src = edge_pos[:, 0] dest = edge_pos[:, 1] positions = src[:, np.newaxis] + np.cumsum( np.hstack((np.zeros((len(segments), 1)), segments)), axis=1)[:, :, np.newaxis] * (dest - src)[:, np.newaxis] linecolls = [] for s in range(segments.shape[1]): coll = LineCollection(positions[:, s:s + 2], colors=edge_colors[s:s + 1], linewidths=lw, antialiaseds=(1, ), linestyle=style, transOffset=ax.transData) coll.set_zorder(1) # edges go behind nodes # coll.set_label(label) if cb.is_numlike(alpha): coll.set_alpha(alpha) ax.add_collection(coll) linecolls.append(coll) # update view minx = np.amin(np.ravel(edge_pos[:, :, 0])) maxx = np.amax(np.ravel(edge_pos[:, :, 0])) miny = np.amin(np.ravel(edge_pos[:, :, 1])) maxy = np.amax(np.ravel(edge_pos[:, :, 1])) w = maxx - minx h = maxy - miny padx, pady = 0.05 * w, 0.05 * h corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady) ax.update_datalim(corners) ax.autoscale_view() return linecolls
def _plot_skeleton(neuron, color, method, ax, **kwargs): """Plot skeleton.""" depth_coloring = kwargs.get('depth_coloring', False) linewidth = kwargs.get('linewidth', kwargs.get('lw', .5)) linestyle = kwargs.get('linestyle', kwargs.get('ls', '-')) alpha = kwargs.get('alpha', .9) norm = kwargs.get('norm') plot_soma = kwargs.get('soma', True) group_neurons = kwargs.get('group_neurons', False) view = kwargs.get('view', ('x', 'y')) if method == '2d': if not depth_coloring and not (isinstance(color, np.ndarray) and color.ndim == 2): # Generate by-segment coordinates coords = segments_to_coords(neuron, neuron.segments, modifier=(1, 1, 1)) # We have to add (None, None, None) to the end of each # slab to make that line discontinuous there coords = np.vstack( [np.append(t, [[None] * 3], axis=0) for t in coords]) x, y = _parse_view2d(coords, view) this_line = mlines.Line2D( x, y, lw=linewidth, ls=linestyle, alpha=alpha, color=color, label=f'{getattr(neuron, "name", "NA")} - #{neuron.id}') ax.add_line(this_line) else: coords = tn_pairs_to_coords(neuron, modifier=(1, 1, 1)) xy = _parse_view2d(coords, view) lc = LineCollection(xy, cmap='jet' if depth_coloring else None, norm=norm if depth_coloring else None, joinstyle='round') lc.set_linewidth(linewidth) lc.set_linestyle(linestyle) lc.set_label(f'{getattr(neuron, "name", "NA")} - #{neuron.id}') if depth_coloring: lc.set_alpha(alpha) lc.set_array(neuron.nodes.loc[neuron.nodes.parent_id >= 0, 'z'].values) elif (isinstance(color, np.ndarray) and color.ndim == 2): # If we have a color for each node, we need to drop the roots if color.shape[1] != coords.shape[0]: lc.set_color(color[neuron.nodes.parent_id.values >= 0]) else: lc.set_color(color) ax.add_collection(lc) if plot_soma and np.any(neuron.soma): soma = utils.make_iterable(neuron.soma) # If soma detection is messed up we might end up producing # dozens of soma which will freeze the kernel if len(soma) >= 10: logger.warning(f'{neuron.id} - {len(soma)} somas found.') for s in soma: if isinstance(color, np.ndarray) and color.ndim > 1: s_ix = np.where(neuron.nodes.node_id == s)[0][0] soma_color = color[s_ix] else: soma_color = color n = neuron.nodes.set_index('node_id').loc[s] r = getattr(n, neuron.soma_radius) if isinstance( neuron.soma_radius, str) else neuron.soma_radius if depth_coloring: d = [n.x, n.y, n.z][_get_depth_axis(view)] soma_color = mpl.cm.jet(norm(d)) sx, sy = _parse_view2d(np.array([[n.x, n.y, n.z]]), view) c = mpatches.Circle((sx[0], sy[0]), radius=r, alpha=alpha, fill=True, fc=soma_color, zorder=4, edgecolor='none') ax.add_patch(c) return None, None elif method in ['3d', '3d_complex']: # For simple scenes, add whole neurons at a time to speed up rendering if method == '3d': if (isinstance(color, np.ndarray) and color.ndim == 2) or depth_coloring: coords = tn_pairs_to_coords(neuron, modifier=(1, 1, 1)) # If we have a color for each node, we need to drop the roots if isinstance( color, np.ndarray) and color.shape[1] != coords.shape[0]: line_color = color[neuron.nodes.parent_id.values >= 0] else: line_color = color else: # Generate by-segment coordinates coords = segments_to_coords(neuron, neuron.segments, modifier=(1, 1, 1)) line_color = color lc = Line3DCollection( coords, color=line_color, label=neuron.id, alpha=alpha if not kwargs.get('shade_by', False) else None, cmap=mpl.cm.jet if depth_coloring else None, lw=linewidth, joinstyle='round', linestyle=linestyle) if group_neurons: lc.set_gid(neuron.id) # Need to get this before adding data line3D_collection = lc ax.add_collection3d(lc) # For complex scenes, add each segment as a single collection # -> helps reducing Z-order errors elif method == '3d_complex': # Generate by-segment coordinates coords = segments_to_coords(neuron, neuron.segments, modifier=(1, 1, 1)) for c in coords: lc = Line3DCollection([c], color=color, lw=linewidth, alpha=alpha, linestyle=linestyle) if group_neurons: lc.set_gid(neuron.id) ax.add_collection3d(lc) line3D_collection = None surf3D_collections = [] if plot_soma and not isinstance(getattr(neuron, 'soma', None), type(None)): soma = utils.make_iterable(neuron.soma) # If soma detection is messed up we might end up producing # dozens of soma which will freeze the kernel if len(soma) >= 5: logger.warning( f'Neuron {neuron.id} appears to have {len(soma)}' ' somas. Skipping plotting its somas.') else: for s in soma: if isinstance(color, np.ndarray) and color.ndim > 1: s_ix = np.where(neuron.nodes.node_id == s)[0][0] soma_color = color[s_ix] else: soma_color = color n = neuron.nodes.set_index('node_id').loc[s] r = getattr(n, neuron.soma_radius) if isinstance( neuron.soma_radius, str) else neuron.soma_radius resolution = 20 u = np.linspace(0, 2 * np.pi, resolution) v = np.linspace(0, np.pi, resolution) x = r * np.outer(np.cos(u), np.sin(v)) + n.x y = r * np.outer(np.sin(u), np.sin(v)) + n.y z = r * np.outer(np.ones(np.size(u)), np.cos(v)) + n.z surf = ax.plot_surface(x, y, z, color=soma_color, shade=False, alpha=alpha) if group_neurons: surf.set_gid(neuron.id) surf3D_collections.append(surf) return line3D_collection, surf3D_collections
squarecorner[3].x ] shadowlats = [ squarecorner[0].y, squarecorner[1].y, squarecorner[2].y, squarecorner[3].y ] x, y = m(shadowlons, shadowlats) shpsegs = [] shpsegs.append(list(zip(x, y))) lines = LineCollection(shpsegs, antialiaseds=(1, )) #不可航行区域 if (squareprolist[plotsquareCount].isNavigonal == False): lines.set_facecolors(cm.jet(0.1)) lines.set_edgecolors('g') lines.set_linewidth(0.6) lines.set_alpha(0.6) #设置透明度 ax.add_collection(lines) #绘制不可行区域 else: lines.set_facecolors(cm.jet(0.02)) lines.set_edgecolors('b') lines.set_linewidth(1.2) #lines.set_alpha(0.1) #设置透明度 # 设置颜色深度,权重越大深度越大 weight = Naviweight.get(squareprolist[plotsquareCount].offsetCoord, 1) if weight < 1: weight = 1 if weight > 10: weight = 10 lines.set_alpha(0.1 * weight) # 设置透明度 # ax.add_collection(lines)
dbf = dbflib.open('../states/statesp020') for npoly in range(shp.info()[0]): # draw colored polygons on the map shpseqs = [] shp_object = shp.read_object(npoly) verts = shp_object.vertices() rings = len(verts) for ring in range(rings): lons, lats = zip(*verts[ring]) x, y = m(lons,lats) shpsegs.append(zip(x,y)) if ring == 0: shapedict = dbf.read_record(npoly) name = shapedict['STATE'] lines = LineCollection(shpsegs,antialiased=(1,)) # state_to_code dict, e.g. 'ALASKA' -> 'AK', omitted try: per = obama[state_to_code[name.upper()]] except KeyError: continue lines.set_facecolors('k') lines.set_alpha(0.75 * per) # shrink the percentage a bit lines.set_edgecolors('k') lines.set_linewidth(0.3) ax.add_collection(lines) plt.show()
def country(countries, bmap, fc=None, ec='none', lw=1, alpha=1, adm=0, gadmpath='/home/dtr/Documents/Webpages/blog-notebooks/data/TravelMap/'): """Colour <countries> with a <bmap> projection. This script is adapted from: http://www.geophysique.be/2013/02/12/ matplotlib-basemap-tutorial-10-shapefiles-unleached-continued I downloaded the countries shapefile from the *Global Administrative Areas* website, [gadm.org](http://gadm.org). => You have to use the same abbreviations for the countries as GADM does, or adjust the script. => You have to download the shapefiles from GADM, and extract them into the <gadmpath> directory. Of course, you can use any other shapfiles you have, and adjust the script accordingly. Parameters ---------- countries : string or list of strings Countries to be plotted. bmap : handle As you get from bmap = Basemap(). fc : None or colour, or list of colours; <None> Face-colour for country; if <None>, it will cycle through colour-cycle. ec : 'none' or colour (scalar or list); <'none'> Edge-colour for country. lw : scalar or list; <1> Linewidth for country. alpha: scalar or list; <1> Transparency. adm : {0, 1, 2, 3}; <0> Administrative area to choose. gadmpath : 'string' Absolut or relative path to shapefiles. """ # Ensure countries is a list if not isinstance(countries, list): countries = [countries,] # Get current axis cax = plt.gca() # Loop through the countries for country in countries: # Get shapefile for the country; extract shapes and records r = shapefile.Reader(gadmpath+country+'_adm/'+country+'_adm'+str(adm)) shapes = r.shapes() records = r.records() # Loop through the records; for adm0 this is only 1 run n = 0 for record, shape in zip(records,shapes): lons,lats = zip(*shape.points) data = np.array(bmap(lons, lats)).T if len(shape.parts) == 1: segs = [data,] else: segs = [] for i in range(1,len(shape.parts)): index = shape.parts[i-1] index2 = shape.parts[i] segs.append(data[index:index2]) segs.append(data[index2:]) lines = LineCollection(segs,antialiaseds=(1,)) # If facecolor is provided, use; else cycle through colours if fc: if not isinstance(fc, list): lines.set_facecolors(fc) else: lines.set_facecolors(fc[n]) else: cycle = cax._get_lines.prop_cycler lines.set_facecolors(next(cycle)['color']) # Edge colour if not isinstance(ec, list): lines.set_edgecolors(ec) else: lines.set_edgecolors(ec[n]) # Alpha if not isinstance(alpha, list): lines.set_alpha(alpha) else: lines.set_alpha(alpha[n]) # Line width if not isinstance(lw, list): lines.set_linewidth(lw) else: lines.set_linewidth(lw[n]) # Add to current plot cax.add_collection(lines) n += 1
def draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=None, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, **kwds): """Draw the edges of the graph G This draws only the edges of the graph G. pos is a dictionary keyed by vertex with a two-tuple of x-y positions as the value. See networkx.layout for functions that compute node positions. edgelist is an optional list of the edges in G to be drawn. If provided, only the edges in edgelist will be drawn. edgecolor can be a list of matplotlib color letters such as 'k' or 'b' that lists the color of each edge; the list must be ordered in the same way as the edge list. Alternatively, this list can contain numbers and those number are mapped to a color scale using the color map edge_cmap. Finally, it can also be a list of (r,g,b) or (r,g,b,a) tuples, in which case these will be used directly to color the edges. If the latter mode is used, you should not provide a value for alpha, as it would be applied globally to all lines. For directed graphs, "arrows" (actually just thicker stubs) are drawn at the head end. Arrows can be turned off with keyword arrows=False. See draw_networkx for the list of other optional parameters. """ try: import matplotlib import matplotlib.pylab as pylab import numpy as np from matplotlib.colors import colorConverter,Colormap from matplotlib.collections import LineCollection except ImportError: raise ImportError("Matplotlib required for draw()") except RuntimeError: pass # unable to open display if ax is None: ax=pylab.gca() if edgelist is None: edgelist=G.edges() if not edgelist or len(edgelist)==0: # no edges! return None # set edge positions edge_pos=np.asarray([(pos[e[0]],pos[e[1]]) for e in edgelist]) if not cb.iterable(width): lw = (width,) else: lw = width if not cb.is_string_like(edge_color) \ and cb.iterable(edge_color) \ and len(edge_color)==len(edge_pos): if np.alltrue([cb.is_string_like(c) for c in edge_color]): # (should check ALL elements) # list of color letters such as ['k','r','k',...] edge_colors = tuple([colorConverter.to_rgba(c,alpha) for c in edge_color]) elif np.alltrue([not cb.is_string_like(c) for c in edge_color]): # If color specs are given as (rgb) or (rgba) tuples, we're OK if np.alltrue([cb.iterable(c) and len(c) in (3,4) for c in edge_color]): edge_colors = tuple(edge_color) alpha=None else: # numbers (which are going to be mapped with a colormap) edge_colors = None else: raise ValueError('edge_color must consist of either color names or numbers') else: if len(edge_color)==1: edge_colors = ( colorConverter.to_rgba(edge_color, alpha), ) else: raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges') edge_collection = LineCollection(edge_pos, colors = edge_colors, linewidths = lw, antialiaseds = (1,), linestyle = style, transOffset = ax.transData, ) # Note: there was a bug in mpl regarding the handling of alpha values for # each line in a LineCollection. It was fixed in matplotlib in r7184 and # r7189 (June 6 2009). We should then not set the alpha value globally, # since the user can instead provide per-edge alphas now. Only set it # globally if provided as a scalar. if cb.is_numlike(alpha): edge_collection.set_alpha(alpha) # need 0.87.7 or greater for edge colormaps. No checks done, this will # just not work with an older mpl if edge_colors is None: if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap)) edge_collection.set_array(np.asarray(edge_color)) edge_collection.set_cmap(edge_cmap) if edge_vmin is not None or edge_vmax is not None: edge_collection.set_clim(edge_vmin, edge_vmax) else: edge_collection.autoscale() pylab.sci(edge_collection) arrow_collection=None if G.is_directed() and arrows: # a directed graph hack # draw thick line segments at head end of edge # waiting for someone else to implement arrows that will work arrow_colors = ( colorConverter.to_rgba('k', alpha), ) a_pos=[] p=1.0-0.25 # make head segment 25 percent of edge length for src,dst in edge_pos: x1,y1=src x2,y2=dst dx=x2-x1 # x offset dy=y2-y1 # y offset d=np.sqrt(float(dx**2+dy**2)) # length of edge if d==0: # source and target at same position continue if dx==0: # vertical edge xa=x2 ya=dy*p+y1 if dy==0: # horizontal edge ya=y2 xa=dx*p+x1 else: theta=np.arctan2(dy,dx) xa=p*d*np.cos(theta)+x1 ya=p*d*np.sin(theta)+y1 a_pos.append(((xa,ya),(x2,y2))) arrow_collection = LineCollection(a_pos, colors = arrow_colors, linewidths = [4*ww for ww in lw], antialiaseds = (1,), transOffset = ax.transData, ) # update view minx = np.amin(np.ravel(edge_pos[:,:,0])) maxx = np.amax(np.ravel(edge_pos[:,:,0])) miny = np.amin(np.ravel(edge_pos[:,:,1])) maxy = np.amax(np.ravel(edge_pos[:,:,1])) w = maxx-minx h = maxy-miny padx, pady = 0.05*w, 0.05*h corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady) ax.update_datalim( corners) ax.autoscale_view() edge_collection.set_zorder(1) # edges go behind nodes ax.add_collection(edge_collection) if arrow_collection: arrow_collection.set_zorder(1) # edges go behind nodes ax.add_collection(arrow_collection) return edge_collection
def draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=1.0, arrowstyle='-|>', arrowsize=10, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, label=None, node_size=300, nodelist=None, node_shape="o", **kwds): """Draw the edges of the graph G. This draws only the edges of the graph G. Parameters ---------- G : graph A networkx graph pos : dictionary A dictionary with nodes as keys and positions as values. Positions should be sequences of length 2. edgelist : collection of edge tuples Draw only specified edges(default=G.edges()) width : float, or array of floats Line width of edges (default=1.0) edge_color : color string, or array of floats Edge color. Can be a single color format string (default='r'), or a sequence of colors with the same length as edgelist. If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters. style : string Edge line style (default='solid') (solid|dashed|dotted,dashdot) alpha : float The edge transparency (default=1.0) edge_ cmap : Matplotlib colormap Colormap for mapping intensities of edges (default=None) edge_vmin,edge_vmax : floats Minimum and maximum for edge colormap scaling (default=None) ax : Matplotlib Axes object, optional Draw the graph in the specified Matplotlib axes. arrows : bool, optional (default=True) For directed graphs, if True draw arrowheads. Note: Arrows will be the same color as edges. arrowstyle : str, optional (default='-|>') For directed graphs, choose the style of the arrow heads. See :py:class: `matplotlib.patches.ArrowStyle` for more options. arrowsize : int, optional (default=10) For directed graphs, choose the size of the arrow head head's length and width. See :py:class: `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale` for more info. label : [None| string] Label for legend Returns ------- matplotlib.collection.LineCollection `LineCollection` of the edges list of matplotlib.patches.FancyArrowPatch `FancyArrowPatch` instances of the directed edges Depending whether the drawing includes arrows or not. Notes ----- For directed graphs, arrows are drawn at the head end. Arrows can be turned off with keyword arrows=False. Be sure to include `node_size' as a keyword argument; arrows are drawn considering the size of nodes. Examples -------- >>> G = nx.dodecahedral_graph() >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G)) >>> G = nx.DiGraph() >>> G.add_edges_from([(1, 2), (1, 3), (2, 3)]) >>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G)) >>> alphas = [0.3, 0.4, 0.5] >>> for i, arc in enumerate(arcs): # change alpha values of arcs ... arc.set_alpha(alphas[i]) Also see the NetworkX drawing examples at https://networkx.github.io/documentation/latest/auto_examples/index.html See Also -------- draw() draw_networkx() draw_networkx_nodes() draw_networkx_labels() draw_networkx_edge_labels() """ try: import matplotlib import matplotlib.pyplot as plt import matplotlib.cbook as cb from matplotlib.colors import colorConverter, Colormap, Normalize from matplotlib.collections import LineCollection from matplotlib.patches import FancyArrowPatch import numpy as np except ImportError: raise ImportError("Matplotlib required for draw()") except RuntimeError: print("Matplotlib unable to open display") raise if ax is None: ax = plt.gca() if edgelist is None: edgelist = list(G.edges()) if not edgelist or len(edgelist) == 0: # no edges! return None if nodelist is None: nodelist = list(G.nodes()) # set edge positions edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist]) if not cb.iterable(width): lw = (width,) else: lw = width if not is_string_like(edge_color) \ and cb.iterable(edge_color) \ and len(edge_color) == len(edge_pos): if np.alltrue([is_string_like(c) for c in edge_color]): # (should check ALL elements) # list of color letters such as ['k','r','k',...] edge_colors = tuple([colorConverter.to_rgba(c, alpha) for c in edge_color]) elif np.alltrue([not is_string_like(c) for c in edge_color]): # If color specs are given as (rgb) or (rgba) tuples, we're OK if np.alltrue([cb.iterable(c) and len(c) in (3, 4) for c in edge_color]): edge_colors = tuple(edge_color) else: # numbers (which are going to be mapped with a colormap) edge_colors = None else: raise ValueError('edge_color must contain color names or numbers') else: if is_string_like(edge_color) or len(edge_color) == 1: edge_colors = (colorConverter.to_rgba(edge_color, alpha), ) else: msg = 'edge_color must be a color or list of one color per edge' raise ValueError(msg) if (not G.is_directed() or not arrows): edge_collection = LineCollection(edge_pos, colors=edge_colors, linewidths=lw, antialiaseds=(1,), linestyle=style, transOffset=ax.transData, ) edge_collection.set_zorder(1) # edges go behind nodes edge_collection.set_label(label) ax.add_collection(edge_collection) # Note: there was a bug in mpl regarding the handling of alpha values # for each line in a LineCollection. It was fixed in matplotlib by # r7184 and r7189 (June 6 2009). We should then not set the alpha # value globally, since the user can instead provide per-edge alphas # now. Only set it globally if provided as a scalar. if cb.is_numlike(alpha): edge_collection.set_alpha(alpha) if edge_colors is None: if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap)) edge_collection.set_array(np.asarray(edge_color)) edge_collection.set_cmap(edge_cmap) if edge_vmin is not None or edge_vmax is not None: edge_collection.set_clim(edge_vmin, edge_vmax) else: edge_collection.autoscale() return edge_collection arrow_collection = None if G.is_directed() and arrows: # Note: Waiting for someone to implement arrow to intersection with # marker. Meanwhile, this works well for polygons with more than 4 # sides and circle. def to_marker_edge(marker_size, marker): if marker in "s^>v<d": # `large` markers need extra space return np.sqrt(2 * marker_size) / 2 else: return np.sqrt(marker_size) / 2 # Draw arrows with `matplotlib.patches.FancyarrowPatch` arrow_collection = [] mutation_scale = arrowsize # scale factor of arrow head arrow_colors = edge_colors if arrow_colors is None: if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap)) else: edge_cmap = plt.get_cmap() # default matplotlib colormap if edge_vmin is None: edge_vmin = min(edge_color) if edge_vmax is None: edge_vmax = max(edge_color) color_normal = Normalize(vmin=edge_vmin, vmax=edge_vmax) for i, (src, dst) in enumerate(edge_pos): x1, y1 = src x2, y2 = dst arrow_color = None line_width = None shrink_source = 0 # space from source to tail shrink_target = 0 # space from head to target if cb.iterable(node_size): # many node sizes src_node, dst_node = edgelist[i] index_node = nodelist.index(dst_node) marker_size = node_size[index_node] shrink_target = to_marker_edge(marker_size, node_shape) else: shrink_target = to_marker_edge(node_size, node_shape) if arrow_colors is None: arrow_color = edge_cmap(color_normal(edge_color[i])) elif len(arrow_colors) > 1: arrow_color = arrow_colors[i] else: arrow_color = arrow_colors[0] if len(lw) > 1: line_width = lw[i] else: line_width = lw[0] arrow = FancyArrowPatch((x1, y1), (x2, y2), arrowstyle=arrowstyle, shrinkA=shrink_source, shrinkB=shrink_target, mutation_scale=mutation_scale, color=arrow_color, linewidth=line_width, zorder=1) # arrows go behind nodes # There seems to be a bug in matplotlib to make collections of # FancyArrowPatch instances. Until fixed, the patches are added # individually to the axes instance. arrow_collection.append(arrow) ax.add_patch(arrow) # update view minx = np.amin(np.ravel(edge_pos[:, :, 0])) maxx = np.amax(np.ravel(edge_pos[:, :, 0])) miny = np.amin(np.ravel(edge_pos[:, :, 1])) maxy = np.amax(np.ravel(edge_pos[:, :, 1])) w = maxx - minx h = maxy - miny padx, pady = 0.05 * w, 0.05 * h corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady) ax.update_datalim(corners) ax.autoscale_view() return arrow_collection
def adaptive_matches_comparison_figure(fig_num, info_ten, info_twentyfive, info_fifty, info_hundred, pred_mean, color_bar='Reds'): ######################## # Plot matches ######################## matplotlib.rcParams.update({'font.size': 40, 'font.weight': 'bold'}) fig, ax = plt.subplots() ######################## # Odometry prediction ######################## x = info_ten.index.to_pydatetime() x[:] = [(i-x[0]).total_seconds() for i in x] y = info_ten.inliers_matches_ratio_th from numpy import linalg as la y = np.ones(len(x)) sd = la.norm(pred_mean, axis=1) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm from matplotlib.colors import LinearSegmentedColormap as lscm cmap = plt.get_cmap(color_bar) norm = plt.Normalize(0.00, 0.0634491701615) lc = LineCollection(segments, cmap=cmap, norm=norm) lc.set_array(sd) lc.set_linewidth(100) lc.set_alpha(0.8) h_cbar = plt.colorbar(lc)#, orientation='horizontal') h_cbar.ax.set_ylabel(r'threshold - odometry error [%]', fontsize=40, fontweight='bold') ######################## #Ten fill x = info_ten.index.to_pydatetime() y = info_ten.inliers_matches_ratio_th d = scipy.zeros(len(x)) ax.fill_between(x, y, 0, color='lightblue') #Scatters scatter_ten = ax.scatter(x[0], y[0], marker='s', facecolor='lightblue', edgecolor='k', label='10%', s=300, alpha=1.0, zorder=100) #Twenty five fill x = info_twentyfive.index.to_pydatetime() y = info_twentyfive.inliers_matches_ratio_th d = scipy.zeros(len(x)) ax.fill_between(x, y, 0, color='lightsteelblue') #Scatters scatter_twentyfive = ax.scatter(x[0], y[0], marker='s', facecolor='lightsteelblue', edgecolor='k', label='25%', s=300, alpha=1.0, zorder=100) #Fifty fill x = info_fifty.index.to_pydatetime() y = info_fifty.inliers_matches_ratio_th d = scipy.zeros(len(x)) #ax.fill_between(x, y, 0, color='steelblue') #Scatters #scatter_fifty = ax.scatter(x[0], y[0], marker='s', facecolor='steelblue', # edgecolor='k', label='50%', s=300, alpha=1.0, zorder=100) #Hundred fill x = info_hundred.index.to_pydatetime() y = info_hundred.inliers_matches_ratio_th d = scipy.zeros(len(x)) ax.fill_between(x, y, 0, color='blue') #Scatters scatter_hundred = ax.scatter(x[0], y[0], marker='s', facecolor='blue', edgecolor='k', label='100%', s=300, alpha=1.0, zorder=100) ######################## #Hundred line x = info_hundred.index.to_pydatetime() y = info_hundred.inliers_matches_ratio_th ax.plot(x, y, linestyle='-', lw=2, alpha=1.0, color=[0.0, 0.0, 0.0]) #Fifty line x = info_fifty.index.to_pydatetime() y = info_fifty.inliers_matches_ratio_th #ax.plot(x, y, linestyle='-', lw=2, alpha=1.0, color=[0.0, 0.0, 0.0]) #Twenty line x = info_twentyfive.index.to_pydatetime() y = info_twentyfive.inliers_matches_ratio_th ax.plot(x, y, linestyle='-', lw=2, alpha=1.0, color=[0.0, 0.0, 0.0]) #Ten line x = info_ten.index.to_pydatetime() y = info_ten.inliers_matches_ratio_th ax.plot(x, y, linestyle='-', lw=2, alpha=1.0, color=[0.0, 0.0, 0.0]) ax.set_ylabel(r'feature matching ratio [$0.0 - 0.75$]', fontsize=40, fontweight='bold') #ax.tick_params('y', colors='k') formatted_ticks = info_ten.resample('3min').mean().index.map(lambda t: t.strftime('%H:%M:%S')) plt.xticks(info_ten.resample('3min').mean().index.to_pydatetime(), formatted_ticks) ax.set_xlim(min(info_ten.resample('3min').mean().index.to_pydatetime()), max(info_ten.resample('3min').mean().index.to_pydatetime())) ax.set_xlabel(r'Time', fontsize=40, fontweight='bold') #ax.tick_params('x', colors='k') plt.grid(True) plt.legend(handles=[scatter_ten, scatter_twentyfive, scatter_hundred], loc=2, prop={'size':40}) plt.show(block=True)
def draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=1.0, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, label=None, **kwds): """Draw the edges of the graph G. This draws only the edges of the graph G. Parameters ---------- G : graph A networkx graph pos : dictionary A dictionary with nodes as keys and positions as values. Positions should be sequences of length 2. edgelist : collection of edge tuples Draw only specified edges(default=G.edges()) width : float, or array of floats Line width of edges (default=1.0) edge_color : color string, or array of floats Edge color. Can be a single color format string (default='r'), or a sequence of colors with the same length as edgelist. If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters. style : string Edge line style (default='solid') (solid|dashed|dotted,dashdot) alpha : float The edge transparency (default=1.0) edge_ cmap : Matplotlib colormap Colormap for mapping intensities of edges (default=None) edge_vmin,edge_vmax : floats Minimum and maximum for edge colormap scaling (default=None) ax : Matplotlib Axes object, optional Draw the graph in the specified Matplotlib axes. arrows : bool, optional (default=True) For directed graphs, if True draw arrowheads. label : [None| string] Label for legend Returns ------- matplotlib.collection.LineCollection `LineCollection` of the edges Notes ----- For directed graphs, "arrows" (actually just thicker stubs) are drawn at the head end. Arrows can be turned off with keyword arrows=False. Yes, it is ugly but drawing proper arrows with Matplotlib this way is tricky. Examples -------- >>> G=nx.dodecahedral_graph() >>> edges=nx.draw_networkx_edges(G,pos=nx.spring_layout(G)) Also see the NetworkX drawing examples at http://networkx.github.io/documentation/latest/gallery.html See Also -------- draw() draw_networkx() draw_networkx_nodes() draw_networkx_labels() draw_networkx_edge_labels() """ try: import matplotlib import matplotlib.pyplot as plt import matplotlib.cbook as cb from matplotlib.colors import colorConverter, Colormap from matplotlib.collections import LineCollection import numpy except ImportError: raise ImportError("Matplotlib required for draw()") except RuntimeError: print("Matplotlib unable to open display") raise if ax is None: ax = plt.gca() if edgelist is None: edgelist = list(G.edges()) if not edgelist or len(edgelist) == 0: # no edges! return None # set edge positions edge_pos = numpy.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist]) if not cb.iterable(width): lw = (width,) else: lw = width if not cb.is_string_like(edge_color) \ and cb.iterable(edge_color) \ and len(edge_color) == len(edge_pos): if numpy.alltrue([cb.is_string_like(c) for c in edge_color]): # (should check ALL elements) # list of color letters such as ['k','r','k',...] edge_colors = tuple([colorConverter.to_rgba(c, alpha) for c in edge_color]) elif numpy.alltrue([not cb.is_string_like(c) for c in edge_color]): # If color specs are given as (rgb) or (rgba) tuples, we're OK if numpy.alltrue([cb.iterable(c) and len(c) in (3, 4) for c in edge_color]): edge_colors = tuple(edge_color) else: # numbers (which are going to be mapped with a colormap) edge_colors = None else: raise ValueError('edge_color must consist of either color names or numbers') else: if cb.is_string_like(edge_color) or len(edge_color) == 1: edge_colors = (colorConverter.to_rgba(edge_color, alpha), ) else: raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges') edge_collection = LineCollection(edge_pos, colors=edge_colors, linewidths=lw, antialiaseds=(1,), linestyle=style, transOffset = ax.transData, ) edge_collection.set_zorder(1) # edges go behind nodes edge_collection.set_label(label) ax.add_collection(edge_collection) # Note: there was a bug in mpl regarding the handling of alpha values for # each line in a LineCollection. It was fixed in matplotlib in r7184 and # r7189 (June 6 2009). We should then not set the alpha value globally, # since the user can instead provide per-edge alphas now. Only set it # globally if provided as a scalar. if cb.is_numlike(alpha): edge_collection.set_alpha(alpha) if edge_colors is None: if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap)) edge_collection.set_array(numpy.asarray(edge_color)) edge_collection.set_cmap(edge_cmap) if edge_vmin is not None or edge_vmax is not None: edge_collection.set_clim(edge_vmin, edge_vmax) else: edge_collection.autoscale() arrow_collection = None if G.is_directed() and arrows: # a directed graph hack # draw thick line segments at head end of edge # waiting for someone else to implement arrows that will work arrow_colors = edge_colors a_pos = [] p = 1.0-0.25 # make head segment 25 percent of edge length for src, dst in edge_pos: x1, y1 = src x2, y2 = dst dx = x2-x1 # x offset dy = y2-y1 # y offset d = numpy.sqrt(float(dx**2 + dy**2)) # length of edge if d == 0: # source and target at same position continue if dx == 0: # vertical edge xa = x2 ya = dy*p+y1 if dy == 0: # horizontal edge ya = y2 xa = dx*p+x1 else: theta = numpy.arctan2(dy, dx) xa = p*d*numpy.cos(theta)+x1 ya = p*d*numpy.sin(theta)+y1 a_pos.append(((xa, ya), (x2, y2))) arrow_collection = LineCollection(a_pos, colors=arrow_colors, linewidths=[4*ww for ww in lw], antialiaseds=(1,), transOffset = ax.transData, ) arrow_collection.set_zorder(1) # edges go behind nodes arrow_collection.set_label(label) ax.add_collection(arrow_collection) # update view minx = numpy.amin(numpy.ravel(edge_pos[:, :, 0])) maxx = numpy.amax(numpy.ravel(edge_pos[:, :, 0])) miny = numpy.amin(numpy.ravel(edge_pos[:, :, 1])) maxy = numpy.amax(numpy.ravel(edge_pos[:, :, 1])) w = maxx-minx h = maxy-miny padx, pady = 0.05*w, 0.05*h corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady) ax.update_datalim(corners) ax.autoscale_view() # if arrow_collection: return edge_collection
boundary='extend', nan_treatment='interpolate', preserve_nan=False) ssha_m = S3postproc.rescale_between(ssha_m, -1, 1) print('SSHA: OK') # SRAL # segments points = np.array([xsr, ysr]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) norm = plt.Normalize(-1, 1) lc = LineCollection(segments, cmap='jet', norm=norm) lc.set_alpha(1) lc.set_array(ssha_m) lc.set_linewidth(8) line = ax.add_collection(lc) fdate_sral = dt.datetime.strptime(f_sral[16:31], '%Y%m%dT%H%M%S') fdate_sral = fdate_sral.strftime('%Y-%m-%d %H_%M_%S') # Keep SRAL dates that are used dates_sral.append(f_sral[:3] + '_' + fdate_sral) del ssha_m, ssha if 'line' in locals(): pass else: continue
class HoughDemo(ImageProcessDemo): TITLE = u"Hough Demo" DEFAULT_IMAGE = "stuff.jpg" SETTINGS = ["th2", "show_canny", "rho", "theta", "hough_th", "minlen", "maxgap", "dp", "mindist", "param2", "min_radius", "max_radius", "blur_sigma", "linewidth", "alpha", "check_line", "check_circle"] check_line = Bool(True) check_circle = Bool(True) #Gaussian blur parameters blur_sigma = Range(0.1, 5.0, 2.0) show_blur = Bool(False) # Canny parameters th2 = Range(0.0, 255.0, 200.0) show_canny = Bool(False) # HoughLine parameters rho = Range(1.0, 10.0, 1.0) theta = Range(0.1, 5.0, 1.0) hough_th = Range(1, 100, 40) minlen = Range(0, 100, 10) maxgap = Range(0, 20, 10) # HoughtCircle parameters dp = Range(1.0, 5.0, 1.9) mindist = Range(1.0, 100.0, 50.0) param2 = Range(5, 100, 50) min_radius = Range(5, 100, 20) max_radius = Range(10, 100, 70) # draw parameters linewidth = Range(1.0, 3.0, 1.0) alpha = Range(0.0, 1.0, 0.6) def control_panel(self): return VGroup( Group( Item("blur_sigma", label=u"标准方差"), Item("show_blur", label=u"显示结果"), label=u"高斯模糊参数" ), Group( Item("th2", label=u"阈值2"), Item("show_canny", label=u"显示结果"), label=u"边缘检测参数" ), Group( Item("rho", label=u"偏移分辨率(像素)"), Item("theta", label=u"角度分辨率(角度)"), Item("hough_th", label=u"阈值"), Item("minlen", label=u"最小长度"), Item("maxgap", label=u"最大空隙"), label=u"直线检测" ), Group( Item("dp", label=u"分辨率(像素)"), Item("mindist", label=u"圆心最小距离(像素)"), Item("param2", label=u"圆心检查阈值"), Item("min_radius", label=u"最小半径"), Item("max_radius", label=u"最大半径"), label=u"圆检测" ), Group( Item("linewidth", label=u"线宽"), Item("alpha", label=u"alpha"), HGroup( Item("check_line", label=u"直线"), Item("check_circle", label=u"圆"), ), label=u"绘图参数" ) ) def __init__(self, **kwargs): super(HoughDemo, self).__init__(**kwargs) self.connect_dirty("th2, show_canny, show_blur, rho, theta, hough_th," "min_radius, max_radius, blur_sigma," "minlen, maxgap, dp, mindist, param2, " "linewidth, alpha, check_line, check_circle") self.lines = LineCollection([], linewidths=2, alpha=0.6) self.axe.add_collection(self.lines) self.circles = EllipseCollection( [], [], [], units="xy", facecolors="none", edgecolors="red", linewidths=2, alpha=0.6, transOffset=self.axe.transData) self.axe.add_collection(self.circles) def _img_changed(self): self.img_gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) def draw(self): img_smooth = cv2.GaussianBlur(self.img_gray, (0, 0), self.blur_sigma, self.blur_sigma) img_edge = cv2.Canny(img_smooth, self.th2 * 0.5, self.th2) if self.show_blur and self.show_canny: show_img = cv2.cvtColor(np.maximum(img_smooth, img_edge), cv2.COLOR_BAYER_BG2BGR) elif self.show_blur: show_img = cv2.cvtColor(img_smooth, cv2.COLOR_BAYER_BG2BGR) elif self.show_canny: show_img = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2BGR) else: show_img = self.img if self.check_line: theta = self.theta / 180.0 * np.pi lines = cv2.HoughLinesP(img_edge, self.rho, theta, self.hough_th, minLineLength=self.minlen, maxLineGap=self.maxgap) if lines is not None: lines = lines[0] lines.shape = -1, 2, 2 self.lines.set_segments(lines) self.lines.set_visible(True) else: self.lines.set_visible(False) else: self.lines.set_visible(False) if self.check_circle: circles = cv2.HoughCircles(img_smooth, 3, self.dp, self.mindist, param1=self.th2, param2=self.param2, minRadius=self.min_radius, maxRadius=self.max_radius) if circles is not None: circles = circles[0] self.circles._heights = self.circles._widths = circles[:, 2] self.circles.set_offsets(circles[:, :2]) self.circles._angles = np.zeros(len(circles)) self.circles._transOffset = self.axe.transData self.circles.set_visible(True) else: self.circles.set_visible(False) else: self.circles.set_visible(False) self.lines.set_linewidths(self.linewidth) self.circles.set_linewidths(self.linewidth) self.lines.set_alpha(self.alpha) self.circles.set_alpha(self.alpha) self.draw_image(show_img)
def voronoi_plot_2d(vor, ax=None, **kw): """ Plot the given Voronoi diagram in 2-D Parameters ---------- vor : scipy.spatial.Voronoi instance Diagram to plot ax : matplotlib.axes.Axes instance, optional Axes to plot on show_points: bool, optional Add the Voronoi points to the plot. show_vertices : bool, optional Add the Voronoi vertices to the plot. line_colors : string, optional Specifies the line color for polygon boundaries line_width : float, optional Specifies the line width for polygon boundaries line_alpha: float, optional Specifies the line alpha for polygon boundaries Returns ------- fig : matplotlib.figure.Figure instance Figure for the plot See Also -------- Voronoi Notes ----- Requires Matplotlib. """ from matplotlib.collections import LineCollection if vor.points.shape[1] != 2: raise ValueError("Voronoi diagram is not 2-D") if kw.get('show_points', True): ax.plot(vor.points[:,0], vor.points[:,1], '.') if kw.get('show_vertices', True): ax.plot(vor.vertices[:,0], vor.vertices[:,1], 'o') line_colors = kw.get('line_colors', 'k') line_width = kw.get('line_width', 1.0) line_alpha = kw.get('line_alpha', 1.0) line_segments = [] for simplex in vor.ridge_vertices: simplex = np.asarray(simplex) if np.all(simplex >= 0): line_segments.append([(x, y) for x, y in vor.vertices[simplex]]) lc = LineCollection(line_segments, colors=line_colors, lw=line_width, linestyle='solid') lc.set_alpha(line_alpha) ax.add_collection(lc) ptp_bound = vor.points.ptp(axis=0) line_segments = [] center = vor.points.mean(axis=0) for pointidx, simplex in zip(vor.ridge_points, vor.ridge_vertices): simplex = np.asarray(simplex) if np.any(simplex < 0): i = simplex[simplex >= 0][0] # finite end Voronoi vertex t = vor.points[pointidx[1]] - vor.points[pointidx[0]] # tangent t /= np.linalg.norm(t) n = np.array([-t[1], t[0]]) # normal midpoint = vor.points[pointidx].mean(axis=0) direction = np.sign(np.dot(midpoint - center, n)) * n far_point = vor.vertices[i] + direction * ptp_bound.max() line_segments.append([(vor.vertices[i, 0], vor.vertices[i, 1]), (far_point[0], far_point[1])]) lc = LineCollection(line_segments, colors=line_colors, lw=line_width, linestyle='dashed') lc.set_alpha(line_alpha) ax.add_collection(lc) _adjust_bounds(ax, vor.points) return ax.figure
def arl_dem_figure(fig_num, dem_file, trajectory, pred_mean, kf_trajectory, frames_trajectory, color_bar='Reds'): ######################## # Load Terrain DEM ######################## import os plydata = PlyData.read(open(os.path.expanduser(dem_file))) vertex = plydata['vertex'].data [dem_px, dem_py, dem_pz] = (vertex[t] for t in ('x', 'y', 'z')) # define grid. npts=100 dem_xi = np.linspace(min(dem_px), max(dem_px), npts) dem_yi = np.linspace(min(dem_py), max(dem_py), npts) # grid the data. dem_zi = griddata(dem_px, dem_py, dem_pz, dem_xi, dem_yi, interp='linear') matplotlib.rcParams.update({'font.size': 30, 'font.weight': 'bold'}) fig = plt.figure(fig_num, figsize=(28, 16), dpi=120, facecolor='w', edgecolor='k') ax = fig.add_subplot(111) #fig, ax = plt.subplots() # Display the DEM plt.rc('text', usetex=False)# activate latex text rendering CS = plt.contour(dem_xi, dem_yi, dem_zi, 15, linewidths=0.5, colors='k') CS = plt.contourf(dem_xi, dem_yi, dem_zi, 15, cmap=plt.cm.gray, vmax=abs(dem_zi).max(), vmin=-abs(dem_zi).max()) # plot data points. plt.xlim(min(dem_px), max(dem_xi)) plt.ylim(min(dem_py), max(dem_yi)) # Display Ground Truth trajectory from numpy import linalg as la x = trajectory[1:trajectory.shape[0]-1,0] y = trajectory[1:trajectory.shape[0]-1,1] sd = la.norm(pred_mean, axis=1) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm from matplotlib.colors import LinearSegmentedColormap as lscm cmap = plt.get_cmap(color_bar) norm = plt.Normalize(0.00, 0.0634491701615) lc = LineCollection(segments, cmap=cmap, norm=norm) lc.set_array(sd) lc.set_linewidth(40) lc.set_alpha(0.8) plt.gca().add_collection(lc) #color bar of the covarianve #h_cbar = plt.colorbar(lc)#, orientation='horizontal') #h_cbar.ax.set_ylabel(r' odometry error[$m/s$]', fontsize=25, fontweight='bold') # Color bar of the dem #cbar = plt.colorbar() # draw colorbar #cbar.ax.set_ylabel(r' terrain elevation[$m$]', fontsize=25, fontweight='bold') # Plot all the image frames line fr_x = frames_trajectory[:,0] fr_y = frames_trajectory[:,1] ax.plot(fr_x, fr_y, #marker='s', linestyle='-', lw=2, alpha=0.5, color=[0.0, 0.3, 1.0], label='slam trajectory', zorder=98) # Plot all the image frames ax.scatter(fr_x, fr_y, marker='s', facecolor=[0.0,0.3,1.0], edgecolor='b', label='image frames', s=300, alpha=0.2, zorder=99) # Plot the key frames kf_x = kf_trajectory[:,0] kf_y = kf_trajectory[:,1] ax.scatter(kf_x, kf_y, marker='D', facecolor=[0.2,1.0,0.0], edgecolor='b', label='keyframes', s=250, alpha=0.8, zorder=100) import os from matplotlib.cbook import get_sample_data from matplotlib._png import read_png import matplotlib.image as image from scipy import ndimage from matplotlib.offsetbox import OffsetImage, AnnotationBbox fn = get_sample_data(os.getcwd()+"/data/img/exoter.png", asfileobj=False) exoter = image.imread(fn) exoter = ndimage.rotate(exoter, 100) imexoter = OffsetImage(exoter, zoom=0.5) ab = AnnotationBbox(imexoter, xy=(x[0], y[0]), xybox=None, xycoords='data', boxcoords="offset points", frameon=False) ax.annotate(r'ExoTeR', xy=(x[1], y[1]), xycoords='data', xytext=(-40, 50), textcoords='offset points', fontsize=30, #arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2", lw=2.0) zorder=101, ) ax.annotate(r'Start', xy=(x[0], y[0]), xycoords='data', xytext=(-5, 5), textcoords='offset points', fontsize=30, horizontalalignment='left', verticalalignment='bottom', zorder=101 ) ax.scatter(x[0], y[0], marker='o', facecolor='k', s=40, alpha=1.0, zorder=103) ax.arrow(x[0], y[0], x[64]-x[0], y[64]-y[0], width=0.04, head_width=0.08, head_length=0.1, fc='k', ec='k', zorder=104) # End sign ax.annotate(r'End', xy=(fr_x[fr_x.shape[0]-1], fr_y[fr_y.shape[0]-1]), xycoords='data', xytext=(-5, 5), textcoords='offset points', fontsize=30, horizontalalignment='left', verticalalignment='bottom', zorder=101 ) ax.scatter(fr_x[fr_x.shape[0]-1], fr_y[fr_y.shape[0]-1], marker='o', facecolor='k', s=40, alpha=1.0, zorder=103) ax.add_artist(ab) plt.xlabel(r'X [$m$]', fontsize=35, fontweight='bold') plt.ylabel(r'Y [$m$]', fontsize=35, fontweight='bold') #ax.legend(loc=2, prop={'size':30}) #plt.axis('equal') plt.grid(True) fig.savefig("arl_adaptive_slam_dem_20150515-1752.png", dpi=fig.dpi) plt.show(block=True)