def hello(): rtimes, rt, rp = np.loadtxt("data/data.txt").T rtimes = map(datetime.datetime.fromtimestamp, rtimes) rtimes = matplotlib.dates.date2num(rtimes) fig = Figure() axis = fig.add_subplot(1, 1, 1) axis.xaxis_date() fig.autofmt_xdate() forecast_list = [] for fname in glob.glob("data/forecast.*.txt"): stamp = fname.split(".")[1] times, tempa = np.loadtxt(fname).T times = map(datetime.datetime.fromtimestamp, times) times = matplotlib.dates.date2num(times) points = np.array([times, tempa]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=plt.get_cmap("jet"), norm=plt.Normalize(0, 1)) lc.set_array(np.linspace(0,1,len(times))) lc.set_linewidth(1) axis.add_collection(lc) axis.plot_date(times, tempa, "-", linewidth=0) axis.plot_date(rtimes, rt, "-",linewidth=1, color="black") canvas = FigureCanvas(fig) output = StringIO.StringIO() canvas.print_png(output) response = make_response(output.getvalue()) response.mimetype = 'image/png' return response
def d3(): rtimes, rt, rp = np.loadtxt("data/data.txt").T mask = np.logical_and(rtimes>1391000000, rtimes<1393000000) rtimes = rtimes[mask] rt = rt[mask] rtimes = map(datetime.datetime.fromtimestamp, rtimes) rtimes = matplotlib.dates.date2num(rtimes) fig, axis = plt.subplots() axis.xaxis_date() fig.autofmt_xdate() axis.plot_date(rtimes, rt, "-",linewidth=3, color="black") forecast_list = [] for fname in glob.glob("data/forecast.1391*.txt"): stamp = fname.split(".")[1] times, tempa = np.loadtxt(fname).T times = map(datetime.datetime.fromtimestamp, times) times = matplotlib.dates.date2num(times) points = np.array([times, tempa]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=plt.get_cmap("jet"), norm=plt.Normalize(0, 1)) lc.set_array(np.linspace(0,1,len(times))) lc.set_linewidth(1) axis.add_collection(lc) axis.plot_date(times, tempa, "-", linewidth=2) return fig_to_html(fig)
def plot_file_color(base, thin=True, start=0, size=14, save=False): conf, track, pegs = load(base) fig = pl.figure(figsize=(size,size*conf['top']/conf['wall'])) track = track[start:] x = track[:,0]; y = track[:,1] t = np.linspace(0,1,x.shape[0]) points = np.array([x,y]).transpose().reshape(-1,1,2) segs = np.concatenate([points[:-1],points[1:]],axis=1) lc = LineCollection(segs, linewidths=0.25, cmap=pl.cm.coolwarm) lc.set_array(t) pl.gca().add_collection(lc) #pl.scatter(x, y, c=np.arange(len(x)),linestyle='-',cmap=pl.cm.coolwarm) #pl.plot(track[-1000000:,0], track[-1000000:,1], '-', linewidth=0.0125, alpha=0.8) for peg in pegs: pl.gca().add_artist(pl.Circle(peg, conf['radius'], color='k', alpha=0.3)) pl.xlim(0, conf['wall']) pl.ylim(0, conf['top']) pl.xticks([]) pl.yticks([]) pl.tight_layout() pl.show() if save: pl.savefig(base+".png", dpi=200)
def _draw_segments(ax, x, y, state, cmap, norm, lc_kwargs): """ helper function to turn boundary edges into the input LineCollection expects. Parameters ---------- ax : Axes The axes to draw to x, y, state : array The x edges, the y values and the state of each region cmap : matplotlib.colors.Colormap The color map to use norm : matplotlib.ticker.Norm The norm to use with the color map lc_kwargs : dict kwargs to pass through to LineCollection """ points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=cmap, norm=norm, **lc_kwargs) lc.set_array(state) ax.add_collection(lc) return lc
def show_bonds(bonds,start=None,lw=1,**kwargs): ''' Display a collection of bonds. bonds: A <BondCollection> instance. start: the location of starting atoms. lw,**kwargs: line width of bonds and key word arguments for *return*: None ''' vdim=bonds.vdim #this bonds is a class bondcollection bvs=[] if start is None: start=zeros([bonds.N,vdim]) elif ndim(start)==1: bvs=zip(start,bonds.bondvs+start) else: bvs=zip(start,bonds.bondvs+start) if vdim==1: bvs=[(append(start,[0]),append(end,[0])) for start,end in bvs] lc=LineCollection(bvs,**kwargs) #draw lines lc.set_linewidth(lw) ax=gca() ax.add_collection(lc) ax.autoscale() ax.margins(0.1)
def colorline(ax, x,y,z,linewidth=1, colormap='jet', norm=None, zorder=1, alpha=1, linestyle='solid'): cmap = plt.get_cmap(colormap) if type(linewidth) is list or type(linewidth) is np.array or type(linewidth) is np.ndarray: linewidths = linewidth else: linewidths = np.ones_like(z)*linewidth if norm is None: norm = plt.Normalize(np.min(z), np.max(z)) else: norm = plt.Normalize(norm[0], norm[1]) ''' if self.hide_colorbar is False: if self.cb is None: self.cb = matplotlib.colorbar.ColorbarBase(self.ax1, cmap=cmap, norm=norm, orientation='vertical', boundaries=None) ''' # Create a set of line segments so that we can color them individually # This creates the points as a N x 1 x 2 array so that we can stack points # together easily to get the segments. The segments array for line collection # needs to be numlines x points per line x 2 (x and y) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) # Create the line collection object, setting the colormapping parameters. # Have to set the actual values used for colormapping separately. lc = LineCollection(segments, linewidths=linewidths, cmap=cmap, norm=norm, zorder=zorder, alpha=alpha, linestyles=linestyle ) lc.set_array(z) lc.set_linewidth(linewidth) ax.add_collection(lc)
def main(self): x_field = self.fields_by_key('x')[0] y_field = self.fields_by_key('y')[0] x = np.array(self.slice_data(x_field,int)) y = np.array(self.slice_data(y_field,int)) n = len(x) render = StringIO.StringIO() ############################################################################### # Fit IsotonicRegression and LinearRegression models ir = IsotonicRegression() y_ = ir.fit_transform(x, y) lr = LinearRegression() lr.fit(x[:, np.newaxis], y) # x needs to be 2d for LinearRegression ############################################################################### # plot result segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)] lc = LineCollection(segments, zorder=0) lc.set_array(np.ones(len(y))) lc.set_linewidths(0.5 * np.ones(n)) fig = plt.figure() plt.plot(x, y, 'r.', markersize=12) plt.plot(x, y_, 'g.-', markersize=12) plt.plot(x, lr.predict(x[:, np.newaxis]), 'b-') plt.gca().add_collection(lc) plt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right') plt.title('Isotonic regression') plt.savefig(render,format='png') return render
def load_colorado_shapes(m): # read all US counties rdr = shapefile.Reader("../USA_adm/USA_adm2") shapes = rdr.shapes() records = rdr.records() # only keep Colorado counties ndx = filter(lambda i: records[i][4] == 'Colorado', np.arange(len(shapes))) shapes = [shapes[i] for i in ndx] records = [records[i] for i in ndx] # modified from web tutorial # http://www.geophysique.be/2013/02/12/matplotlib-basemap-tutorial-10-shapefiles-unleached-continued/ line_col = [] 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.8) line_col.append(lines) return line_col
def gradient(figure_object, axis_object, xs, ys, start_year, TWP_length, cmap, key_count): """Based on http://matplotlib.org/examples/pylab_examples/multicolored_line.html and http://stackoverflow.com/questions/19132402/set-a-colormap-under-a-graph """ from matplotlib.collections import LineCollection # plot a color_map line fading to white points = np.array([xs, ys]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=plt.get_cmap('gray'), norm=plt.Normalize(start_year, start_year+TWP_length), linewidth=0.2, zorder=1) # norm sets the color min:max range lc.set_array(np.array(xs)) axis_object.add_collection(lc) # add fading color_map fill as well xs.append(max(xs)) xs.append(min(xs)) ys.append(0) ys.append(0) poly, = axis_object.fill(xs, ys, facecolor='none', edgecolor='none') img_data = np.arange(0, 100, 1) img_data = img_data.reshape(1, img_data.size) im = axis_object.imshow(img_data, aspect='auto', origin='lower', cmap=plt.get_cmap(cmap), extent=[start_year+TWP_length, start_year, 1000, -1000], vmin=0., vmax=100., zorder=-(start_year+1)*key_count) im.set_clip_path(poly)
class Visualize: def __init__(self, v, t, e, fig, win, axesLimit=[-3,3.5,-2,2]): self.e = e.copy() self.p = [Polygon(v[ti]) for ti in t] self.p = PatchCollection(self.p, edgecolors='none') self.l = LineCollection(v[e[:,:2]]) win = win or fig.canvas.manager.window if fig is None: fig = gcf() fig.clf() ax = fig.add_axes([0.02,0.02,.98,.98]) ax.axis('scaled') ax.axis(axesLimit) ax.set_autoscale_on(False) self.axis, self.fig, self.win = ax, fig, win ax.add_collection(self.p) ax.add_collection(self.l) # ax.add_collection(self.l1) # ax.add_collection(self.l2) def update(self, title, phi): norm = Normalize(phi.min(), phi.max()) self.p.set_norm(norm) self.l.set_norm(norm) self.p.set_array(phi) self.l.set_array(phi[self.e[:,2:]].mean(1)) if not self.__dict__.has_key('colorbar'): self.colorbar = self.fig.colorbar(self.p) self.win.set_title(title) #self.fig.canvas.set_window_title(title) self.fig.canvas.draw()
def plotPattern(self, type, stats): """Common graph function for read and writes, type is either 'read' or 'write'. Stats is a bool that indicates whether to print statistics or not.""" names = self.filenames(type) #unique names of used files if not self.fileName in names: print self.fileName, "is not in our data set" return if self.data == None: self.__prepareData() self.axes.clear() graphdata = np.column_stack((self.data['off'], self.data['start'], self.data['off']+ self.data['size'], self.data['start'] + self.data['dur'])) lineSegments = LineCollection(graphdata.reshape(-1,2,2), linewidths=(4)); lineSegments.set_picker(True) self.lineCol = self.axes.add_collection(lineSegments) maxEnd = max(graphdata[:,2]) maxTime = max(graphdata[:,3]) if stats: self.__printStats() self.axes.xaxis.set_major_formatter(FuncFormatter(self.__xFormater)) self.axes.grid(color='grey', linewidth=0.5) self.axes.set_xlabel("file offset (kiB)", fontsize=16); self.axes.set_ylabel("time (ms)", fontsize=16); self.axes.set_xlim(0, maxEnd); self.axes.set_ylim(self.startTime, maxTime); self.fig.suptitle('%s' % self.__elideText(self.fileName), fontsize=9) # ticks = self.__getTicks(0, maxEnd) # plt.xticks(ticks); self.fig.autofmt_xdate()
def plotflow(nm,j,ylabel='Congestion Window Size',state=False): i=0 if state and not isinstance(nm,list): r = (1,0,0) g = (0,1,0) b = (0,0,1) clrs = np.zeros((flows[nm][3].shape[0],3)) clrs[flows[nm][-1]=='SS']=g clrs[flows[nm][-1]=='CA']=b clrs[flows[nm][-1]=='FR']=r points = np.array([flows[nm][i], flows[nm][j]]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, colors=clrs) lc.set_linewidth(1.7) fig, ax = plt.subplots() ax.add_collection(lc) ax.autoscale_view() line_ss = mlines.Line2D([], [], color='green', label='Slow Start') line_ca = mlines.Line2D([], [], color='blue', label='Congestion Avoidance') line_fr = mlines.Line2D([], [], color='red', label='Fast Recovery') plt.legend(handles=[line_ss,line_ca,line_fr]) else: if isinstance(nm,list): for n in nm: if n in flows: plt.plot(flows[n][i],flows[n][j],label=n) else: plt.plot(flows[nm][i],flows[nm][j]) plt.legend() plt.xlabel('time (s)') plt.ylabel(ylabel) plt.show()
def traceShape(file_shapefile): r = shapefile.Reader(file_shapefile) shapes = r.shapes() records = r.records() #sc_fac = 100000 for record, shape in zip(records,shapes): #print shape.points lonsh,latsh = zip(*shape.points) # lonsh = [x/sc_fac for x in lonsh] # latsh = [x/sc_fac for x in latsh] data = np.array(m(lonsh, latsh)).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(cm.jet(np.random.rand(1))) lines.set_edgecolors('k') lines.set_linewidth(0.1) ax.add_collection(lines) return None
class Tracks: def __init__(self, ax, stormcells): self.tracks = None self.update_trackmap(ax, stormcells) def update_trackmap(self, ax, stormcells): if self.tracks is not None: self.tracks.remove() self.tracks = None if self.tracks is None: self.tracks = LineCollection([]) ax.add_collection(self.tracks) self.trackmap = [] for trackid in range(np.max(stormcells['track_id']) + 1): indexes = np.where(stormcells['track_id'] == trackid)[0] # Makes sure the track segments are in chronological order indexes = indexes[np.argsort(stormcells['frame_index'][indexes])] self.trackmap.append(indexes) def update_frame(self, frame_index, stormcells): segments = [] for trackid, indexes in enumerate(self.trackmap): trackdata = stormcells[indexes] trackdata = trackdata[trackdata['frame_index'] <= frame_index] segments.append(zip(trackdata['xcent'], trackdata['ycent']) or [(np.nan, np.nan)]) self.tracks.set_segments(segments)
def changeVecteur(self, ech=1.0, col=None): """ modifie les valeurs de vecteurs existants""" self.drawVecteur(False) if type(ech) == type((3, 4)): if len(ech) >= 1: ech = ech[0] # previous object obj = self.getObjFromType("vecteur") if obj == None: return # change coordinates dep, arr_old, ech_old = obj.getData() arr = dep + (arr_old - dep) * ech / ech_old # new object lc1 = LineCollection(zip(dep, arr)) lc1.set_transform(self.transform) if col == None: col = wx.Color(0, 0, 255) a = col.Get() col = (a[0] / 255, a[1] / 255, a[2] / 255) lc1.set_color(col) obj = GraphicObject("vecteur", lc1, False, None) obj.setData([dep, arr, ech]) self.addGraphicObject(obj) self.cnv.collections[0] = lc1 self.redraw()
def get_figures(self): from matplotlib.collections import LineCollection figs = [] ys = [(1.0/self.PROCS_PER_WINDOW.value)*(i+1) for i in range(self.PROCS_PER_WINDOW.value)] all_xs = [] for rad1, procs in self.rad1_to_procs.iteritems(): windows = get_procedure_windows(procs, self.PROCS_PER_WINDOW.value, self.STEP_SIZE.value) all_xs = [] for window in windows: all_xs.append([p.fluoro for p in window]) #the matplotlib part fig = plt.figure() ax = plt.gca() ax.set_xlim(0,10) ax.set_ylim(0,1) line_segments= LineCollection([zip(xs,ys) for xs in all_xs]) line_segments.set_array(np.array(range(len(all_xs)))) ax.add_collection(line_segments) plt.title(rad1) plt.xlabel("Fluoro Time") plt.ylabel("Fraction of Procedures Below Fluoro Time") colorbar = fig.colorbar(line_segments, ticks = range(len(windows)))#ticks = ? colorbar.set_ticklabels([str(window[0].dos_start) for window in windows]) colorbar.set_label("Window Start Date") figs.append(fig) return figs
def doTracelines(xstart,ystart,zstart,step,tmax,Nmax): global ActiveAxis, ActiveCanvas, ActiveTimmlModel, ActiveSettings setActiveWindow() win = getActiveWindow() ActiveAxis.set_autoscale_on(False) width = 0.5 color = [] for j in range(getActiveNumberLayers()): color.append( ActiveSettings.get_color('Trace',j) ) color[j] = colorConverter.to_rgba( color[j] ) for i in range( len(xstart) ): xyz, time, reason, pylayers = ActiveTimmlModel.\ traceline(xstart[i],ystart[i],zstart[i],step,tmax,Nmax,tstart=0.0,window=win,labfrac = 2.0, Hfrac = 2.0) trace_color = [] for j in range(len(xyz)-1): # Number of segments one less than number of points trace_color.append( color[ pylayers[j] ] ) points = zip( xyz[:,0], xyz[:,1] ) segments = zip( points[:-1], points[1:] ) LC = LineCollection(segments, colors = trace_color) LC.set_linewidth(width) ActiveAxis.add_collection(LC) #ActiveAxis.plot( xyz[:,0], xyz[:,1], 'b' ) ActiveAxis.set_xlim(win[0],win[2]) ActiveAxis.set_ylim(win[1],win[3]) ActiveCanvas.draw()
def addLine(shapefilename): r = shapefile.Reader(shapefilename) shapes = r.shapes() records = r.records() cnt = 0 for record, shape in zip(records, shapes): print(cnt) 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,), zorder=3) # lines.set_facecolors(np.random.rand(3, 1) * 0.5 + 0.5) lines.set_edgecolors('k') lines.set_linewidth(0.3) ax.add_collection(lines) cnt += 1
def set_linestyle(self, v): if v is None or v == 'None': self._nodraw = True else: self._nodraw = False LineCollection.set_linestyle(self, v) self._cz_linesytle_name = v
def show_mf_wave(**kwargs): ion() mjfile='data/mf_W1%s_W2%s_U%s_N%s_dmu%s.npy'%(kwargs.get('K1'),kwargs.get('K2'),kwargs.get('U'),kwargs.get('nsite'),kwargs.get('dmu')) pls=load(mjfile) ampl=(pls[:2]*pls[:2].conj()).real print 'Magnituede %s'%sum(ampl,axis=1) if ONSV: return #mjfile2='data/mf_W1%s_W2%s_U%s_N%s_dmu%s.npy'%(kwargs.get('K1'),kwargs.get('K2'),kwargs.get('U'),kwargs.get('nsite'),-kwargs.get('dmu')) #pls2=load(mjfile2) #overlap=(pls2[:2].dot(pls[:2].T.conj())) #print overlap #subplot(211) #plot(abs(ket_even.state)) #ylim(0,0.5) #subplot(212) #plot(abs(ket_odd.state)) #ylim(0,0.5) #pdb.set_trace() lw=2 lc='r' nsite=pls.shape[1] for n in xrange(2): pln=ampl[n] ax=subplot(121+n) lc=LineCollection([[(i,0),(i,pln[i].item())] for i in xrange(nsite)]) lc.set_linewidth(lw) ax.add_collection(lc) ax.autoscale() ax.margins(0.1) pdb.set_trace()
def plot_spectrum(el,x=arange(2),offset=[0.,0.],ax=None,lw=3,**kwargs): ''' Plot spectrum. el: the data. x: the lower and upper limit of x. offset: the displace of data. ax: the ax. ''' N=len(el) if ax==None: ax=gca() #x=repeat([array(x)+offset[0]],N,axis=0).T x=array(x)+offset[0] el=el+offset[1] lc=LineCollection([[(x[0],el[i]),(x[1],el[i])] for i in xrange(N)],**kwargs) lc.set_linewidth(lw) #pl=ax.plot(x,concatenate([el[newaxis,...],el[newaxis,...]],axis=0)) ax.add_collection(lc) ax.autoscale() ax.margins(0.1) #for i in xrange(N): #axhline(y=el[i],xmin=x[0],xmax=x[1]) return ax
def plot_Kiel_diagram(starl): """ Plot Kiel diagram. """ x = starl['temperature'] y = starl['g'] age = starl['age']/1e6 points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) cmap = pl.cm.spectral norm = pl.Normalize(age.min(), age.max()) lc = LineCollection(segments, cmap=cmap,norm=norm) lc.set_array(age) lc.set_linewidth(3) pl.gca().add_collection(lc) pl.xlim(x.max(), x.min()) pl.ylim(y.max(), y.min()) pl.xlabel('Effective temperature [K]') pl.ylabel('log(surface gravity [cm s$^{-2}$]) [dex]') ax0 = pl.gca() ax1 = pl.mpl.colorbar.make_axes(ax0)[0] norm = pl.mpl.colors.Normalize(age.min(), age.max()) cb1 = pl.mpl.colorbar.ColorbarBase(ax1, cmap=cmap, norm=norm,orientation='vertical') cb1.set_label('Age [Myr]') pl.axes(ax0)
def plot_multi_line(x, y, z, bins, colors, ax): """ Plot a multi-color line. See: http://matplotlib.sourceforge.net/examples/ pylab_examples/multicolored_line.html """ from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm # Allow specifying bin centers, not edges if len(bins) == len(colors): bins = np.array(bins, dtype=np.float) bins = np.concatenate([[z.min() - 1], (bins[1:] + bins[:-1]) / 2.0, [z.max() + 1]]) cmap = ListedColormap(colors) norm = BoundaryNorm(bins, cmap.N) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=cmap, norm=norm) lc.set_array(z) lc.set_linewidth(3) ax.add_collection(lc)
def map_along_line(x, y, q, ax=None, cmap=None, norm=None, time=None, max_step=1., missing=np.nan, new_timebase=None, **kwargs): """Map some quantity q along x,y as a coloured line. With time set, perform linear interpolation of x,y,q onto new_timebase filling with missing, and with max_step.""" if ax is None: ax = plt.gca() if x.shape != y.shape: raise ValueError('Shape mismatch') if x.shape != q.shape: raise ValueError('Shape mismatch') if time is not None: if new_timebase is None: new_timebase = np.arange(time[0], time[-1], np.min(np.diff(time))) # Bit redundant x = interp_safe(new_timebase, time, x, max_step=max_step, missing=missing) y = interp_safe(new_timebase, time, y, max_step=max_step, missing=missing) q = interp_safe(new_timebase, time, q, max_step=max_step, missing=missing) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=cmap, norm=norm, **kwargs) lc.set_array(q) plt.gca().add_collection(lc) return lc
def update_line(num, print_loss, data, axes, epochsInds, test_error, test_data, epochs_bins, loss_train_data, loss_test_data, colors, font_size = 18, axis_font=16, x_lim = [0,12.2], y_lim=[0, 1.08], x_ticks = [], y_ticks = []): """Update the figure of the infomration plane for the movie""" #Print the line between the points cmap = ListedColormap(LAYERS_COLORS) segs = [] for i in range(0, data.shape[1]): x = data[0, i, num, :] y = data[1, i, num, :] points = np.array([x, y]).T.reshape(-1, 1, 2) segs.append(np.concatenate([points[:-1], points[1:]], axis=1)) segs = np.array(segs).reshape(-1, 2, 2) axes[0].clear() if len(axes)>1: axes[1].clear() lc = LineCollection(segs, cmap=cmap, linestyles='solid',linewidths = 0.3, alpha = 0.6) lc.set_array(np.arange(0,5)) #Print the points for layer_num in range(data.shape[3]): axes[0].scatter(data[0, :, num, layer_num], data[1, :, num, layer_num], color = colors[layer_num], s = 35,edgecolors = 'black',alpha = 0.85) axes[1].plot(epochsInds[:num], 1 - np.mean(test_error[:, :num], axis=0), color ='r') title_str = 'Information Plane - Epoch number - ' + str(epochsInds[num]) utils.adjustAxes(axes[0], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True, x_label='$I(X;T)$', y_label='$I(T;Y)$') title_str = 'Precision as function of the epochs' utils.adjustAxes(axes[1], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True, x_label='# Epochs', y_label='Precision')
def update_scalarmappable(self): # # update_scalamappable in super class will # set proper size of edgecolors # then I need to set alpha # LineCollection.update_scalarmappable(self) self.set_alpha(self._cz_alpha)
def plot_colored_line(x,y, color, cmap = 'spectral_r', line_width = 2): """Plot a line with color code""" segments = np.array([x, y]).T.reshape(-1, 1, 2); segments = np.concatenate([segments[:-1], segments[1:]], axis=1); lc = LineCollection(segments, cmap=cmap); lc.set_array(np.array(color)); #lc.set_linewidth(line_width); plt.gca().add_collection(lc)
def __init__(self, coords, plotSegments, linewidths, linestyle, colors, picker): LineCollection.__init__(self, plotSegments, linewidths=linewidths, linestyle=linestyle, colors=colors, picker=picker )
def segments(X,Y,color=(1,0,0,0)): N = X.shape[0] z = np.zeros((N,2,2)); z[:,0,:] = X z[:,1,:] = Y lc = LineCollection(z) lc.set_color(color) plt.gca().add_collection(lc)
def fading_line(x, y, color='black', alpha_initial=1., alpha_final=0., glow=False, **kwargs): """ Returns a matplotlib LineCollection connecting the points in the x and y lists, with a single color and alpha varying from alpha_initial to alpha_final along the line. Can pass any kwargs you can pass to LineCollection, like linewidgth. Parameters ---------- x : list or array of floats for the positions on the (plot's) x axis y : list or array of floats for the positions on the (plot's) y axis color : matplotlib color for the line. Can also pass a 3-tuple of RGB values (default: 'black') alpha_initial: Limiting value of alpha to use at the beginning of the arrays. alpha_final: Limiting value of alpha to use at the end of the arrays. """ try: from matplotlib.collections import LineCollection from matplotlib.colors import LinearSegmentedColormap import numpy as np except: raise ImportError("Error importing matplotlib and/or numpy. Plotting functions not available. If running from within a jupyter notebook, try calling '%matplotlib inline' beforehand.") if glow: glow = False kwargs["lw"] = 1 fl1 = fading_line(x, y, color, alpha_initial, alpha_final, glow=False, **kwargs) kwargs["lw"] = 2 alpha_initial *= 0.5 alpha_final *= 0.5 fl2 = fading_line(x, y, color, alpha_initial, alpha_final, glow=False, **kwargs) kwargs["lw"] = 6 alpha_initial *= 0.5 alpha_final *= 0.5 fl3 = fading_line(x, y, color, alpha_initial, alpha_final, glow=False, **kwargs) return [fl3,fl2,fl1] color = get_color(color) cdict = {'red': ((0.,color[0],color[0]),(1.,color[0],color[0])), 'green': ((0.,color[1],color[1]),(1.,color[1],color[1])), 'blue': ((0.,color[2],color[2]),(1.,color[2],color[2])), 'alpha': ((0.,alpha_initial, alpha_initial), (1., alpha_final, alpha_final))} Npts = len(x) if len(y) != Npts: raise AttributeError("x and y must have same dimension.") segments = np.zeros((Npts-1,2,2)) segments[0][0] = [x[0], y[0]] for i in range(1,Npts-1): pt = [x[i], y[i]] segments[i-1][1] = pt segments[i][0] = pt segments[-1][1] = [x[-1], y[-1]] individual_cm = LinearSegmentedColormap('indv1', cdict) lc = LineCollection(segments, cmap=individual_cm, **kwargs) lc.set_array(np.linspace(0.,1.,len(segments))) return lc
def init_artists(self, ax, plot_args, plot_kwargs): line_segments = LineCollection(*plot_args, **plot_kwargs) ax.add_collection(line_segments) return {'artist': line_segments}
hlines.append(style) # draw vertical lines for child in n.children: cstyle = child._get_style() coords[child] = __draw_edge(child, y) nodes.append(style) nodex.append(x) nodey.append(y) # draw root __draw_edge(tree, 0) lstyles = ['-', '--', ':'] hline_col = LineCollection(hlinec, colors=[l['hz_line_color'] for l in hlines], linestyle=[lstyles[l['hz_line_type']] for l in hlines], linewidth=[(l['hz_line_width'] + 1.) / 2 for l in hlines]) vline_col = LineCollection(vlinec, colors=[l['vt_line_color'] for l in vlines], linestyle=[lstyles[l['vt_line_type']] for l in vlines], linewidth=[(l['vt_line_width'] + 1.) / 2 for l in vlines]) ali_line_col = LineCollection(ali_lines, colors='k') tree_ax.add_collection(hline_col) tree_ax.add_collection(vline_col) tree_ax.add_collection(ali_line_col) nshapes = dict((('circle', 'o'), ('square', 's'), ('sphere', 'o'))) shapes = set(n['shape'] for n in nodes) for shape in shapes: indexes = [i for i, n in enumerate(nodes) if n['shape'] == shape] scat = tree_ax.scatter([nodex[i] for i in indexes],
self.fc[:, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle() if __name__ == '__main__': G = nx.read_gpickle(GRAPH_PATH) graph_data = nx.get_node_attributes(G, 'pos') data = np.array(tuple(graph_data.values())) labels = np.zeros(len(data)) instances = np.zeros(len(data)) edgelist = list(G.edges()) edge_pos = np.asarray([(graph_data[e[0]], graph_data[e[1]]) for e in edgelist]) edge_collection = LineCollection(edge_pos) edge_collection.set_zorder(1) # edges go behind nodes edge_collection.set_label(None) fig, ax = plt.subplots() pts = ax.scatter(data[:, 0], data[:, 1], s=80, c='b') ax.add_collection(edge_collection) selector = SelectFromCollection(ax, pts) fc = pts.get_facecolors() mode = 'SELECT' instance = 1 fig.suptitle("Mode: " + mode + " | Instance: " + str(instance), x=0.5, y=0.05)
def set_segments(self, segments): ''' Set 3D segments ''' self._segments3d = np.asanyarray(segments) LineCollection.set_segments(self, [])
def __init__(self, segments, *args, **kwargs): ''' Keyword arguments are passed onto :func:`~matplotlib.collections.LineCollection`. ''' LineCollection.__init__(self, segments, *args, **kwargs)
def draw(self, *argrs, **kargs): self._transform_path() if not self._nodraw: LineCollection.draw(self, *argrs, **kargs)
def set_linewidth(self, v): LineCollection.set_linewidth(self, v)
maximum_of_spectrum = np.append(maximum_of_spectrum, np.max(Pressure)) plt.rcParams['axes.facecolor'] = 'white' points = np.array([radius / 1000, np.abs(profile)]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) # fig, axs = plt.subplots(1, 1, sharex=True, sharey=True) fig.set_size_inches(15, 10) # plt.fill_between(radius / 1000, np.ones(5000) * np.max(np.abs(profile)) + 1, np.abs(profile), linewidth=5,color="grey") # plt.fill_between(radius / 1000, np.abs(profile), np.zeros(5000) + 1-50 , linewidth=5, color="blue", alpha=0.2) plt.plot(x_sum / 1000, y_sum - 40, color="green") plt.plot([0, radius[-1] / 1000], [0 - 50, 0 - 50], linewidth=5, color="blue") norm = plt.Normalize(Pressure.min(), Pressure.max()) lc = LineCollection(segments, cmap='hot', norm=norm) lc.set_array(Pressure) lc.set_linewidth(6) line = axs.add_collection(lc) fig.colorbar(line, ax=axs) axs.set_xlim(radius.min() / 1000, radius.max() / 1000) axs.set_ylim(np.abs(profile).max(), -100) plt.xlabel("distance [km]") plt.ylabel("ocean depth [m]") plt.show() # stri=path+"/ocean_bottom_profile(flat part)_loc: x_0:"+str(int(x_0))+" y_0:_"+str(int(y_0))+"_period: "\ # +str(np.round(T[iii],2))+" theta_0: "+str(theta_0)+".png" # plt.savefig(stri) stri_max="/home/djamel/PHD_projects/FOH_ICE/maximum_of_the_pressure_amplification_factor/"+"/maximum_of_ocean_bottom_profile(flat part)_loc: x_0:"+str(int(x_0))\
def draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=1.0, arrowstyle='-|>', arrowsize=10, draw_loop=False, 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 if draw_loop == False: arrow = arrow arrow_collection.append(arrow) ax.add_patch(arrow) else: cycle_edges = list(nx.simple_cycles(G)) loop_points = [(x, y) for x, y in cycle_edges] for x in loop_points: to_remove = list(G.edges()) half_cycle = to_remove.index(x) second_half = to_remove.index(x[::-1]) if (src in edge_pos[half_cycle][0] and dst in edge_pos[half_cycle][1]) or ( src in edge_pos[second_half][0] and dst in edge_pos[second_half][1]): arrow1 = FancyArrowPatch( (x1, y1), (x2, y2), arrowstyle=arrowstyle, shrinkA=shrink_source, connectionstyle= 'angle3, angleA=28.66', #180/2pi, approx shrinkB=shrink_target, mutation_scale=mutation_scale, color=arrow_color, linewidth=line_width, zorder=1) # arrows go behind nodes arrow_collection.append(arrow1) ax.add_patch(arrow1) try: arrow2 = FancyArrowPatch( (x2, y2), (x1, y1), arrowstyle=arrowstyle, shrinkA=shrink_source, connectionstyle='angle3, angleA=28.66', #180/2pi shrinkB=shrink_target, mutation_scale=mutation_scale, color=arrow_color, linewidth=line_width, zorder=1) # arrows go behind nodes arrow_collection.append(arrow2) ax.add_patch(arrow2) except nx.NetworkXError: raise else: arrow = arrow 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
# -*- coding: utf-8 -*- """ Created on Thu Dec 10 11:07:11 2020 @author: 80lascha """ import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib import colors as mcolors import pandas as pd fig = plt.figure(figsize=(12, 6)) ax = plt.axes() ax.set_facecolor('whitesmoke') lines = [z[0:6], z[6:10]] line_segments = LineCollection( lines, colors=[mcolors.to_rgb("blue"), mcolors.to_rgb("green")]) ax.add_collection(line_segments) ax.autoscale() plt.grid() plt.xlabel("Date") plt.ylabel("Price ($)") plt.show()
def _imshow_grid_values( grid, values, plot_name=None, var_name=None, var_units=None, grid_units=(None, None), symmetric_cbar=False, cmap="pink", limits=None, colorbar_label=None, allow_colorbar=True, vmin=None, vmax=None, norm=None, shrink=1.0, color_for_closed="black", color_for_background=None, show_elements=False, output=None, ): cmap = plt.get_cmap(cmap) if color_for_closed is not None: cmap.set_bad(color=color_for_closed) else: cmap.set_bad(alpha=0.0) if isinstance(grid, RasterModelGrid): if values.ndim != 2: raise ValueError("values must have ndim == 2") y = (np.arange(values.shape[0] + 1) * grid.dy - grid.dy * 0.5 + grid.xy_of_lower_left[1]) x = (np.arange(values.shape[1] + 1) * grid.dx - grid.dx * 0.5 + grid.xy_of_lower_left[0]) kwds = dict(cmap=cmap) (kwds["vmin"], kwds["vmax"]) = (values.min(), values.max()) if (limits is None) and ((vmin is None) and (vmax is None)): if symmetric_cbar: (var_min, var_max) = (values.min(), values.max()) limit = max(abs(var_min), abs(var_max)) (kwds["vmin"], kwds["vmax"]) = (-limit, limit) elif limits is not None: (kwds["vmin"], kwds["vmax"]) = (limits[0], limits[1]) else: if vmin is not None: kwds["vmin"] = vmin if vmax is not None: kwds["vmax"] = vmax myimage = plt.pcolormesh(x, y, values, **kwds) myimage.set_rasterized(True) plt.gca().set_aspect(1.0) plt.autoscale(tight=True) if allow_colorbar: cb = plt.colorbar(norm=norm, shrink=shrink) if colorbar_label: cb.set_label(colorbar_label) else: import matplotlib.colors as colors import matplotlib.cm as cmx if limits is not None: (vmin, vmax) = (limits[0], limits[1]) else: if vmin is None: vmin = values.min() if vmax is None: vmax = values.max() if symmetric_cbar: vmin, vmax = -max(abs(vmin), abs(vmax)), max( abs(vmin), abs(vmax)) cNorm = colors.Normalize(vmin, vmax) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap) colorVal = scalarMap.to_rgba(values)[grid.node_at_cell] patches = [] for corners in grid.corners_at_cell: valid_corners = corners[corners != grid.BAD_INDEX] closed_loop_corners = np.concatenate( [valid_corners, [valid_corners[0]]]) x = grid.x_of_corner[closed_loop_corners] y = grid.y_of_corner[closed_loop_corners] xy = np.vstack((x, y)).T patches.append(Polygon(xy, closed=True, fill=True)) patchcollection = PatchCollection(patches, facecolor=colorVal, edgecolor=colorVal) ax = plt.gca() ax.add_collection(patchcollection) if show_elements: x = grid.x_of_corner[grid.corners_at_face] y = grid.y_of_corner[grid.corners_at_face] segs = np.dstack((x, y)) line_segments = LineCollection(segs) line_segments.set_color("black") ax.add_collection(line_segments) ax.set_aspect(1.0) ax.set_rasterized(True) plt.xlim((np.min(grid.x_of_node), np.max(grid.x_of_node))) plt.ylim((np.min(grid.y_of_node), np.max(grid.y_of_node))) scalarMap.set_array(values) if allow_colorbar: cb = plt.colorbar(scalarMap, shrink=shrink) if grid_units[1] is None and grid_units[0] is None: grid_units = grid.axis_units if grid_units[1] == "-" and grid_units[0] == "-": plt.xlabel("X") plt.ylabel("Y") else: plt.xlabel("X (%s)" % grid_units[1]) plt.ylabel("Y (%s)" % grid_units[0]) else: plt.xlabel("X (%s)" % grid_units[1]) plt.ylabel("Y (%s)" % grid_units[0]) if plot_name is not None: plt.title("%s" % (plot_name)) if var_name is not None or var_units is not None: if var_name is not None: assert type(var_name) is str if var_units is not None: assert type(var_units) is str colorbar_label = var_name + " (" + var_units + ")" else: colorbar_label = var_name else: assert type(var_units) is str colorbar_label = "(" + var_units + ")" assert type(colorbar_label) is str assert allow_colorbar cb.set_label(colorbar_label) if color_for_background is not None: plt.gca().set_facecolor(color_for_background) if output is not None: if type(output) is str: plt.savefig(output) plt.clf() elif output: plt.show()
partial_correlations *= d[:, np.newaxis] non_zero = (np.abs(np.triu(partial_correlations, k=1)) > 0.02) # Plot the nodes using the coordinates of our embedding plt.scatter(embedding[0], embedding[1], s=100 * d ** 2, c=labels, cmap=plt.cm.spectral) # Plot the edges start_idx, end_idx = np.where(non_zero) #a sequence of (*line0*, *line1*, *line2*), where:: # linen = (x0, y0), (x1, y1), ... (xm, ym) segments = [[embedding[:, start], embedding[:, stop]] for start, stop in zip(start_idx, end_idx)] values = np.abs(partial_correlations[non_zero]) lc = LineCollection(segments, zorder=0, cmap=plt.cm.hot_r, norm=plt.Normalize(0, .7 * values.max())) lc.set_array(values) lc.set_linewidths(15 * values) ax.add_collection(lc) # Add a label to each node. The challenge here is that we want to # position the labels to avoid overlap with other labels for index, (name, label, (x, y)) in enumerate( zip(names, labels, embedding.T)): dx = x - embedding[0] dx[index] = 1 dy = y - embedding[1] dy[index] = 1 this_dx = dx[np.argmin(np.abs(dy))]
def draw(self, renderer, project=False): if project: self.do_3d_projection(renderer) LineCollection.draw(self, renderer)
def make_labeled_images_from_dataframe( df, cfg, destfolder="", scale=1.0, dpi=100, keypoint="+", draw_skeleton=True, color_by="bodypart", ): """ Write labeled frames to disk from a DataFrame. Parameters ---------- df : pd.DataFrame DataFrame containing the labeled data. Typically, the DataFrame is obtained through pandas.read_csv() or pandas.read_hdf(). cfg : dict Project configuration. destfolder : string, optional Destination folder into which images will be stored. By default, same location as the labeled data. Note that the folder will be created if it does not exist. scale : float, optional Up/downscale the output dimensions. By default, outputs are of the same dimensions as the original images. dpi : int, optional Output resolution. 100 dpi by default. keypoint : str, optional Keypoint appearance. By default, keypoints are marked by a + sign. Refer to https://matplotlib.org/3.2.1/api/markers_api.html for a list of all possible options. draw_skeleton : bool, optional Whether to draw the animal skeleton as defined in *cfg*. True by default. color_by : str, optional Color scheme of the keypoints. Must be either 'bodypart' or 'individual'. By default, keypoints are colored relative to the bodypart they represent. """ bodyparts = df.columns.get_level_values("bodyparts") bodypart_names = bodyparts.unique() nbodyparts = len(bodypart_names) bodyparts = bodyparts[::2] draw_skeleton = draw_skeleton and cfg[ 'skeleton'] # Only draw if a skeleton is defined if color_by == "bodypart": map_ = bodyparts.map(dict(zip(bodypart_names, range(nbodyparts)))) cmap = get_cmap(nbodyparts, cfg["colormap"]) colors = cmap(map_) elif color_by == "individual": try: individuals = df.columns.get_level_values("individuals") individual_names = individuals.unique().to_list() nindividuals = len(individual_names) individuals = individuals[::2] map_ = individuals.map( dict(zip(individual_names, range(nindividuals)))) cmap = get_cmap(nindividuals, cfg["colormap"]) colors = cmap(map_) except KeyError as e: raise Exception( "Coloring by individuals is only valid for multi-animal data" ) from e else: raise ValueError( "`color_by` must be either `bodypart` or `individual`.") bones = [] if draw_skeleton: for bp1, bp2 in cfg["skeleton"]: match1, match2 = [], [] for j, bp in enumerate(bodyparts): if bp == bp1: match1.append(j) elif bp == bp2: match2.append(j) bones.extend(zip(match1, match2)) ind_bones = tuple(zip(*bones)) sep = "/" if "/" in df.index[0] else "\\" images = cfg["project_path"] + sep + df.index if sep != os.path.sep: images = images.str.replace(sep, os.path.sep) if not destfolder: destfolder = os.path.dirname(images[0]) # print("Debug; reading from files: ", images) tmpfolder = destfolder + "_labeled" attempttomakefolder(tmpfolder) # Charlie: allow this to work with tiff files if cfg['using_z_slices']: # This is just a list ic = [io.imread(file) for file in images.to_list()] # ic = io.imread_collection(images.to_list(), plugin='tifffile') else: ic = io.imread_collection(images.to_list()) # Charlie: if z_slices, format is zxy if cfg['using_z_slices']: h, w = ic[0].shape[1:3] else: h, w = ic[0].shape[:2] fig, ax = prepare_figure_axes(w, h, scale, dpi) fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) im = ax.imshow(np.zeros((h, w)), "gray") scat = ax.scatter([], [], s=cfg["dotsize"], alpha=cfg["alphavalue"], marker=keypoint) scat.set_color(colors) # Charlie: only keep xy if annotations are xyz if cfg['using_z_slices']: # Why do I need a 4 here? does the old df not have likelihoods but I do? xy = df.values.reshape((df.shape[0], -1, 3))[:, :, 1:3] # xy = df.values.reshape((df.shape[0], -1, 4))[:,:,1:3] im.set_clim(0.0, 1.0) # Is this needed even for 2d? I think so else: xy = df.values.reshape((df.shape[0], -1, 2)) segs = xy[:, ind_bones].swapaxes(1, 2) coll = LineCollection([], colors=cfg["skeleton_color"], alpha=cfg["alphavalue"]) ax.add_collection(coll) for i in trange(len(ic)): coords = xy[i] # Charlie: Do a max projection if 3d if cfg['using_z_slices']: proj_frame = np.max(ic[i], axis=0) proj_frame = proj_frame / np.max(np.max(proj_frame)) im.set_array(proj_frame) # print("Performing max projection from original shape:", ic[i].shape) # print("Max of projected data: ", np.max(im.get_array(),axis=0), np.max(im.get_array(),axis=1)) # print("To new shape:", proj_frame.shape) else: im.set_array(ic[i]) if ind_bones: coll.set_segments(segs[i]) scat.set_offsets(coords) # imagename = os.path.basename(ic.files[i]) imagename = os.path.basename(images.to_list()[i]) fig.tight_layout() fig.savefig( os.path.join(tmpfolder, imagename.replace(".png", f"_{color_by}.png"))) plt.close(fig)
def set_segments(self, segments): """ Set 3D segments. """ self._segments3d = np.asanyarray(segments) LineCollection.set_segments(self, [])
def plot_graph_route(G, route, bbox=None, fig_height=6, fig_width=None, margin=0.02, bgcolor='w', axis_off=True, show=True, save=False, close=True, file_format='png', filename='temp', dpi=300, annotate=False, node_color='#999999', node_size=15, node_alpha=1, node_edgecolor='none', node_zorder=1, edge_color='#999999', edge_linewidth=1, edge_alpha=1, use_geom=True, origin_point=None, destination_point=None, route_color='r', route_linewidth=4, route_alpha=0.5, orig_dest_node_alpha=0.5, orig_dest_node_size=100, orig_dest_node_color='r', orig_dest_point_color='b'): """ Plot a route along a networkx spatial graph. Parameters ---------- G : networkx multidigraph route : list the route as a list of nodes bbox : tuple bounding box as north,south,east,west - if None will calculate from spatial extents of data fig_height : int matplotlib figure height in inches fig_width : int matplotlib figure width in inches margin : float relative margin around the figure axis_off : bool if True turn off the matplotlib axis bgcolor : string the background color of the figure and axis show : bool if True, show the figure save : bool if True, save the figure as an image file to disk close : bool close the figure (only if show equals False) to prevent display file_format : string the format of the file to save (e.g., 'jpg', 'png', 'svg') filename : string the name of the file if saving dpi : int the resolution of the image file if saving annotate : bool if True, annotate the nodes in the figure node_color : string the color of the nodes node_size : int the size of the nodes node_alpha : float the opacity of the nodes node_edgecolor : string the color of the node's marker's border node_zorder : int zorder to plot nodes, edges are always 2, so make node_zorder 1 to plot nodes beneath them or 3 to plot nodes atop them edge_color : string the color of the edges' lines edge_linewidth : float the width of the edges' lines edge_alpha : float the opacity of the edges' lines use_geom : bool if True, use the spatial geometry attribute of the edges to draw geographically accurate edges, rather than just lines straight from node to node origin_point : tuple optional, an origin (lat, lon) point to plot instead of the origin node destination_point : tuple optional, a destination (lat, lon) point to plot instead of the destination node route_color : string the color of the route route_linewidth : int the width of the route line route_alpha : float the opacity of the route line orig_dest_node_alpha : float the opacity of the origin and destination nodes orig_dest_node_size : int the size of the origin and destination nodes orig_dest_node_color : string the color of the origin and destination nodes orig_dest_point_color : string the color of the origin and destination points if being plotted instead of nodes Returns ------- fig, ax : tuple """ # plot the graph but not the route fig, ax = plot_graph(G, bbox=bbox, fig_height=fig_height, fig_width=fig_width, margin=margin, axis_off=axis_off, bgcolor=bgcolor, show=False, save=False, close=False, filename=filename, dpi=dpi, annotate=annotate, node_color=node_color, node_size=node_size, node_alpha=node_alpha, node_edgecolor=node_edgecolor, node_zorder=node_zorder, edge_color=edge_color, edge_linewidth=edge_linewidth, edge_alpha=edge_alpha, use_geom=use_geom) # the origin and destination nodes are the first and last nodes in the route origin_node = route[0] destination_node = route[-1] if origin_point is None or destination_point is None: # if caller didn't pass points, use the first and last node in route as origin/destination origin_destination_lats = (G.node[origin_node]['y'], G.node[destination_node]['y']) origin_destination_lons = (G.node[origin_node]['x'], G.node[destination_node]['x']) else: # otherwise, use the passed points as origin/destination origin_destination_lats = (origin_point[0], destination_point[0]) origin_destination_lons = (origin_point[1], destination_point[1]) orig_dest_node_color = orig_dest_point_color # scatter the origin and destination points ax.scatter(origin_destination_lons, origin_destination_lats, s=orig_dest_node_size, c=orig_dest_node_color, alpha=orig_dest_node_alpha, edgecolor=node_edgecolor, zorder=4) # plot the route lines edge_nodes = list(zip(route[:-1], route[1:])) lines = [] for u, v in edge_nodes: # if there are parallel edges, select the shortest in length data = min([data for data in G.edge[u][v].values()], key=lambda x: x['length']) # if it has a geometry attribute (ie, a list of line segments) if 'geometry' in data and use_geom: # add them to the list of lines to plot xs, ys = data['geometry'].xy lines.append(list(zip(xs, ys))) else: # if it doesn't have a geometry attribute, the edge is a straight line from node to node x1 = G.node[u]['x'] y1 = G.node[u]['y'] x2 = G.node[v]['x'] y2 = G.node[v]['y'] line = [(x1, y1), (x2, y2)] lines.append(line) # add the lines to the axis as a linecollection lc = LineCollection(lines, colors=route_color, linewidths=route_linewidth, alpha=route_alpha, zorder=3) ax.add_collection(lc) # save and show the figure as specified fig, ax = save_and_show(fig, ax, save, show, close, filename, file_format, dpi, axis_off) return fig, ax
def show_rag(labels, rag, image, border_color='black', edge_width=1.5, edge_cmap='magma', img_cmap='bone', in_place=True, ax=None): """Show a Region Adjacency Graph on an image. Given a labelled image and its corresponding RAG, show the nodes and edges of the RAG on the image with the specified colors. Edges are displayed between the centroid of the 2 adjacent regions in the image. Parameters ---------- labels : ndarray, shape (M, N) The labelled image. rag : RAG The Region Adjacency Graph. image : ndarray, shape (M, N[, 3]) Input image. If `colormap` is `None`, the image should be in RGB format. border_color : color spec, optional Color with which the borders between regions are drawn. edge_width : float, optional The thickness with which the RAG edges are drawn. edge_cmap : :py:class:`matplotlib.colors.Colormap`, optional Any matplotlib colormap with which the edges are drawn. img_cmap : :py:class:`matplotlib.colors.Colormap`, optional Any matplotlib colormap with which the image is draw. If set to `None` the image is drawn as it is. in_place : bool, optional If set, the RAG is modified in place. For each node `n` the function will set a new attribute ``rag.node[n]['centroid']``. ax : :py:class:`matplotlib.axes.Axes`, optional The axes to draw on. If not specified, new axes are created and drawn on. Returns ------- lc : :py:class:`matplotlib.collections.LineCollection` A colection of lines that represent the edges of the graph. It can be passed to the :meth:`matplotlib.figure.Figure.colorbar` function. Examples -------- >>> from skimage import data, segmentation >>> from skimage.future import graph >>> import matplotlib.pyplot as plt >>> >>> img = data.coffee() >>> labels = segmentation.slic(img) >>> g = graph.rag_mean_color(img, labels) >>> lc = graph.show_rag(labels, g, img) >>> cbar = plt.colorbar(lc) """ from matplotlib import colors, cm from matplotlib import pyplot as plt from matplotlib.collections import LineCollection if not in_place: rag = rag.copy() if ax is None: fig, ax = plt.subplots() out = util.img_as_float(image, force_copy=True) if img_cmap is None: if image.ndim < 3 or image.shape[2] not in [3, 4]: msg = 'If colormap is `None`, an RGB or RGBA image should be given' raise ValueError(msg) # Ignore the alpha channel out = image[:, :, :3] else: img_cmap = cm.get_cmap(img_cmap) out = color.rgb2gray(image) # Ignore the alpha channel out = img_cmap(out)[:, :, :3] edge_cmap = cm.get_cmap(edge_cmap) # Handling the case where one node has multiple labels # offset is 1 so that regionprops does not ignore 0 offset = 1 map_array = np.arange(labels.max() + 1) for n, d in rag.nodes(data=True): for label in d['labels']: map_array[label] = offset offset += 1 rag_labels = map_array[labels] regions = measure.regionprops(rag_labels) for (n, data), region in zip(rag.nodes(data=True), regions): data['centroid'] = tuple(map(int, region['centroid'])) cc = colors.ColorConverter() if border_color is not None: border_color = cc.to_rgb(border_color) out = segmentation.mark_boundaries(out, rag_labels, color=border_color) ax.imshow(out) # Defining the end points of the edges # The tuple[::-1] syntax reverses a tuple as matplotlib uses (x,y) # convention while skimage uses (row, column) lines = [[rag.node[n1]['centroid'][::-1], rag.node[n2]['centroid'][::-1]] for (n1, n2) in rag.edges()] lc = LineCollection(lines, linewidths=edge_width, cmap=edge_cmap) edge_weights = [d['weight'] for x, y, d in rag.edges(data=True)] lc.set_array(np.array(edge_weights)) ax.add_collection(lc) return lc
def plot_graph(G, bbox=None, fig_height=6, fig_width=None, margin=0.02, axis_off=True, bgcolor='w', show=True, save=False, close=True, file_format='png', filename='temp', dpi=300, annotate=False, node_color='#66ccff', node_size=15, node_alpha=1, node_edgecolor='none', node_zorder=1, edge_color='#999999', edge_linewidth=1, edge_alpha=1, use_geom=True): """ Plot a networkx spatial graph. Parameters ---------- G : networkx multidigraph bbox : tuple bounding box as north,south,east,west - if None will calculate from spatial extents of data fig_height : int matplotlib figure height in inches fig_width : int matplotlib figure width in inches margin : float relative margin around the figure axis_off : bool if True turn off the matplotlib axis bgcolor : string the background color of the figure and axis show : bool if True, show the figure save : bool if True, save the figure as an image file to disk close : bool close the figure (only if show equals False) to prevent display file_format : string the format of the file to save (e.g., 'jpg', 'png', 'svg') filename : string the name of the file if saving dpi : int the resolution of the image file if saving annotate : bool if True, annotate the nodes in the figure node_color : string the color of the nodes node_size : int the size of the nodes node_alpha : float the opacity of the nodes node_edgecolor : string the color of the node's marker's border node_zorder : int zorder to plot nodes, edges are always 2, so make node_zorder 1 to plot nodes beneath them or 3 to plot nodes atop them edge_color : string the color of the edges' lines edge_linewidth : float the width of the edges' lines edge_alpha : float the opacity of the edges' lines use_geom : bool if True, use the spatial geometry attribute of the edges to draw geographically accurate edges, rather than just lines straight from node to node Returns ------- fig, ax : tuple """ log('Begin plotting the graph...') node_Xs = [float(node['x']) for node in G.node.values()] node_Ys = [float(node['y']) for node in G.node.values()] # get north, south, east, west values either from bbox parameter or from the spatial extent of the edges' geometries if bbox is None: edges = graph_to_gdfs(G, nodes=False, fill_edge_geometry=True) west, south, east, north = edges.total_bounds else: north, south, east, west = bbox # if caller did not pass in a fig_width, calculate it proportionately from the fig_height and bounding box aspect ratio bbox_aspect_ratio = (north - south) / (east - west) if fig_width is None: fig_width = fig_height / bbox_aspect_ratio # create the figure and axis fig, ax = plt.subplots(figsize=(fig_width, fig_height), facecolor=bgcolor) ax.set_facecolor(bgcolor) # draw the edges as lines from node to node start_time = time.time() lines = [] for u, v, key, data in G.edges(keys=True, data=True): if 'geometry' in data and use_geom: # if it has a geometry attribute (a list of line segments), add them to the list of lines to plot xs, ys = data['geometry'].xy lines.append(list(zip(xs, ys))) else: # if it doesn't have a geometry attribute, the edge is a straight line from node to node x1 = G.node[u]['x'] y1 = G.node[u]['y'] x2 = G.node[v]['x'] y2 = G.node[v]['y'] line = [(x1, y1), (x2, y2)] lines.append(line) # add the lines to the axis as a linecollection lc = LineCollection(lines, colors=edge_color, linewidths=edge_linewidth, alpha=edge_alpha, zorder=2) ax.add_collection(lc) log('Drew the graph edges in {:,.2f} seconds'.format(time.time() - start_time)) # scatter plot the nodes ax.scatter(node_Xs, node_Ys, s=node_size, c=node_color, alpha=node_alpha, edgecolor=node_edgecolor, zorder=node_zorder) # set the extent of the figure margin_ns = (north - south) * margin margin_ew = (east - west) * margin ax.set_ylim((south - margin_ns, north + margin_ns)) ax.set_xlim((west - margin_ew, east + margin_ew)) # configure axis appearance ax.get_xaxis().get_major_formatter().set_useOffset(False) ax.get_yaxis().get_major_formatter().set_useOffset(False) # if axis_off, turn off the axis display set the margins to zero and point the ticks in so there's no space around the plot if axis_off: ax.axis('off') ax.margins(0) ax.tick_params(which='both', direction='in') fig.canvas.draw() # annotate the axis with node IDs if annotate=True if annotate: for node, data in G.nodes(data=True): ax.annotate(node, xy=(data['x'], data['y'])) # save and show the figure as specified fig, ax = save_and_show(fig, ax, save, show, close, filename, file_format, dpi, axis_off) return fig, ax
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. Parameters ---------- G : graph A networkx graph pos : dictionary A dictionary with nodes as keys and positions as values. If not specified a spring layout positioning will be computed. See networkx.layout for functions that compute node positions. edgelist : collection of edge tuples Draw only specified edges(default=G.edges()) width : float 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. 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.lanl.gov/gallery.html See Also -------- draw() draw_networkx() draw_networkx_nodes() draw_networkx_labels() draw_networkx_edge_labels() """ try: import matplotlib import matplotlib.pylab as pylab 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 = 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 = 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 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) # need 0.87.7 or greater for edge colormaps mpl_version = matplotlib.__version__ if mpl_version.endswith('.svn'): mpl_version = matplotlib.__version__[0:-4] elif mpl_version.endswith('svn'): mpl_version = matplotlib.__version__[0:-3] elif mpl_version.endswith('pre'): mpl_version = matplotlib.__version__[0:-3] if list(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(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() # pylab.axes(ax) 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.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 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
def plot_band_weight(kslist, ekslist, wkslist=None, efermi=0, yrange=None, output=None, style='alpha', color='blue', axis=None, width=2, xticks=None, title=None): """ kslist: [iband, kx] ekslist: [iband, energy] wkslist: [iband, weight] """ if axis is None: fig, a = plt.subplots() plt.tight_layout(pad=2.19) plt.axis('tight') plt.gcf().subplots_adjust(left=0.17) else: a = axis if title is not None: a.set_title(title) xmax = max(kslist[0]) if yrange is None: yrange = (np.array(ekslist).flatten().min() - 66, np.array(ekslist).flatten().max() + 66) if wkslist is not None: for i in range(len(kslist)): # number of bands x = kslist[i] # bandx y = ekslist[i] # band energy lwidths = np.array(wkslist[i]) * width #lwidths=np.ones(len(x)) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) if style == 'width': lc = LineCollection(segments, linewidths=lwidths, colors=color) elif style == 'alpha': lc = LineCollection(segments, linewidths=[2] * len(x), colors=[ colorConverter.to_rgba( color, alpha=np.abs(lwidth / (width + 0.001))) for lwidth in lwidths ]) a.add_collection(lc) plt.ylabel('Frequency (cm$^{-1}$)') if axis is None: for ks, eks in zip(kslist, ekslist): plt.plot(ks, eks, color='gray', linewidth=0.001) a.set_xlim(0, xmax) a.set_ylim(yrange) if xticks is not None: plt.xticks(xticks[1], xticks[0]) for x in xticks[1]: plt.axvline(x, color='gray', linewidth=0.5) if efermi is not None: plt.axhline(linestyle='--', color='black') return a
def update_line(num, print_loss, data, axes, epochsInds, test_error, test_data, epochs_bins, loss_train_data, loss_test_data, colors, font_size=18, axis_font=16, x_lim=[0, 12.2], y_lim=[0, 1.08], x_ticks=[], y_ticks=[]): """Update the figure of the infomration plane for the movie""" #Print the line between the points cmap = ListedColormap(LAYERS_COLORS) segs = [] for i in range(0, data.shape[1]): x = data[0, i, num, :] y = data[1, i, num, :] points = np.array([x, y]).T.reshape(-1, 1, 2) segs.append(np.concatenate([points[:-1], points[1:]], axis=1)) segs = np.array(segs).reshape(-1, 2, 2) axes[0].clear() if len(axes) > 1: axes[1].clear() lc = LineCollection(segs, cmap=cmap, linestyles='solid', linewidths=0.3, alpha=0.6) lc.set_array(np.arange(0, 5)) #Print the points for layer_num in range(data.shape[3]): axes[0].scatter(data[0, :, num, layer_num], data[1, :, num, layer_num], color=colors[layer_num], s=35, edgecolors='black', alpha=0.85) axes[1].plot(epochsInds[:num], 1 - np.mean(test_error[:, :num], axis=0), color='r') title_str = 'Information Plane - Epoch number - ' + str(epochsInds[num]) utils.adjustAxes(axes[0], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True, x_label='$I(X;T)$', y_label='$I(T;Y)$') title_str = 'Precision as function of the epochs' utils.adjustAxes(axes[1], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True, x_label='# Epochs', y_label='Precision')
n = 100 x = np.arange(n) rs = check_random_state(0) y = rs.randint(-50, 50, size=(n,)) + 50. * np.log1p(np.arange(n)) # ############################################################################# # Fit IsotonicRegression and LinearRegression models ir = IsotonicRegression() y_ = ir.fit_transform(x, y) lr = LinearRegression() lr.fit(x[:, np.newaxis], y) # x needs to be 2d for LinearRegression # ############################################################################# # Plot result segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)] lc = LineCollection(segments, zorder=0) lc.set_array(np.ones(len(y))) lc.set_linewidths(np.full(n, 0.5)) fig = plt.figure() plt.plot(x, y, 'r.', markersize=12) plt.plot(x, y_, 'b.-', markersize=12) plt.plot(x, lr.predict(x[:, np.newaxis]), 'b-') #plt.gca().add_collection(lc) plt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right') plt.title('Isotonic regression') plt.show()
def drawStreamLine_(ax, mesh, c, data, dataMesh=None, linewidth=1.0, dropTol=0.0, **kwargs): """Draw a single streamline. Draw a single streamline into a given mesh for given data stating at the center of cell c. The Streamline will be enlarged until she reached a cell that already contains a streamline. TODO linewidth and color depends on absolute velocity or background color saturation Parameters ---------- ax : matplotlib.ax ax to draw into mesh : :gimliapi:`GIMLI::Mesh` 2d Mesh to draw the streamline c : :gimliapi:`GIMLI::Cell` start cell data : iterable float | [float, float] If data is an array (per cell or node) gradients are calculated otherwise the data will be interpreted as vector field. dataMesh : :gimliapi:`GIMLI::Mesh` [None] Optional mesh for the data. If you want high resolution data to plot on coarse draw mesh. linewidth : float [1.0] Streamline linewidth dropTol : float [0.0] Don't draw stream lines with velocity lower than drop tolerance. """ x, y, v = streamline(mesh, data, startCoord=c.center(), dLengthSteps=5, dataMesh=dataMesh, maxSteps=10000, verbose=False, coords=[0, 1]) if 'color' not in kwargs: kwargs['color'] = 'black' lines = None if len(x) > 2: points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lwidths = pg.RVector(len(v), linewidth) lwidths[pg.find(pg.RVector(v) < dropTol)] = 0.0 lines = LineCollection(segments, linewidths=lwidths, **kwargs) ax.add_collection(lines) # probably the limits are wrong without plot call # lines = ax.plot(x, y, **kwargs) # updateAxes_(ax, lines) # ax.plot(x, y, '.-', color='black', **kwargs) if len(x) > 3: xmid = int(len(x) / 2) ymid = int(len(y) / 2) dx = x[xmid + 1] - x[xmid] dy = y[ymid + 1] - y[ymid] c = mesh.findCell([x[xmid], y[ymid]]) dLength = c.center().dist(c.node(0).pos()) / 4. if v[xmid] > dropTol: ax.arrow(x[xmid], y[ymid], dx, dy, width=dLength / 3., head_starts_at_zero=True, **kwargs) return lines
def Graph_DEM_Distance_Discharge(Discharge_dict, Distance_dict, DEM_dict, River_dict, Startdate, Enddate, Reference_data): import matplotlib.pyplot as plt from matplotlib.collections import LineCollection Dates = pd.date_range(Startdate, Enddate, freq='MS') River_dict_tot = dict() DEM_dict_tot = dict() Discharge_dict_tot = dict() Distance_dict_tot = dict() for timestep in range(0, len(Dates)): River_dict_tot[timestep] = River_dict DEM_dict_tot[timestep] = DEM_dict Discharge_dict_one = dict() for river_part in Discharge_dict.iteritems(): Discharge_dict_one[river_part[0]] = Discharge_dict[river_part[0]][ timestep, 1:] Discharge_dict_tot[timestep] = Discharge_dict_one Distance_dict_tot[timestep] = Distance_dict All_discharge_values = [] for o in range(0, len(Dates)): for p in range(0, len(River_dict_tot[0])): Discharge_data_one = Discharge_dict_tot[o][p] All_discharge_values = np.append(All_discharge_values, Discharge_data_one) for i in range(0, len(Dates)): Max_length_dict = len(River_dict_tot[i][max( River_dict_tot[i], key=lambda x: len(River_dict_tot[i][x]))]) Data_3d = np.ones([len(River_dict_tot[i]), Max_length_dict, 2]) * -9999 Data_z_2d = np.ones([len(River_dict_tot[i]), Max_length_dict]) * np.nan for River_number in range(0, len(River_dict_tot[i])): xData = Distance_dict_tot[i][River_number] / 1000 yData = DEM_dict_tot[i][River_number] zData = Discharge_dict_tot[i][River_number] Data_3d[River_number, 1:len(Distance_dict_tot[i][River_number]), 0] = xData[1:] Data_3d[River_number, 1:len(Distance_dict_tot[i][River_number]), 1] = yData[1:] Data_z_2d[River_number, 1:len(Distance_dict_tot[i][River_number])] = zData[:] # Mask some values to test masked array support: segs = np.ma.masked_where((Data_3d < -10), Data_3d) LineData = np.nanmin(Data_z_2d, axis=1) LineWidth = ( (LineData - np.min(All_discharge_values)) / (np.max(All_discharge_values) - np.min(All_discharge_values)) * (9) + 1) plt.figure(i) ax = plt.axes() minx = np.min(segs[:, :, 0]) maxx = np.max(segs[:, :, 0]) miny = np.min(segs[:, :, 1]) maxy = np.max(segs[:, :, 1]) ax.set_xlim(minx - (maxx - minx) / 10, maxx + (maxx - minx) / 10) ax.set_ylim(miny - (maxy - miny) / 10, maxy + (maxy - miny) / 10) line_segments = LineCollection(segs, LineWidth, linestyle='solid', cmap=plt.get_cmap('Spectral'), norm=plt.Normalize( np.min(All_discharge_values), np.max(All_discharge_values))) ax.add_collection(line_segments) ax.set_title('Timestep = %d' % i) line_segments.set_array(LineData) axcb = plt.colorbar(line_segments) plt.ylabel('Altitude in m') plt.xlabel('Upstream distance in km') plt.show()
def get_linewidth(self): v = LineCollection.get_linewidth(self)[0] return v
def generate_map(countries): # Initialize plotting area, set the boundaries and add a sub-plot on which # we are going to plot the map fig = plt.figure(figsize=(11.7, 8.3)) plt.subplots_adjust(left=0.05, right=0.95, top=0.90, bottom=0.05, wspace=0.15, hspace=0.05) ax = plt.subplot(111) # Initialize the basemap, set the resolution, projection type and the viewport bm = Basemap(resolution='i', projection='robin', lon_0=0) # Tell basemap how to draw the countries (built-in shapes), draw parallels and meridians # and color in the water bm.drawcountries(linewidth=0.5) bm.drawparallels(np.arange(-90., 120., 30.)) bm.drawmeridians(np.arange(0., 360., 60.)) bm.drawmapboundary(fill_color='aqua') # Open the countries shapefile and read the shape and attribute information r = shapefile.Reader('world_borders/TM_WORLD_BORDERS-0.3.shp') shapes = r.shapes() records = r.records() # Iterate through all records (attributes) and shapes (countries) for record, shape in zip(records, shapes): # Extract longitude and latitude values into two separate arrays then # project the coordinates onto the map projection and transpose the array, so that # the data variable contains (lon, lat) pairs in the list. # Basically, the following two lines convert the initial data # [ [lon_original_1, lat_original_1], [lon_original_2, lat_original_2], ... ] # into projected data # [ [lon_projected_1, lat_projected_1, [lon_projected_2, lat_projected_2], ... ] # # Note: Calling baseshape object with the coordinates as an argument returns the # projection of those coordinates lon_array, lat_array = zip(*shape.points) data = np.array(bm(lon_array, lat_array)).T # Next we will create groups of points by splitting the shape.points according to # the indices provided in shape.parts if len(shape.parts) == 1: # If the shape has only one part, then we have only one group. Easy. groups = [ data, ] else: # If we have more than one part ... groups = [] for i in range(1, len(shape.parts)): # We iterate through all parts, and find their start and end positions index_start = shape.parts[i - 1] index_end = shape.parts[i] # Then we copy all point between two indices into their own group and append # that group to the list groups.append(data[index_start:index_end]) # Last group starts at the last index and finishes at the end of the points list groups.append(data[index_end:]) # Create a collection of lines provided the group of points. Each group represents a line. lines = LineCollection(groups, antialiaseds=(1, )) # We then select a color from a color map (in this instance all Reds) # The intensity of the selected color is proportional to the number of requests. # Color map accepts values from 0 to 1, therefore we need to normalize our request count # figures, so that the max number of requests is 1, and the rest is proportionally spread # in the range from 0 to 1. max_value = float(max(countries.values())) country_name = record[4] requests = countries.get(country_name, 0) requests_norm = requests / max_value lines.set_facecolors(cm.Reds(requests_norm)) # Finally we set the border color to be black and add the shape to the sub-plot lines.set_edgecolors('k') lines.set_linewidth(0.1) ax.add_collection(lines) # Once we are ready, we save the resulting picture plt.savefig('requests_per_country.png', dpi=300)
def plot_day_summary2_ohlc( ax, opens, highs, lows, closes, ticksize=4, colorup='k', colordown='r', ): """Represent the time, open, high, low, close as a vertical line ranging from low to high. The left tick is the open and the right tick is the close. *opens*, *highs*, *lows* and *closes* must have the same length. NOTE: this code assumes if any value open, high, low, close is missing (*-1*) they all are missing Parameters ---------- ax : `Axes` an Axes instance to plot to opens : sequence sequence of opening values highs : sequence sequence of high values lows : sequence sequence of low values closes : sequence sequence of closing values ticksize : int size of open and close ticks in points colorup : color the color of the lines where close >= open colordown : color the color of the lines where close < open Returns ------- ret : list a list of lines added to the axes """ _check_input(opens, highs, lows, closes) rangeSegments = [((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1] # the ticks will be from ticksize to 0 in points at the origin and # we'll translate these to the i, close location openSegments = [((-ticksize, 0), (0, 0))] # the ticks will be from 0 to ticksize in points at the origin and # we'll translate these to the i, close location closeSegments = [((0, 0), (ticksize, 0))] offsetsOpen = [(i, open) for i, open in zip(xrange(len(opens)), opens) if open != -1] offsetsClose = [(i, close) for i, close in zip(xrange(len(closes)), closes) if close != -1] scale = ax.figure.dpi * (1.0 / 72.0) tickTransform = Affine2D().scale(scale, 0.0) colorup = mcolors.to_rgba(colorup) colordown = mcolors.to_rgba(colordown) colord = {True: colorup, False: colordown} colors = [ colord[open < close] for open, close in zip(opens, closes) if open != -1 and close != -1 ] useAA = 0, # use tuple here lw = 1, # and here rangeCollection = LineCollection( rangeSegments, colors=colors, linewidths=lw, antialiaseds=useAA, ) openCollection = LineCollection( openSegments, colors=colors, antialiaseds=useAA, linewidths=lw, offsets=offsetsOpen, transOffset=ax.transData, ) openCollection.set_transform(tickTransform) closeCollection = LineCollection( closeSegments, colors=colors, antialiaseds=useAA, linewidths=lw, offsets=offsetsClose, transOffset=ax.transData, ) closeCollection.set_transform(tickTransform) minpy, maxx = (0, len(rangeSegments)) miny = min([low for low in lows if low != -1]) maxy = max([high for high in highs if high != -1]) corners = (minpy, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last ax.add_collection(rangeCollection) ax.add_collection(openCollection) ax.add_collection(closeCollection) return rangeCollection, openCollection, closeCollection
def add_gradient_line(ax: Axes, x: np.ndarray, y: np.ndarray, v: np.ndarray, cmap: str = 'gist_rainbow', linewidth: float = 2, vmin: Optional[float] = None, vmax: Optional[float] = None): """ Add a set of lines with a colormap based on the coordinates :param Axes ax: The axis to add a line to :param ndarray x: The n point x coordinates :param ndarray y: The n point y coordinates :param ndarray v: The n point color matrix to plot :param str cmap: The matplotlib colormap to use :param int linewidth: The line width to plot :param float vmin: The minimum value for the color map :param float vmax: The maximum value for the color map """ coords = np.stack([x, y], axis=1) v = np.squeeze(v) assert coords.ndim == 2 assert coords.shape[1] == 2 assert coords.shape[0] > 1 if v.ndim != 1: raise ValueError(f'Expected 1D colors but got shape {v.shape}') if v.shape[0] != coords.shape[0]: raise ValueError( f'Got coords with shape {coords.shape} but colors with shape {v.shape}' ) if vmin is None: vmin = np.min(v) if vmax is None: vmax = np.max(v) # Convert from vertex-centric to edge-centric coords = coords[:, np.newaxis, :] stack_coords = np.stack([coords[:-1, 0, :], coords[1:, 0, :]], axis=1) assert stack_coords.shape == (coords.shape[0] - 1, 2, 2) # Convert each segment to a color on the gradient cm = plt.get_cmap(cmap) cnorm = mplcolors.Normalize(vmin=vmin, vmax=vmax) scalar_map = mplcm.ScalarMappable(norm=cnorm, cmap=cm) index = (v[:-1] + v[1:]) / 2 coll = LineCollection(stack_coords, colors=scalar_map.to_rgba(index), linewidth=linewidth) ax.add_collection(coll) return ax
def candlestick2_ohlc( ax, opens, highs, lows, closes, width=4, colorup='k', colordown='r', alpha=0.75, ): """Represent the open, close as a bar line and high low range as a vertical line. NOTE: this code assumes if any value open, low, high, close is missing they all are missing Parameters ---------- ax : `Axes` an Axes instance to plot to opens : sequence sequence of opening values highs : sequence sequence of high values lows : sequence sequence of low values closes : sequence sequence of closing values ticksize : int size of open and close ticks in points colorup : color the color of the lines where close >= open colordown : color the color of the lines where close < open alpha : float bar transparency Returns ------- ret : tuple (lineCollection, barCollection) """ _check_input(opens, highs, lows, closes) delta = width / 2. barVerts = [((i - delta, open), (i - delta, close), (i + delta, close), (i + delta, open)) for i, open, close in zip(xrange(len(opens)), opens, closes) if open != -1 and close != -1] rangeSegments = [((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1] colorup = mcolors.to_rgba(colorup, alpha) colordown = mcolors.to_rgba(colordown, alpha) colord = {True: colorup, False: colordown} colors = [ colord[open < close] for open, close in zip(opens, closes) if open != -1 and close != -1 ] useAA = 0, # use tuple here lw = 0.5, # and here rangeCollection = LineCollection( rangeSegments, colors=((0, 0, 0, 1), ), linewidths=lw, antialiaseds=useAA, ) barCollection = PolyCollection( barVerts, facecolors=colors, edgecolors=((0, 0, 0, 1), ), antialiaseds=useAA, linewidths=lw, ) minx, maxx = 0, len(rangeSegments) miny = min([low for low in lows if low != -1]) maxy = max([high for high in highs if high != -1]) corners = (minx, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last ax.add_collection(rangeCollection) ax.add_collection(barCollection) return rangeCollection, barCollection
skip_footer=num_lines - (nsamples + 3)) f.close() xs = samples[:, 2] ys = samples[:, 1] ax.plot(xs, ys, 'ro', markersize=10) ax.plot(xs[0], ys[0], 'bo', markersize=20) xpairs = [] ypairs = [] data = np.genfromtxt("list_segments.txt") for I in range(len(data[:, 1])): xends = [data[I, 0], data[I, 2]] yends = [data[I, 1], data[I, 3]] xpairs.append(xends) ypairs.append(yends) segs = list(zip(zip(data[:, 1], data[:, 0]), zip(data[:, 3], data[:, 2]))) line_segments = LineCollection(segs, linewidths=1) ax.add_collection(line_segments) if (output == "file"): string = filename string2 = string.split(sep=".")[0] plt.savefig(string2 + ".png") if (output == "screen"): plt.show()