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 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 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 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 test_characteristic(self): m, n = 100, 100 # Compute characteristic. c = vel.characteristic(m, n, c0, v0, tau0, tau1, 0.6) # Compute velocity field. v = vel.velocity(m, n, c0, v0, tau0, tau1) # Convert to matrix. v = dh.funvec2img(v.vector().get_local(), m, n) # Plot velocity. fig = plt.figure() plt.imshow(v, cmap=cm.coolwarm) # Plot characteristic. y = np.linspace(0, m, m + 1).reshape(m + 1, 1) points = np.array([n * c, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments[:-1]) lc.set_linewidth(2) plt.gca().add_collection(lc) plt.show() plt.close(fig)
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 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 hilbert_spectrum(time, frec, amp, config): x = time y = frec z = amp n = len(x) cmap = plt.get_cmap(config['color_map']) # norm = BoundaryNorm(np.linspace(z.min(), z.max(), 1000), cmap.N) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) norm = Normalize(vmin=0, vmax=1300) # norm = None lc = LineCollection(segments, cmap=cmap, norm=norm) lc.set_array(z) lc.set_linewidth(config['linewidth']) fig1, ax1 = plt.subplots() plt.gca().add_collection(lc) plt.xlim(x.min(), x.max()) plt.ylim(y.min(), y.max()) line = ax1.add_collection(lc) cbar = fig1.colorbar(line, ax=ax1, format='%1.0f') cbar.set_label(config['zlabel'], size=13) cbar.ax.tick_params(labelsize=12) cbar.set_ticks(list(np.arange(np.min(z), np.max(z), config['step_cbar']))) ax1.set_xlabel(config['xlabel'], fontsize=13) ax1.set_ylabel(config['ylabel'], fontsize=13) # ax1.set_ylim(config['ylim'][0], config['ylim'][1]) ax1.tick_params(axis='both', labelsize=12) return fig1, ax1
def plot_center(data_values, left_idx, right_idx, k): x_l = [] y_l = [] for i in range(left_idx, right_idx): x_c, y_c = center_slice(data_values[:, :, i], k) x_l.append(x_c) y_l.append(y_c) x = np.array(x_l) y = np.array(y_l) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) fig, ax = plt.subplots() # Create a continuous norm to map from data points to colors norm = plt.Normalize(0, len(x)) lc = LineCollection(segments, cmap='cool', norm=plt.Normalize(0, 16)) # Set the values used for colormapping lc.set_array(np.linspace(0, 20, len(x))) lc.set_linewidth(3) line = ax.add_collection(lc) fig.colorbar(line, ax=ax) ax.plot(x, y, c='white', alpha=0.001) ax.set_xlim(0, 15) ax.set_ylim(0, 15) ax.set_title(f'Brightness movement, coeff = {k}') plt.grid(True) # ax.autoscale() plt.show()
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_transitions_w_strengths(Ex,Ey,Strain_start,Strain_end,pts,B_field=[0.,0.,0.],m0=True,m1=True,p1=True,ax=None,log_scale =False): Strain = Ex-Ey ExZero = (Ex+Ey)/2 EyZero = (Ex+Ey)/2 Strainarray = np.linspace(Strain_start,Strain_end,pts) trans_keys = [] if m0: trans_keys.append('ms0') if m1: trans_keys.append('msm1') if p1: trans_keys.append('msp1') transitions = {} for key in trans_keys: transitions[key] = {} transitions[key]['strength'] = np.empty([6,pts]) transitions[key]['freq'] = np.empty([6,pts]) for ii in range(pts): slice_list = nvlevels.get_optical_transition_strengths_ExEy(ExZero+Strainarray[ii]/2,EyZero-Strainarray[ii]/2,B_field=B_field, show_ms0_transitions=m0,show_m1_transitions=m1,show_p1_transitions=p1) for key in trans_keys: transitions[key]['strength'][:,ii] = slice_list[key]['strength'] transitions[key]['freq'][:,ii] = slice_list[key]['freq'] color_map_key = {'msp1' : 'Blues', 'msm1': 'Greens', 'ms0' : 'Reds'} if ax == None: fig = plt.figure(figsize = (8,6)) ax = plt.subplot() for key in transitions: for ii in range(np.shape(transitions[key]['freq'])[0]): points = np.array([Strainarray, transitions[key]['freq'][ii,:]]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) if not log_scale: lc = LineCollection(segments, cmap=plt.get_cmap(color_map_key[key]),norm=plt.Normalize(vmin=0,vmax=1)) lc.set_array(transitions[key]['strength'][ii,:]) else: lc = LineCollection(segments, cmap=plt.get_cmap(color_map_key[key]),norm=plt.Normalize(vmin=-3,vmax=0)) transitions[key]['strength'][ii,(transitions[key]['strength'][ii,:] == 0)] = 1e-5 lc.set_array(np.log10(transitions[key]['strength'][ii,:])) lc.set_linewidth(1) ax.add_collection(lc) plt.ylabel('Frequency (GHz)') plt.xlabel('Strain splitting (GHz)') ax.autoscale_view(True,True,True) plt.show() plt.close("all")
def display_conv_activations(model,sig): if len(sig.shape)==2: sig = sig.reshape(1,sig.shape[0],sig.shape[1]) #get activations activations = keract.get_activations(model, sig) #get convolutional layers keys conv_keys = [key for key in activations.keys() if 'conv' in key] #prepare for plotting t = np.linspace(0, len(sig[0]),len(sig[0])) signal = sig[0].reshape(-1,) points = np.array([t, signal]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) #create fig and axs fig = plt.figure(figsize=(18,5)) if len(conv_keys)>10: print('Warning: only the 10 last layers will be displayed') for i in range(1,min([11,len(conv_keys)])): ax = fig.add_subplot(2,5,i) key = conv_keys[-i] act = np.mean(activations[key][0],axis=1) # Create a continuous norm to map from data points to colors norm = plt.Normalize(act.min(), act.max()) lc = LineCollection(segments, cmap='bwr', norm=norm) # Set the values used for colormapping lc.set_array(act) lc.set_linewidth(2) line = ax.add_collection(lc) fig.colorbar(line, ax=ax) ax.set_xlim(t.min(), t.max()) ax.set_title(key) plt.tight_layout()
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 animate(i): global anim_running if not anim_running: return ax, ax.clear() s_t.set_val(t[i]) anim_running = True # plot only tmin to t[i] when t < tbuf wpts = w[0:i] Ypts = Y[0:i] tpts = t[0:i] if i >= tbuff: # plot from t[i-tbuff] to t = t[i] wpts = w[i - tbuff:i] Ypts = Y[i - tbuff:i] tpts = t[i - tbuff:i] points = np.array([wpts, Ypts]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=hot2cold) lc.set_array(tpts) lc.set_linewidth(3) ax.add_collection(lc) ax.scatter(wpts, Ypts, s=3, c='r') ax.set_title("Goodwin model: wage and output trajectory") ax.set_xlabel('wage share, $w$') ax.set_ylabel('Output, $Y$') ax.set_xlim(0, wmax) ax.set_ylim(0, Ymax) return ax,
def display_conv_activations_transplant(model,sig,cols): """ for transplant with 10 channels """ #get activations sig = sig.reshape(1,sig.shape[0],sig.shape[1]) activations = keract.get_activations(model, sig) conv_keys = [key for key in activations.keys() if 'conv' in key] #prepare for plotting t = np.linspace(0, len(sig[0]),len(sig[0])) #signal = sig[0].reshape(-1,) #create fig and axs fig = plt.figure(figsize=(14,5)) key = conv_keys[-1] #last convolutional layer act = np.mean(activations[key][0],axis=1) # Create a continuous norm to map from data points to colors norm = plt.Normalize(act.min(), act.max()) for i in range(1,11): signal = sig[0][:,i-1] points = np.array([t, signal]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) ax = fig.add_subplot(2,5,i) lc = LineCollection(segments, cmap='bwr', norm=norm) # Set the values used for colormapping lc.set_array(act) lc.set_linewidth(2) line = ax.add_collection(lc) fig.colorbar(line, ax=ax) ax.set_xlim(t.min(), t.max()) ax.set_ylim(signal.min(),signal.max()) ax.set_title(cols[i-1],fontsize=13) plt.tight_layout()
def multicolored_line(graph, x, y, norm_color_value, ax=None, alpha=1., cmap='cool', lw=2): if ax is None: fig, ax = graph.figure() else: fig = None points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) # Create a continuous norm to map from data points to colors norm = plt.Normalize(norm_color_value.min(), norm_color_value.max()) lc = LineCollection(segments, cmap=cmap, norm=norm) # Set the values used for colormapping lc.set_array(norm_color_value) lc.set_linewidth(lw) line = ax.add_collection(lc) return fig, ax, line
def plot_prediction(session, model, title, data, x, y): global p preds = [] for i in range(len(data)): p = session.run(model.f, { model.batch_size: 1, model.x: [data[:i + 1]] })[0] preds.append(np.argmax(p)) x = x[1:] y = y[1:] points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) fig, ax = plt.subplots() cmap = ListedColormap(['r', 'y', 'g']) norm = BoundaryNorm([(len(p) - 1) * i / len(p) for i in range(len(p) + 1)], cmap.N) lc = LineCollection(segments, cmap=cmap, norm=norm) lc.set_array(np.array(preds)) lc.set_linewidth(2) line = ax.add_collection(lc) fig.colorbar(line, ax=ax) ax.set_xlim(x.min(), x.max()) ax.set_ylim(y.min(), y.max()) plt.title(title) plt.xlabel("Day") plt.ylabel("Price") plt.show()
def plot_indiv(points, ax, title, grid_size, tt, prey = False): ticks = np.arange(grid_size) norm = plt.Normalize(tt.min(), tt.max()) if not (points == points[0]).all(): points = points.reshape(-1, 1 , 2) # x is vertical points = np.flip(points, axis = 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) if not prey: lc = LineCollection(segments, cmap = 'winter' ,norm=norm) else: lc = LineCollection(segments, cmap = 'autumn' ,norm=norm) lc.set_array(tt) lc.set_linewidth(10) line = ax.add_collection(lc) plt.colorbar(line, ax=ax) else: if not prey: ax.plot(points[0,1], points[0,0], 's', color = 'b', markersize = 10) else: ax.plot(points[0,1], points[0,0], 's', color = 'r', markersize = 10) ax.set_xlim(-1, grid_size) ax.set_ylim(grid_size, -1) ax.set_xticks(ticks) ax.set_yticks(ticks) ax.grid() ax.set_title(title)
def plot_saliency_median(beispiel, grads): from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm x = np.arange(0, 600) y = np.squeeze(beispiel[1:, :], 1) dydx = grads # 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 (for x and y) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) fig, axs = plt.subplots(figsize=(14, 7)) # Create a continuous norm to map from data points to colors norm = plt.Normalize(dydx.min(), dydx.max()) lc = LineCollection(segments, cmap='viridis', norm=norm) # Set the values used for colormapping lc.set_array(dydx) lc.set_linewidth(3) line = axs.add_collection(lc) fig.colorbar(line, ax=axs) axs.set_xlim(x.min(), x.max()) axs.set_ylim(beispiel[1:, :].min() - 100, beispiel[1:, :].max() + 100) plt.show()
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 update(val): global scat Yeari = int(S_Year.val) - 1880 ax.cla() r = NP[M * Yeari:M * (Yeari + 1)] points = PL.BuildPolyLine(r) segments = np.concatenate([points[:-1], points[1:]], axis=1) # for same reason, we have faster update time if we create new lc # instead of set new segments # lc.set_segments(segments) #if you remove the comment add comments at the two next commands lc = LineCollection(segments, cmap=plt.get_cmap('coolwarm'), norm=plt.Normalize(np.min(NP), np.max(NP))) lc.set_linewidth(3) lc.set_array(PL.R) # this is necessary ax.scatter(PL.Qthetta, r, s=50, c=r, cmap=plt.cm.coolwarm, vmin=ticks[0], vmax=ticks[-1]) ax.add_collection(lc) ax.set_rticks(ticks) ax.set_yticklabels(tick_label) ax.set_rmax(np.max(NP) + 0.06) ax.set_rlabel_position(-22.5) ax.set_xticks(np.pi / 180. * np.linspace(0, 360, 12, endpoint=False)) ax.set_xticklabels(Months) fig.canvas.draw_idle()
def plot_view(result): # Determine bounding box if no clipping boundary was supplied if not result['bbox']: result['bbox'] = bbox_of_view(result) ax = plt.subplot(111) # plt.box(on=None) m = Basemap(resolution='i', projection='merc', llcrnrlat=result['bbox']['ymin'], urcrnrlat=result['bbox']['ymax'], llcrnrlon=result['bbox']['xmin'], urcrnrlon=result['bbox']['xmax'], lat_ts=(result['bbox']['xmin'] + result['bbox']['xmax']) / 2) m.drawcoastlines() try: for el in result['results']: vectors = get_vectors_from_postgis_map(m, loads(el['geom'])) lines = LineCollection(vectors, antialiaseds=(1, )) lines.set_facecolors('black') lines.set_edgecolors('white') lines.set_linewidth(1) ax.add_collection(lines) m.fillcontinents(color='coral', lake_color='aqua') # If AttributeError assume geom_type 'Point', simply collect all # points and perform scatterplot except AttributeError: xy = m([loads(point['geom']).x for point in result['results']], [loads(point['geom']).y for point in result['results']]) plt.scatter(xy[0], xy[1]) plt.show()
def add_china_map_2basemap(ax,name ="province", facecolor='none', edgecolor='c', lw=2, encoding='utf-8', **kwargs): """ Add china province boundary to basemap instance. :param mp: basemap instance. :param ax: matplotlib axes instance. :param name: map name. :param facecolor: fill color, default is none. :param edgecolor: edge color. :param lw: line width. :param kwargs: keywords passing to Polygon. :return: None. """ # map name names = {'nation': "bou1_4p", 'province': "bou2_4p", 'county': "BOUNT_poly", 'river': "hyd1_4p", 'river_high': "hyd2_4p"} # get shape file and information shpfile = pkg_resources.resource_filename( 'meteva', "resources/maps/" + names[name]) shp1 = readshapefile(shpfile, default_encoding=encoding) lines = LineCollection(shp1,antialiaseds=(1,)) lines.set_color(edgecolor) lines.set_linewidth(lw) lines.set_label('_nolabel_') ax.add_collection(lines)
def plot_pheno_in_dir(path, save_path=None): os.chdir(path) files = os.listdir() # Find generation numbers pheno_generations = [] for fname in files: if fname.startswith("archive") and ".dat" in fname: pheno_generations.append(fname.rstrip(r".dat")[len("archive_"):]) for GEN_NUMBER in pheno_generations: if save_path: os.chdir(path) FILE = f'archive_{GEN_NUMBER}.dat' phenotypes = [] with open(FILE, "r") as f: for line in f.readlines(): data = line.strip().split(" ") # descriptors.append(data[1,2]) phenotypes.append([float(x) for x in data[-2:]]) fig = plt.figure() spec = fig.add_gridspec(1, 1) ax1 = fig.add_subplot(spec[0, 0], aspect='equal', adjustable='box') max_dpf = max(phen[1] for phen in phenotypes) plt.xlim([-max_dpf, max_dpf]) plt.ylim([-max_dpf, max_dpf]) # create lines, origin to point lines = [] colours = [] for (angle, dpf) in phenotypes: x = np.cos(angle) * dpf y = np.sin(angle) * dpf lines.append([(0, 0), (x, y)]) colours.append(dpf) # Create a continuous norm to map from data points to colors norm = plt.Normalize(0, max_dpf) # https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html # add all lines with the colours lc = LineCollection(lines, cmap='PuBuGn', norm=norm) colour_data = ax1.add_collection(lc) fig.colorbar(colour_data, ax=ax1) # Set the values used for colormapping lc.set_array(np.array(colours)) lc.set_linewidth(1) plt.title(f"Solution space in Polar Coordinates - Gen {GEN_NUMBER}") if save_path: os.chdir(save_path) plt.savefig(f"pheno_{GEN_NUMBER}.png") plt.close()
def update(tval): global anim_running anim_running ^= True ax.clear() # update t array index i = closest_index(t, tval, tol=(tmin - tmax) / 1000.) # plot only tmin to t_[i] when i<tbuf wpts = w[0:i] Ypts = Y[0:i] tpts = t[0:1] if i >= tbuff: # plot from t[i-tbuff] to t_cur = t[i] wpts = w[i - tbuff:i] Ypts = Y[i - tbuff:i] tpts = t[i - tbuff:i] points = np.array([wpts, Ypts]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=hot2cold) # , norm=plt.Normalize(0, 1) ) lc.set_array(tpts) lc.set_linewidth(3) ax.add_collection(lc) ax.scatter(wpts, Ypts, s=3, c='r') ax.set_title("Goodwin model: wage and output trajectory") ax.set_xlabel('wage share, $w$') ax.set_ylabel('Output, $Y$') ax.set_xlim(0, wmax) ax.set_ylim(0, Ymax) #plt.draw() fig.canvas.draw_idle()
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
class BatchLineCollection(object): def __init__(self, ax): self._ax = ax self._lc = None @property def artists(self): return [self._lc] def draw(self, x, y, **kwargs): segments = [] for x_i, y_i in zip(x, y): xy_i = np.stack([x_i, y_i], axis=1) xy_i = xy_i.reshape(-1, 1, 2) segments_i = np.hstack([xy_i[:-1], xy_i[1:]]) segments.append(segments_i) segments = np.concatenate(segments, axis=0) if self._lc is None: self._lc = PltLineCollection(segments) self._ax.add_collection(self._lc) else: self._lc.set_segments(segments) if 'color' in kwargs: self._lc.set_color(np.reshape(kwargs['color'], [len(segments), -1])) if 'linewidth' in kwargs: self._lc.set_linewidth(kwargs['linewidth']) self._lc.set_joinstyle('round') self._lc.set_capstyle('round')
def pl(): x = np.linspace(0, 10, 500) y = np.sin(x) dydx = np.cos(0.5 * (x[:-1] + x[1:])) # first derivative # 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 (for x and y) # points[0] = (x[0], y[0] points = np.array([x, y]).T.reshape(-1, 1, 2) # segments[0] = 2x2 matrix. segments[0][0] = points[0]; segments[0][1] = points[1] segments = np.concatenate([points[:-1], points[1:]], axis=1) fig, axs = plt.subplots(1, 1) # Create a continuous norm to map from data points to colors # min(norm) = 0, max(norm) = 1 norm = plt.Normalize(dydx.min(), dydx.max()) # cmap = color map lc = LineCollection(segments, cmap='viridis', norm=norm) # Set the values used for colormapping lc.set_array(dydx) lc.set_linewidth(2) line = axs.add_collection(lc) fig.colorbar(line, ax=axs) axs.set_xlim(x.min(), x.max()) axs.set_ylim(-1.1, 1.1) embed() plt.show()
def draw_shp_polygons(self, shp_filepath, linewidths=0.2, colors='k', antialiaseds=None, linestyles='solid'): """ Draw a shapefile containing polygons """ # Read the shapefile as shapes and records. For each polygon in shapes, draw its boundaries r = shapefile.Reader(shp_filepath) shapes = r.shapes() records = r.records() for record, shape in zip(records, shapes): lons, lats = zip(*shape.points) data = [(x, y) for x, y in zip(*self(lons, lats))] # shape.parts is a list containing the starting index of each part of shape (e.g. a lake inside the shape) on xy_pts. If shape contains only 1 part, a list containing 0 is returned. if len(shape.parts) == 1: segs = [data, ] else: segs = [] for npart in range(1, len(shape.parts)): ix1 = shape.parts[npart-1] ix2 = shape.parts[npart] segs.append(data[ix1:ix2]) segs.append(data[ix2: ]) lines = LineCollection(segs, antialiaseds = [1, ]) lines.set_edgecolors(colors) lines.set_linestyle(linestyles) lines.set_linewidth(linewidths) self.ax.add_collection(lines)
def color_code(x, y, z, fig, ax, cbar=False): # 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 (for x and y) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) # Create a continuous norm to map from data points to colors norm = plt.Normalize(0, 1) lc = LineCollection(segments, cmap='viridis', norm=norm) # Set the values used for colormapping lc.set_array(z) lc.set_linewidth(2) line = ax.add_collection(lc) # if cbar: # cbar = fig.colorbar(line, orientation='horizontal') # cbar.set_ticks([0., 1.]) # cbar.set_ticklabels(['matter', 'photon']) # ax.set_xlim(-6,4) # ax.set_ylim(3.,8.0) return line
def colorline(x, y, cmap=None, cm_range=(0, 0.7), **kwargs): """Colorline plots a trajectory of (x,y) points with a colormap""" # plt.plot(x, y, '-k', zorder=1) # plt.scatter(x, y, s=40, c=plt.cm.RdBu(np.linspace(0,1,40)), zorder=2, edgecolor='k') assert len(cm_range) == 2, "cm_range must have (min, max)" assert len(x) == len(y), "x and y must have the same number of elements!" ax = kwargs.get('ax', plt.gca()) lw = kwargs.get('lw', 2) if cmap is None: cmap = plt.cm.Blues_r t = np.linspace(cm_range[0], cm_range[1], len(x)) 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=plt.Normalize(0, 1), zorder=50) lc.set_array(t) lc.set_linewidth(lw) ax.add_collection(lc) return lc
def plot_line_colored(x, y, t, w=None, color=None, cmap=None): import numpy as np from matplotlib.collections import LineCollection # 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) extra = {} if w is None: extra['linewidths'] = w # Create the line collection object, setting the colormapping parameters. # Have to set the actual values used for colormapping separately. lc = LineCollection(segments, cmap=p.get_cmap(cmap), **extra #norm=p.Normalize(0, 10) ) lc.set_array(t) lc.set_linewidth(w) if color is not None: lc.set_color(color) p.gca().add_collection(lc)
def figure(self, ax, x, y, speed, state): # Rescale x and y to figure x, y = x/4, y/4 # Read image and RGB-> BGR background_path = os.path.join(self.maps_dir, state+".png") background = cv2.imread(background_path) background = background[:, :, ::-1] # Create a line of segments points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) # Create a continuous norm to map from data points to colors norm = plt.Normalize(speed.min(), speed.max()) lc = LineCollection(segments, cmap='winter', norm=norm) # Set the values used for colormapping lc.set_array(speed) lc.set_linewidth(2) ax.add_collection(lc) fig.colorbar(line, ax=ax) ax.imshow(background, alpha=0.3) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.set_title(f"State: {state}, episodes: {self.step}")
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 add_data(globe, axes, color_dict): """Add shapefile polygons to the matplotlib axes""" file_object = shapefile.Reader(filename) shapes = file_object.shapes() records = file_object.records() #iterate over all but the first 20 polygons (they're junk) for record, shape in zip(records[20:],shapes[20:]): #this entry is the colour code description = record[6] lons,lats = zip(*shape.points) #transform the lat/long coords to the right projection data = np.array(globe(lons, lats)).T #shapefile shapes can have disconnected parts, we have #to check if len(shape.parts) == 1: segs = [data,] else: segs = [] for i in range(1,len(shape.parts)): #add all the parts index = shape.parts[i-1] index2 = shape.parts[i] segs.append(data[index:index2]) segs.append(data[index2:]) #Add all the parts we've found as a set of lines lines = LineCollection(segs,antialiaseds=(1,)) lines.set_facecolors(color_dict[description]) lines.set_edgecolors('k') lines.set_linewidth(0.1) #add the collection to the active axes axes.add_collection(lines)
def plotTrajDist(self, trajFallRisk, trajectory, counter, background_filename, traj_png_filenames, traj_pdf_filenames): x = [] y = [] dydx = [] for i in range(len(trajectory)): x.append(trajectory[i][0][1]) y.append(trajectory[i][0][0]) dydx.append(trajFallRisk[i]) # 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 (for x and y) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) fig, ax = plt.subplots() datafile = cbook.get_sample_data(background_filename, asfileobj=False) im = image.imread(datafile) ax.imshow(im, aspect='auto', extent=(0, 10, 0, 10), alpha=0.5, zorder=-1) c = ["navy", [0.27,0.69,0.70], [0.45,0.68,0.82], [0.67,0.85,0.91], [0.99,0.68,0.38], [0.95,0.43,0.26], [0.84,0.19,0.15], "firebrick"] v = [0, 0.15, 0.3, 0.45, 0.6, 0.72, 0.85, 1.] l = list(zip(v,c)) palette=LinearSegmentedColormap.from_list('rg',l, N=256) lc = LineCollection(segments, cmap=palette, norm=plt.Normalize(0, 1.5)) lc.set_array(np.array(dydx)) lc.set_linewidth(4) line = ax.add_collection(lc) fig.colorbar(line, ax=ax) plt.xlim(0, 10) plt.ylim(0, 10) plt.savefig(traj_png_filenames[counter], dpi =300) plt.savefig(traj_pdf_filenames[counter], dpi =300) plt.show()
def plot_bumps_1d(Y, subsampling=20, labels=None, labels_palette='hls', ax=None): if ax is None: ax = plt.gca() Y_subsampled = Y[:, ::subsampling] ax.plot(Y_subsampled) ax.set_xticks([]) if labels is not None: labels = np.sort(labels) unique_labels = np.unique(labels) segments = [] for lab in unique_labels: subset = np.where(labels == lab)[0] segments.append((subset[0] - 0.5, subset[-1] + 0.5)) offset = -0.1 * Y_subsampled.max() h_segments = [((s[0], offset), (s[1], offset)) for s in segments] colors = sns.color_palette(labels_palette, n_colors=len(unique_labels)) hlc = LineCollection(h_segments, colors=colors) hlc.set_linewidth(5) hlc.set_clip_on(False) ax.add_collection(hlc)
def waterfall_plot(fig,ax,X,Y,Z): ''' Make a waterfall plot Input: fig,ax : matplotlib figure and axes to populate Z : n,m numpy array. Must be a 2d array even if only one line should be plotted X,Y : n,m array ''' # Set normalization to the same values for all plots norm = plt.Normalize(Z.min().min(), Z.max().max()) # Check sizes to loop always over the smallest dimension n,m = Z.shape if n>m: X=X.T; Y=Y.T; Z=Z.T m,n = n,m for j in range(n): # reshape the X,Z into pairs points = np.array([X[j,:], Z[j,:]]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap='plasma', norm=norm) # Set the values used for colormapping lc.set_array((Z[j,1:]+Z[j,:-1])/2) lc.set_linewidth(2) # set linewidth a little larger to see properly the colormap variation line = ax.add_collection3d(lc,zs=(Y[j,1:]+Y[j,:-1])/2, zdir='y') # add line to axes fig.colorbar(lc) # add colorbar, as the normalization is the same for all, it doesent matter which of the lc objects we use
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 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 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 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
def coordsToLC(x, y, vals, cmap='jet'): """Converts coordinates to LineCollection and labels them with colormap. Args: x (numpy.ndarray): List of x-values. y (numpy.ndarray): List of y-values. vals (numpy.ndarray): Segment values. Keyword Args: cmap (str): Name of colormap. Returns: matplotlib.collections.LineCollection: LineCollection of the data. """ 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(0, max(vals))) lc.set_array(vals) lc.set_linewidth(3) return lc
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 trajectory_vel_with_occupancy_grid(map, file_ptahs): occupancy_grid, start, goal = get_occupancy_grid(map) #plt.style.use('ggplot') labels = [] for fp in file_ptahs: # data_path = np.genfromtxt(fp, delimiter=',') # plt.plot(data_path[:, 0], data_path[:, 1], color = "r" if "rrt" in fp else "b") # labels.append("RRT" if "rrt" in fp else "Wavefront") data_trajectory = np.genfromtxt(fp, delimiter=',') fig, axs = plt.subplots() velocities = data_trajectory[:, 2] # Create a continuous norm to map from data points to colors norm = plt.Normalize(velocities.min(), velocities.max()) points = np.array([data_trajectory[:, 0], data_trajectory[:, 1]]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap="Reds" if "rrt" in fp else "Blues", norm=norm) # Set the values used for colormapping lc.set_array(velocities) lc.set_linewidth(2) line = axs.add_collection(lc) plt.colorbar(line, ax=axs) occupancy_grid.draw() plt.show() #plt.title('Planned trajectories') plt.legend(labels) occupancy_grid.draw() plt.show()
def plotcf(grid, phase, modulus, darken=None, axes=None, linestylep="solid", linewidthp=1, color="k", **kwargs): r"""Plot the modulus of a complex valued function :math:`f:\mathbb{R} \rightarrow \mathbb{C}` together with its phase in a color coded fashion. :param grid: The grid nodes of the real domain R :param phase: The phase of the complex domain result f(grid) :param modulus: The modulus of the complex domain result f(grid) :param darken: Whether to take into account the modulus of the data to darken colors. :param axes: The axes instance used for plotting. :param linestylep: The line style of the phase curve. :param linewidthp: The line width of the phase curve. :param color: The color of the phase curve. """ # Color mapping rgb_colors = color_map(modulus, phase=phase, modulus=modulus, darken=darken) # Put all the vertical line into a collection segments = [array([[node, 0], [node, value]]) for node, value in zip(grid, modulus)] line_segments = LineCollection(segments) # Set some properties of the lines rgb_colors = line_segments.to_rgba(rgb_colors) line_segments.set_color(rgb_colors[0]) line_segments.set_linestyle(linestylep) line_segments.set_linewidth(linewidthp) # Plot to the given axis instance or retrieve the current one if axes is None: axes = gca() # Plot the phase axes.add_collection(line_segments) # Plot the modulus axes.plot(grid, modulus, color=color, **kwargs)
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 shape(self, height, yrange, rotated): g = rlg2mpl.Group() trans = TransformScalePart(g.combined_transform) y = height/2.0 segments = [[(x1,y),(x2,y)] for (x1,x2) in self.segments] a = LineCollection(segments, edgecolor='k', facecolor='k') a.set_linewidth(2) g.add(a) a.set_transform(g.combined_transform) return g
def plotgraph(xy,edges,edgecolor='b'): lcol = xy[edges] lc = LineCollection(xy[edges]) lc.set_linewidth(0.1) lc.set_color(edgecolor) pl.gca().add_collection(lc) #pl.plot(xy[:,0], xy[:,1], 'ro') pl.xlim(xy[:,0].min(), xy[:,0].max()) pl.ylim(xy[:,1].min(), xy[:,1].max()) pl.show()
def shape(self, height, yrange, rotated): g = rlg2mpl.Group() trans = TransformScalePart(g.combined_transform) segment = [(0.1, 0), (0.9, 0)] if rotated: segment = [(y, x) for (x, y) in segment] a = LineCollection([segment], colors=self.cvalues, offsets=self.offsets, transOffset=g.combined_transform) a.set_linewidth(3) g.add(a) a.set_transform(trans) return g
def plot_colored_line(ax, x, y, c=None, s=2, **kwargs): """ Draws a linegraph with the line color coded. """ points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, **kwargs) if c is not None: lc.set_array(c) lc.set_linewidth(s) ax.add_collection(lc) ax.set_xlim([x.min(), x.max()]) ax.set_ylim([y.min(), y.max()])
def plot_trajectory(trajectories, name='trajectory', pos='left'): print "Plotting trajectory: %s" % name plt.figure(1, figsize=(4, 4)) ax = plt.subplot(111) trajx = np.concatenate([t[0] for t in trajectories]) trajy = np.concatenate([t[1] for t in trajectories]) annote = set() for t in trajectories: for a in t[2]: annote.add(a) cmap = plt.get_cmap('Greys') t = np.arange(trajx.shape[0]) * 0.001 points = np.array([trajy, trajx]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, cmap=cmap, norm=plt.Normalize(-t[-1] * 0.5, t[-1] * 0.75)) lc.set_array(t) lc.set_linewidth(3) lc.set_rasterized(True) ax.add_collection(lc) for (a_t, l) in annote: ix = int(a_t / 0.001) - 1 xy = (trajy[ix], trajx[ix]) xytext = (-30 if xy[0] > 0 else 30, -30 if xy[1] > 0 else 30) if l == 'Start of next trial' and xy[1] > 0: l = 'Start of\nnext trial' xytext = (-50, 5) if l == 'Release\n(premature)': xytext = (-10, -35) plt.annotate(l, xy, xycoords='data', xytext=xytext, ha='center', va='center', textcoords='offset points', arrowprops={'arrowstyle': '->', 'connectionstyle': 'arc3, rad=0.2'}) plt.axhline(0.0, color='k', ls=":") plt.axvline(0.0, color='k', ls=":") if 'left' in pos: plt.ylabel("Task state (arbitrary units)") ax.get_yaxis().tick_left() else: plt.yticks(()) ax.get_xaxis().tick_bottom() plt.xlabel("Relative time in task state (arbitrary units)") plt.axis((-1.5, 1.5, -2.0, 1.5)) plt.subplots_adjust(bottom=0.12, top=0.97, left=0.17, right=0.97) save_or_show('plots/' + name + '_traj')
def drawstates(self,ax,linewidth=0.5,color='k',antialiased=1): """ Draw state boundaries in Americas. ax - current axis instance. linewidth - state boundary line width (default 0.5) color - state boundary line color (default black) antialiased - antialiasing switch for state boundaries (default True). """ coastlines = LineCollection(self.statesegs,antialiaseds=(antialiased,)) coastlines.color(color) coastlines.set_linewidth(linewidth) ax.add_collection(coastlines)
def drawcoastlines(self,ax,linewidth=1.,color='k',antialiased=1): """ Draw coastlines. ax - current axis instance. linewidth - coastline width (default 1.) color - coastline color (default black) antialiased - antialiasing switch for coastlines (default True). """ coastlines = LineCollection(self.coastsegs,antialiaseds=(antialiased,)) coastlines.color(color) coastlines.set_linewidth(linewidth) ax.add_collection(coastlines)
def plot(self, show_minima=False, linewidth=0.5, axes=None): """draw the disconnectivity graph using matplotlib don't forget to call calculate() first also, you must call pyplot.show() to actually see the plot """ import matplotlib as mpl from matplotlib.collections import LineCollection import matplotlib.pyplot as plt self.line_segments = self._get_line_segments(self.tree_graph, eoffset=self.eoffset) #set up how the figure should look if axes is not None: ax = axes else: fig = plt.figure(figsize=(6,7)) fig.set_facecolor('white') ax = fig.add_subplot(111, adjustable='box') ax.tick_params(axis='y', direction='out') ax.yaxis.tick_left() ax.spines['left'].set_color('black') ax.spines['left'].set_linewidth(0.5) ax.spines['top'].set_color('none') ax.spines['bottom'].set_color('none') ax.spines['right'].set_color('none') # plt.box(on=True) #draw the minima as points if show_minima: leaves = self.tree_graph.get_leaves() energies = [self._getEnergy(leaf.data["minimum"]) for leaf in leaves] xpos = [leaf.data["x"] for leaf in leaves] ax.plot(xpos, energies, 'o') # draw the line segments # use LineCollection because it's much faster than drawing the lines individually linecollection = LineCollection([ [(x[0],y[0]), (x[1],y[1])] for x,y in self.line_segments]) linecollection.set_linewidth(linewidth) linecollection.set_color("k") ax.add_collection(linecollection) # scale the axes appropriately ax.relim() ax.autoscale_view(scalex=True, scaley=True, tight=None) #remove xtics ax.set_xticks([])
def AddLine(self, X, Y, Z): #Add line to the 2D plot to show where the slice is taken # global linecolor # try: # self.line_segment.pop(0).remove() # except: # pass 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('Spectral')) lc.set_array(Z) lc.set_linewidth(2) self.axes.add_collection(lc) self.canvas.draw() #Update 2D plot