def __init__(self, N_onscreen=700,*args, **kwargs): ui.View.__init__(self,*args,**kwargs) # ready lock is used to protect calls to matplotlib self.ready=threading.Lock() #set up zoomable sliders self.hslider=ZoomSlider(frame=(self.width*0.08,0,self.width*0.84,self.height*0.08),vert=0,flex='wt') self.vslider=ZoomSlider(frame=(0,self.height*0.08,self.width*0.08,self.height*0.84),vert=1,flex='hr') self.add_subview(self.hslider) self.add_subview(self.vslider) self.hslider.barvalue=0.125 self.hslider.barwidth=0.25 self.vslider.barvalue=0.5 self.vslider.barwidth=1.0 self.hslider.action=self.did_slide self.vslider.action=self.did_slide #matplotlib image output self.img_view = ui.ImageView(frame=[self.width*0.08,self.height*0.08,self.width*0.84,self.height*0.84],flex='WH',bg_color=(1,1,1)) self.add_subview(self.img_view) # image buffer self.b = io.BytesIO() #store base xlim and ylim, only update when drag ends self.xlim=plt.xlim() self.ylim=plt.ylim() self.N_onscreen=N_onscreen # number of points onscreen # fast and slow dpi.. set low_dpi to lower number for snappier response self.high_dpi=92 self.low_dpi=16. self.device_dpi=72 # set output image size to match view size. this probably should be modified to use actual device dpi and size. fonts and line width are based on pts, not pixels plt.gcf().set_size_inches(self.img_view.width/self.device_dpi,self.img_view.height/self.device_dpi)
def plot_impressions(self, *args, **kwargs): """ Plots impressions over the duration of the test Allow setting a time range And Smoothing by taking an avergae over a window of records """ # set up list of banner to process if len(args) == 0: names = self.names else: names = args #process keyword arguments smooth = kwargs.get('smooth', 1) start = kwargs.get('start', '2000') stop = kwargs.get('stop', '2050') fig = plt.figure(figsize=(10, 6), dpi=80) ax = fig.add_subplot(111) plt.xticks(rotation=70) formatter = DateFormatter('%Y-%m-%d %H:%M') plt.gcf().axes[0].xaxis.set_major_formatter(formatter) for name in names: d = self.data[name]['impressions'] d = d[start:stop] d = pd.rolling_mean(d, smooth) ax.plot(d.index, d['count'], label=name) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.ylabel('impressions') plt.show()
def test_t_dates(self): cube = _date_series(self.wind[:, 0, 0, 0]) self.draw_method(cube) plt.gcf().autofmt_xdate() plt.xlabel('Phenomenon time') self.check_graphic()
def plot(self,plot_id): device_id = sEtting.device_id #"LASS-Example0" if self.first: self.init() plt.title(sEtting.mqtt_topic + ' Sensor data') plt.ylabel('Sensor value') plt.xlabel("Data sensing time") if plot_id>0: #FIXME error handler if device_id in dEvices.devs: x, y = dEvices.devs[device_id].get_values(sEtting.plot_cnt,plot_id) self.first=0 else: print("plot device:" + device_id + " not exist!") return else: x, y = dEvices.get_values(sEtting.plot_cnt) #FIXME self.first=0 # draw and show it #self.fig.canvas.draw() #plt.show(block=False) if len(x)<=0 or not x : print("data count=0, ignore plot. Maybe device id is wrong") plt.gcf().autofmt_xdate() (self.li, )= self.ax.plot(x, y) self.li.set_xdata(x) self.li.set_ydata(y) self.fig.canvas.draw() if sEtting.plot_save: plt.savefig("lass_" + str(plot_id) + ".png") else: plt.show(block=False)
def toggle_artist(self, artist): try: visible = artist.get_visible() artist.set_visible(not visible) plt.gcf().canvas.draw() except Exception: pass
def main(): from time import time import matplotlib.pyplot as plt x, y = np.mgrid[0:2000, 0:2000] data = np.sin(x / 10.) * np.cos(y / 30.) f = plt.figure() ax = f.add_subplot(111) #try switching between artist = ModestImage(ax, data=data) #artist = mi.AxesImage(ax, data=data) ax.set_aspect('equal') artist.norm.vmin = -1 artist.norm.vmax = 1 ax.add_artist(artist) ax.set_xlim(0, 1000) ax.set_ylim(0, 1000) t0 = time() plt.gcf().canvas.draw() t1 = time() print "Draw time for %s: %0.1f ms" % (artist.__class__.__name__, (t1 - t0) * 1000) plt.show()
def plot_jobs_by_skills(cur, skills): skill_jobs = {} for skill in skills: cur.execute('''select count(j.id) amount from jobs j where j.id in (select js.job_id from job_skills js where js.skill=?)''', (skill,)) res = cur.fetchone() skill_jobs[skill] = res[0] sorted_skill_jobs = zip(*sorted(skill_jobs.items(), key=operator.itemgetter(1), reverse=False)) fig = plt.figure() y_pos = np.arange(len(skill_jobs)) print y_pos ax = plt.barh(y_pos, sorted_skill_jobs[1], align='center', alpha=0.3) plt.yticks(y_pos, ['\n'.join(wrap(x, 10)) for x in sorted_skill_jobs[0]]) plt.ylabel('Skill') plt.xlabel('Amount of jobs') autolabel_h(ax) plt.gcf().subplots_adjust(left=0.20) return fig
def __pick_handler_event_annotation(event): """ Pick handler for the event annotation. """ if event.mouseevent.button == 1 and not event.mouseevent.dblclick: # Remove any potentially existing annotations. for i in __pick_state["event_annotations"]: i.remove() __pick_state["event_annotations"][:] = [] if __pick_state["current_event_annotation_artist"] is event.artist: __pick_state["current_event_annotation_artist"] = None return x, y = event.mouseevent.xdata, event.mouseevent.ydata annotation = plt.annotate( event.artist.detailed_event_description, xy=(x, y), xytext=(0.98, 0.98), textcoords="figure fraction", horizontalalignment="right", verticalalignment="top", arrowprops=dict(arrowstyle="fancy", color="0.5", connectionstyle="arc3,rad=0.3"), zorder=10E9, fontsize="small") __pick_state["event_annotations"].append(annotation) __pick_state["current_event_annotation_artist"] = event.artist # If it is a double-click, plot the event in a new figure. elif event.mouseevent.dblclick and event.artist._project: plt.figure() event.artist._project.plot_event(event.artist._event_name) plt.gcf().patch.set_alpha(0.0) plt.show()
def plot_event_histogram(events, plot_type): from matplotlib.dates import date2num, num2date from matplotlib import ticker plt.figure(figsize=(12, 4)) values = [] for event in events: if plot_type == "depth": values.append(event["depth_in_km"]) elif plot_type == "time": values.append(date2num(event["origin_time"].datetime)) plt.hist(values, bins=250) if plot_type == "time": plt.gca().xaxis.set_major_formatter(ticker.FuncFormatter( lambda numdate, _: num2date(numdate).strftime('%Y-%d-%m'))) plt.gcf().autofmt_xdate() plt.xlabel("Origin time (UTC)") plt.title("Origin time distribution (%i events)" % len(events)) elif plot_type == "depth": plt.xlabel("Event depth in km") plt.title("Hypocenter depth distribution (%i events)" % len(events)) plt.tight_layout()
def select_image(images, selection_callback): """ Givel an array of images, show them all and allow seection by clicking. :param images: :param selection_callback: :return: """ data = put_data_in_grid(images, is_color_data=True) plt.figure(figsize=(12, 12)) plt.imshow(data) plt.gca().tick_params(labelbottom = 'off') plt.gca().tick_params(labelleft = 'off') # dbplot(first_ims, 'First BBox Images') def callback(event): n_cols = int(np.ceil(np.sqrt(len(images)))) n_rows = int(np.ceil(len(images)/n_cols)) ax_size_x = plt.gca().get_xlim()[1] ax_size_y = plt.gca().get_ylim()[0] frac_x = event.xdata/ax_size_x frac_y = event.ydata/ax_size_y print (frac_x, frac_y) col_ix = int(n_cols*frac_x) row_ix = int((n_rows+1)*frac_y) ix = row_ix*n_cols + col_ix selection_callback(ix) plt.gcf().canvas.callbacks.connect('button_press_event', callback) plt.show()
def createHistogram(df, pic, bins=45, rates=False): data=mergeMatrix(df, pic) matrix=sortMatrix(df, pic) density = gaussian_kde(data) xs = np.linspace(min(data), max(data), max(data)) density.covariance_factor = lambda : .25 density._compute_covariance() #xs = np.linspace(min(data), max(data), 1000) fig,ax1 = plt.subplots() #plt.xlim([0, 4000]) plt.hist(data, bins=bins, range=[-500, 4000], histtype='stepfilled', color='grey', alpha=0.5) lims = plt.ylim() height=lims[1]-2 for i in range(0,len(matrix)): currentRow = matrix[i][np.nonzero(matrix[i])] plt.plot(currentRow, np.ones(len(currentRow))*height, '|', color='black') height -= 2 plt.axvline(x=0, color='red', linestyle='dashed') #plt.axvline(x=1000, color='black', linestyle='dashed') #plt.axvline(x=2000, color='black', linestyle='dashed') #plt.axvline(x=3000, color='black', linestyle='dashed') if rates: rates = get_rate(df, pic) ax1.text(-250, 4, str(rates[0]), size=15, ha='center', va='center', color='green') ax1.text(500, 4, str(rates[1]), size=15, ha='center', va='center', color='green') ax1.text(1500, 4, str(rates[2]), size=15, ha='center', va='center', color='green') ax1.text(2500, 4, str(rates[3]), size=15, ha='center', va='center', color='green') ax1.text(3500, 4, str(rates[4])+ r' $\frac{\mathsf{Spikes}}{\mathsf{s}}$', size=15, ha='center', va='center', color='green') plt.ylim([0,lims[1]+5]) plt.xlim([0, 4000]) plt.title('Histogram for ' + str(pic)) ax1.set_xticklabels([-500, 'Start\nStimulus', 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000]) plt.xlabel('Time (ms)') plt.ylabel('Counts (Spikes)') print lims arr_hand = getPic(pic) imagebox = OffsetImage(arr_hand, zoom=.3) xy = [3200, lims[1]+5] # coordinates to position this image ab = AnnotationBbox(imagebox, xy, xybox=(30., -30.), xycoords='data',boxcoords="offset points") ax1.add_artist(ab) ax2 = ax1.twinx() #Necessary for multiple y-axes #Use ax2.plot to draw the hypnogram. Be sure your x values are in seconds ax2.plot(xs, density(xs) , 'g', drawstyle='steps') plt.ylim([0,0.001]) plt.yticks([0.0001,0.0002, 0.0003, 0.0004, 0.0005, 0.0006, 0.0007, 0.0008, 0.0009]) ax2.set_yticklabels([1,2,3,4, 5, 6, 7, 8, 9]) plt.ylabel(r'Density ($\cdot \mathsf{10^{-4}}$)', color='green') plt.gcf().subplots_adjust(right=0.89) plt.gcf().subplots_adjust(bottom=0.2) plt.savefig(pic, dpi=150)
def plot_f(x,y): #plots one planck function plt.plot(x,y) plt.xlabel('$\lambda$ [nm]') plt.ylabel('Spectral radiance [W.sr$^{-1}$.m$^{-}$.nm$^{-1}$') plt.grid() plt.savefig("planck") plt.gcf().clear()
def run_mag_test(fld, title="", show=False): vx, vy, vz = fld.component_views() # pylint: disable=W0612 vx, vy, vz = fld.component_fields() try: t0 = time() mag_ne = viscid.magnitude(fld, preferred="numexpr", only=False) t1 = time() logger.info("numexpr mag runtime: %g", t1 - t0) except viscid.verror.BackendNotFound: xfail("Numexpr is not installed") planes = ["z=0", "y=0"] nrows = 4 ncols = len(planes) _, axes = plt.subplots(nrows, ncols, sharex=True, sharey=True, squeeze=False) for ind, p in enumerate(planes): vlt.plot(vx, p, ax=axes[0, ind], show=False) vlt.plot(vy, p, ax=axes[1, ind], show=False) vlt.plot(vz, p, ax=axes[2, ind], show=False) vlt.plot(mag_ne, p, ax=axes[3, ind], show=False) plt.suptitle(title) vlt.auto_adjust_subplots(subplot_params=dict(top=0.9, right=0.9)) plt.gcf().set_size_inches(6, 7) plt.savefig(next_plot_fname(__file__)) if show: vlt.mplshow()
def existe_note(img,ecart,i,j,seuil,coul): somme = 0 rep = False ecart = int(round(ecart)) for x in range(i-ecart,i): for y in range(j-ecart,j): if x < img.shape[0] and y < img.shape[1]: if img[x][y] == 0: somme = 1 + somme #plt.plot([j-ecart,j,j,j-ecart,j-ecart],[i-ecart-1,i-ecart-1,i-1,i-1,i-ecart-1]) #si on remplit plus de 20% du carré "en bas" if somme*100 >= seuil*ecart*ecart: c1 = plt2.Circle(((2*j-ecart)/2,i),3*e/2,color=coul) plt2.gcf().gca().add_artist(c1) rep = True else: somme = 0 for x in range(i-ecart,i): for y in range(j,j+ecart): if x < img.shape[0] and y < img.shape[1]: if img[x][y] == 0: somme = 1 + somme #plt.plot([j,j+ecart,j+ecart,j,j],[i-ecart+1,i-ecart+1,i+1,i+1,i-ecart+1]) #si on remplit plus de 20% du carré "en haut" if somme*100 >= seuil*ecart*ecart: c1 = plt2.Circle(((2*j+ecart)/2,i),3*e/2,color=coul) plt2.gcf().gca().add_artist(c1) rep = True return rep
def existe_croche_bas(img,ecart,i,j): somme = 0 rep = 0 ecart = int(round(ecart)) e2 = int(round(ecart/2)) for x in range(i-e2,i): for y in range(j-e2,j): if x < img.shape[0] and y < img.shape[1]: if img[x][y] == 0: somme = 1 + somme if somme*100 >= pc_cro*e2*e2: p = plt2.Rectangle((j-e2,i-e2),e2,e2,color='b') plt2.gcf().gca().add_artist(p) rep = 1 else: somme = 0 for x in range(i-e2,i): for y in range(j,j+e2): if x < img.shape[0] and y < img.shape[1]: if img[x][y] == 0: somme = 1 + somme if somme*100 >= pc_cro*e2*e2: p = plt2.Rectangle((j-e2,i-e2),e2,e2,color='b') plt2.gcf().gca().add_artist(p) rep = 1 return rep
def plot_eta(pT_lower_cut): properties_reco = [parse_file("/home/aashish/pythia_reco.dat", pT_lower_cut=pT_lower_cut), parse_file("/home/aashish/herwig_reco.dat", pT_lower_cut=pT_lower_cut), parse_file("/home/aashish/sherpa_reco.dat", pT_lower_cut=pT_lower_cut)] properties_truth = [parse_file("/home/aashish/pythia_truth.dat", pT_lower_cut=pT_lower_cut), parse_file("/home/aashish/herwig_truth.dat", pT_lower_cut=pT_lower_cut), parse_file("/home/aashish/sherpa_truth.dat", pT_lower_cut=pT_lower_cut)] labels = ["pythia", "herwig", "sherpa"] for prop_reco, prop_truth, label in zip(properties_reco, properties_truth, labels): x = prop_truth['hardest_eta'] y = prop_reco['hardest_eta'] H, xedges, yedges = np.histogram2d(x, y, bins=200, normed=1 ) H = np.rot90(H) H = np.flipud(H) Hmasked = np.ma.masked_where(H == 0, H) # Mask pixels with a value of zero plt.pcolormesh(xedges,yedges, Hmasked) cbar = plt.colorbar() cbar.ax.set_ylabel('Counts') plt.xlim(0, 3) plt.ylim(0, 3) plt.xlabel('Truth $\eta$', fontsize=50, labelpad=75) plt.ylabel('Reco $\eta$', fontsize=50, labelpad=75) plt.gcf().set_size_inches(30, 30, forward=1) plt.gcf().set_snap(True) plt.savefig("plots/With MC/2D/eta_" + label + ".pdf") plt.clf()
def plot( name, data ) : dates = data["date"] times = data["time"] ddiff = max(dates)-min(dates) plt.close() plt.figure() plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b-%d %X')) # set x-axis scale if ddiff.days > 60 : plt.gca().xaxis.set_major_locator(mdates.MonthLocator()) elif ddiff.days > 2 : plt.gca().xaxis.set_major_locator(mdates.DayLocator()) else : plt.gca().xaxis.set_major_locator(mdates.HourLocator()) plt.plot( dates, times, 'bo-' ) plt.gcf().autofmt_xdate() plt.title( name ) plt.xlabel( "Date" ) plt.ylabel( "Time (s)" ) plt.grid(True) plt.setp(plt.gca().get_xmajorticklabels(), size=6,rotation=30) # plt.show() plt.savefig( name )
def plot_currents(gex,ginh , xlabel = 'Time (s)',ylabel='ylabel',title='Title',color='r', filename='currents', size=(10, 5),fontsize= 10,lw=2,marker='',ylims=(-5,5),xticks=[],yticks=[]): fig = plt.figure() ax = plt.gca() fig.set_size_inches(size) plt.plot(gex,linewidth = lw, marker=marker, color ='darkgreen' ) plt.plot(-1 * ginh,linewidth = lw,marker=marker, color ='darkred' ) if not ARTISTIC_PLOT: plt.xlabel(xlabel,fontsize=fontsize) plt.ylabel(ylabel,fontsize=fontsize) if SHOW_TITLE: plt.title(title, fontsize=fontsize) plt.tick_params(labelsize=fontsize) ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') plt.gcf().subplots_adjust(bottom=.4,left=.2) plt.xlim([0,10000]) plt.ylim(ylims) ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') if len (xticks ) > 0: plt.xticks(xticks,xlabels) if len (yticks ) > 0: plt.yticks(yticks) if ARTISTIC_PLOT: ax.spines['bottom'].set_color('none') plt.xticks([]) if SAVE_PLOTS: plt.savefig('results/' + filename+'.eps') plt.savefig('results/' + filename+'.png')
def plot_nice(data, xlabel = 'Time (s)',ylabel='ylabel',title='Title',color='b', dims = 1, filename='nice', size=(10,5), fontsize= 10,lw=2,marker='',xticks=[],yticks=[]): fig = plt.figure() ax = plt.gca() fig.set_size_inches(size) if dims == 1: plt.plot(data,linewidth = lw, color =color ,marker=marker) else: plt.plot(data[0],data[1], linewidth = lw, color=color) if not ARTISTIC_PLOT: plt.xlabel(xlabel,fontsize=fontsize) plt.ylabel(ylabel,fontsize=fontsize) if SHOW_TITLE: plt.title(title,fontsize=fontsize) plt.tick_params(labelsize=fontsize) ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') plt.gcf().subplots_adjust(bottom=.4,left=.2) if ARTISTIC_PLOT: ax.spines['bottom'].set_color('none') if len (xticks ) > 0 and not ARTISTIC_PLOT: plt.xticks(xticks,xlabels) #if len (yticks ) > 0: plt.yticks(yticks) if ARTISTIC_PLOT: ax.spines['bottom'].set_color('none') plt.xticks([]) if SAVE_PLOTS: plt.savefig('results/' + filename+'.eps') plt.savefig('results/' + filename+'.png')
def showFakeObjects(root1, root2, visit, ccd, root="", matchObjs=None, noMatch=None, badMatch=None): # get the image array before the fake objects are added imgBefore = getExpArray(root + root1, visit, ccd) imgAfter = getExpArray(root + root2, visit, ccd) # get the difference between the two image imgDiff = (imgAfter - imgBefore) # stretch it with arcsinh and make a png with pyplot fig, axes = pyplot.subplots(1, 3, sharex=True, sharey=True, figsize=(15,10)) pyplot.subplots_adjust(left=0.04, bottom=0.03, right=0.99, top=0.97, wspace=0.01, hspace = 0.01) imgs = imgBefore, imgAfter, imgDiff titles = "Before", "After", "Diff" for i in range(3): axes[i].imshow(numpy.arcsinh(imgs[i]), cmap='gray') axes[i].set_title(titles[i]) area1 = numpy.pi * 6 ** 2 area2 = numpy.pi * 4 ** 2 if matchObjs is not None: axes[i].scatter(matchObjs['X'], matchObjs['Y'], s=area1, edgecolors='g', alpha=0.9) if noMatch is not None: axes[i].scatter(noMatch['X'], noMatch['Y'], s=area2, c='r', alpha=0.3) if badMatch is not None: axes[i].scatter(badMatch['X'], badMatch['Y'], s=area2, c='b', alpha=0.4) pyplot.gcf().savefig("%s-%d-%s.png"%(root2, visit, str(ccd)))
def target_class_variance(target_class, features, title): feature_variance = np.var(target_class, axis = 0) assert len(feature_variance) == len(target_class[0]) # create dictionary of feature and variance variance_per_feature = {} for i in range(0, len(feature_variance)): variance_per_feature[features[i]] = feature_variance[i] decreasing_variance_per_feature = OrderedDict(sorted(variance_per_feature.items(), key=lambda t: t[1], reverse = True)) # create tuples of feature and variance variances = sorted(variance_per_feature.items(), key=operator.itemgetter(1), reverse=True) ####################################################### # plot feature variance N = len(variances) x = np.arange(1, N+1) y = [num for (s, num) in variances] labels = [s for (s, num) in variances] width = 1 bar1 = plt.bar(x, y, width, color="y") plt.ylabel('Variance') plt.xticks(x + width/2.0, labels, rotation=45) plt.gcf().subplots_adjust(bottom=0.25) plt.title(title) plt.show()
def plot_date_bars(bin_data, bin_edges, title, ylabel, fname): """ Semi-generic function to plot a bar graph, x-label is fixed to "date" and the x-ticks are formatted accordingly. To plot a histogram, the histogram data must be calculated manually outside this function, either manually or using :py:func`numpy.histogram`. :param bin_data: list of data for each bin :param bin_edges: list of bin edges (:py:class:`datetime.date` objects), its length must be ``len(data)+1`` :param title: title of the plot :param ylabel: label of y-axis :param fname: output file name """ import matplotlib.pyplot as plt from matplotlib.dates import date2num, num2date from matplotlib import ticker plt.figure() # clear previous figure plt.title(title) plt.xlabel("date") plt.ylabel(ylabel) # plot the bars, width of the bins is assumed to be fixed plt.bar(date2num(bin_edges[:-1]), bin_data, width=date2num(bin_edges[1]) - date2num(bin_edges[0])) # x-ticks formatting plt.gca().xaxis.set_major_formatter(ticker.FuncFormatter(lambda numdate, _: num2date(numdate).strftime('%Y-%m-%d'))) plt.gcf().autofmt_xdate() plt.tick_params(axis="x", which="both", direction="out") plt.xticks([date2num(ts) for ts in bin_edges if ts.month % 12 == 1]) plt.savefig(fname, papertype="a4")
def beautify(): """Format the figure of the run length distribution. Used in conjunction with plot method (obsolete/outdated, see functions ``beautifyFVD`` and ``beautifyRLD``). """ # raise NotImplementedError('this implementation is obsolete') plt.subplot(121) axisHandle = plt.gca() axisHandle.set_xscale('log') axisHandle.set_xlabel('log10 of FEvals / DIM') axisHandle.set_ylabel('proportion of trials') # Grid options logxticks() beautifyECDF() plt.subplot(122) axisHandle = plt.gca() axisHandle.set_xscale('log') xmin, fmax = plt.xlim() plt.xlim(1., fmax) axisHandle.set_xlabel('log10 of Df / Dftarget') beautifyECDF() logxticks() axisHandle.set_yticklabels(()) plt.gcf().set_size_inches(16.35, 6.175)
def test_plot_tfr_topomap(): """Test plotting of TFR data """ import matplotlib as mpl import matplotlib.pyplot as plt raw = _get_raw() times = np.linspace(-0.1, 0.1, 200) n_freqs = 3 nave = 1 rng = np.random.RandomState(42) data = rng.randn(len(raw.ch_names), n_freqs, len(times)) tfr = AverageTFR(raw.info, data, times, np.arange(n_freqs), nave) tfr.plot_topomap(ch_type="mag", tmin=0.05, tmax=0.150, fmin=0, fmax=10, res=16) eclick = mpl.backend_bases.MouseEvent("button_press_event", plt.gcf().canvas, 0, 0, 1) eclick.xdata = 0.1 eclick.ydata = 0.1 eclick.inaxes = plt.gca() erelease = mpl.backend_bases.MouseEvent("button_release_event", plt.gcf().canvas, 0.9, 0.9, 1) erelease.xdata = 0.3 erelease.ydata = 0.2 pos = [[0.11, 0.11], [0.25, 0.5], [0.0, 0.2], [0.2, 0.39]] _onselect(eclick, erelease, tfr, pos, "mag", 1, 3, 1, 3, "RdBu_r", list()) tfr._onselect(eclick, erelease, None, "mean", None) plt.close("all")
def plot(self): self.artists = [] axis = plt.subplot(111) for i, plot_inst in enumerate(sorted(self.plot_instances, key=lambda pi: pi.sort_order)): self.artists.extend(plot_inst.plot(axis, i)) self.print_shortcuts() axis.set_xlabel('time') axis.set_xticklabels(axis.get_xticks(), rotation=90, fontsize=10) axis.xaxis.set_major_formatter(DateFormatter('%b %d\n%H:%M:%S')) for label in axis.get_xticklabels(): # make the xtick labels pickable label.set_picker(True) # log y axis if self.args['log']: axis.set_yscale('log') axis.set_ylabel('query duration in ms (log scale)') else: axis.set_ylabel('query duration in ms') handles, labels = axis.get_legend_handles_labels() if len(labels) > 0: self.legend = axis.legend(loc='upper left', frameon=False, numpoints=1, fontsize=9) plt.gcf().canvas.mpl_connect('pick_event', self.onpick) plt.gcf().canvas.mpl_connect('key_press_event', self.onpress) plt.show()
def plot_scatter(points, rects, level_id, fig_area=FIG_AREA, grid_area=GRID_AREA, with_axis=False, with_img=True, img_alpha=1.0): rect = rects[level_id] top_lat, top_lng, bot_lat, bot_lng = get_rect_bounds(rect) plevel = get_points_level(points, rects, level_id) ax = plevel.plot('lng', 'lat', 'scatter') plt.xlim(left=top_lng, right=bot_lng) plt.ylim(top=top_lat, bottom=bot_lat) if with_img: img = plt.imread('/data/images/level%s.png' % level_id) plt.imshow(img, zorder=0, alpha=img_alpha, extent=[top_lng, bot_lng, bot_lat, top_lat]) width, height = get_rect_width_height(rect) fig_width, fig_height = get_fig_width_height(width, height, fig_area) plt.gcf().set_size_inches(fig_width, fig_height) if grid_area: grid_horiz, grid_vertic = get_grids(rects, level_id, grid_area, fig_area) for lat in grid_horiz: plt.axhline(lat, color=COLOR_GRID, lw=GRID_LW) for lng in grid_vertic: plt.axvline(lng, color=COLOR_GRID, lw=GRID_LW) if not with_axis: ax.set_axis_off() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) return ax
def update(frame_number): plt.cla() if map_msg is not None: for lane in map_msg.hdmap.lane: draw_lane_boundary(lane, ax, 'b', map_msg.lane_marker) draw_lane_central(lane, ax, 'r') for key in map_msg.navigation_path: x = [] y = [] for point in map_msg.navigation_path[key].path.path_point: x.append(point.y) y.append(point.x) ax.plot(x, y, ls='-', c='g', alpha=0.3) if planning_msg is not None: x = [] y = [] for tp in planning_msg.trajectory_point: x.append(tp.path_point.y) y.append(tp.path_point.x) ax.plot(x, y, ls=':', c='r', linewidth=5.0) ax.axvline(x=0.0, alpha=0.3) ax.axhline(y=0.0, alpha=0.3) ax.set_xlim([10, -10]) ax.set_ylim([-10, 200]) y = 10 while y < 200: ax.plot([10, -10], [y, y], ls='-', c='g', alpha=0.3) y = y + 10 plt.yticks(np.arange(10, 200, 10)) adc = plt.Circle((0, 0), 0.3, color='r') plt.gcf().gca().add_artist(adc) ax.relim()
def main(): plt.figure(figsize=[8, 8]) ax = plt.axes(projection=ccrs.SouthPolarStereo()) ax.coastlines() ax.gridlines() im = ax.stock_img() def on_draw(event=None): """ Hooks into matplotlib's event mechanism to define the clip path of the background image. """ # Clip the image to the current background boundary. im.set_clip_path(ax.background_patch.get_path(), transform=ax.background_patch.get_transform()) # Register the on_draw method and call it once now. plt.gcf().canvas.mpl_connect("draw_event", on_draw) on_draw() # Generate a matplotlib path representing the character "C". fp = FontProperties(family="Bitstream Vera Sans", weight="bold") logo_path = matplotlib.textpath.TextPath((-4.5e7, -3.7e7), "C", size=1, prop=fp) # Scale the letter up to an appropriate X and Y scale. logo_path._vertices *= np.array([103250000, 103250000]) # Add the path as a patch, drawing black outlines around the text. patch = matplotlib.patches.PathPatch( logo_path, facecolor="white", edgecolor="black", linewidth=10, transform=ccrs.SouthPolarStereo() ) ax.add_patch(patch) plt.show()
def main(): start = datetime(2006, 1, 1, 0, 0, 0, 0, pytz.utc) end = datetime(2014, 8, 25, 0, 0, 0, 0, pytz.utc) data = zp.utils.factory.load_bars_from_yahoo(stocks=[stock], start=start, end=end, adjusted=True) algo = MyAlgo() perf = algo.run(data) fig = plt.figure() ax1 = fig.add_subplot(211, ylabel='Price in $') data[stock]['close'].plot(ax=ax1, color='r', lw=2.) perf[['short_ma', 'long_ma']].plot(ax=ax1, lw=2.) ax1.plot(perf.ix[perf.buy].index, perf.short_ma[perf.buy], '^', markersize=10, color='m') ax1.plot(perf.ix[perf.sell].index, perf.short_ma[perf.sell], 'v', markersize=10, color='k') ax2 = fig.add_subplot(212, ylabel='Portfolio value in $') perf.portfolio_value.plot(ax=ax2, lw=2.) ax2.plot(perf.ix[perf.buy].index, perf.portfolio_value[perf.buy], '^', markersize=10, color='m') ax2.plot(perf.ix[perf.sell].index, perf.portfolio_value[perf.sell], 'v', markersize=10, color='k') plt.legend(loc=0) plt.gcf().set_size_inches(14, 10) plt.show()
def save(w): # Make the directory if it's not already there filename, extension = os.path.splitext(savefilename_widget.value) extension = extension[1:] study.maybe_make_directory(savefilename_widget.value) plt.gcf().savefig(savefilename_widget.value, format=extension.lstrip('.'))
if use_cuda: val_x = val_x.cuda() val_label = val_label.cuda() val_output = cnn(val_x) v_loss = criterion(val_output, val_label) val_loss += v_loss # draw last val dataset for k in range(row_num * col_num): ii = k // col_num jj = k % col_num ax[ii, jj].cla() # clear the current axis ax[ii, jj].imshow(val_x[k, :].data.cpu().numpy().reshape(28, 28), cmap='Greys') display.clear_output(wait=True) display.display(plt.gcf()) # get a reference to a current figure print("label: {}".format(val_label[:row_num * col_num])) print("prediction: {}".format(val_output.argmax(dim=1)[:row_num * col_num])) del val_output del v_loss print("epoch: {}/{} | step: {}/{} | trn loss: {:.4f} | val loss: {:.4f}".format( epoch + 1, num_epochs, i + 1, num_batches, trn_loss / 100, val_loss / len(val_loader) )) trn_loss_list.append(trn_loss / 100) val_loss_list.append(val_loss / len(val_loader)) trn_loss = 0.0 plt.figure(figsize=(16, 9))
John = Mover(name = 'Cade',Circuits = Circuits,fitness_goal = goal) print('Cade: ',cos_vec_sim(Cade.Body_Vec, Cade.fitness_goal)) print('John: ',cos_vec_sim(John.Body_Vec, John.fitness_goal)) print("################\n") x = np.arange(10) y = np.zeros(10) for i in x: y[i] = cos_vec_sim(Cade.Body_Vec, Cade.fitness_goal) Cade.Perform_Ckt(Cade.Recommend_Diverse_Ckt()) colors = (0,0,0) plt.scatter(x, y, c=colors, alpha=0.5) plt.xlabel('Iteration') plt.ylabel('Cosine Similarity') plt.show() fig = plt.gcf() print('Cade: ',cos_vec_sim(Cade.Body_Vec, Cade.fitness_goal))
def new_state(self): """ layout editor state machine Parameters ---------- 'l' : select activelayer 'i' : back to init state 'j' : vertical and horizontal scaling 'e' : edit segment 'b' : edit segment keyboard 'CTRL + t' : translate structure 'h' : add subsegment 'd |Del' : delete subsegment 'r |F5' : refresh 'o' : toggle overlay (<> CP mode) set origin (CP mode) 'm' : toggle mode (point or segment) 'n' : toggle node label display 'z' : change display parameters 'CTRL+q' : quit 'x |CTRL+s' : save .str2 and .ini file 'w' : display all layers 'v' : flip layout w.r.t y axis 'f' : toggle points nodes display 'g' : toggle segments nodes display '=' : increment layer '$' : decrement layer """ fig = plt.gcf() ax = plt.gca() sl = self.L.sl cold = pyu.coldict() #print "In State ",self.state #print "In Event ",self.evt # # flip layout in y # if self.evt == ',': for k in self.ddoc.keys(): print k,self.ddoc[k] if self.evt == 'v': for n in self.L.Gs.pos: self.L.Gs.pos[n]=(self.L.Gs.pos[n][0],-self.L.Gs.pos[n][1]) self.update_state() return # # translation of layout (open a box) # # if self.evt == 't' : # offx,offy = offsetbox() # for n in self.L.Gs.pos: # self.L.Gs.pos[n]=(self.L.Gs.pos[n][0]+offx,self.L.Gs.pos[n][1]+offy) # self.update_state() # return if self.evt=='escape': self.state='Init' self.update_state() self.fig.canvas.draw() return if self.evt=='ctrl+z': self.bundo=True print len(self.L.Gs) if len (self.undoGs) >2: oGs=self.undoGs.pop(-1) oGs=self.undoGs.pop(-1) self.L.Gs=oGs self.L.g2npy() self.update_state() self.bundo=False return if self.evt=='t': if 'SM' in self.state: self.update_state() # fig=plt.gcf() # ax=plt.gca() if self.selected == 'pt': self.plotselptseg(self.selectseg,color='r') PP=self.L.pt[:,self.L.tahe[:,self.L.tgs[self.selectseg]]] if PP.shape[-1]!=0: self.fig,self.ax=plu.displot(PP[:,0],PP[:,1],fig=self.fig,ax=self.ax,color='r',linewidth=3,alpha=0.4) plt.draw() self.selected='seg' self.state='SMS' else: self.fig,self.ax= self.plotselptseg(self.selectpt) self.selected='pt' self.state='SMP' self.ax.title.set_text(self.statename[self.state]) # self.update_state() if self.evt == '3': self.L._show3() return # Choose layers to visualized # if self.evt == 'l': listchoices = self.L.name.keys() self.L.display['layers'] = multchoicebox('message', 'titre', listchoices) self.state = 'Init' self.update_state() return # # 'f' toggle points nodes display # if self.evt=='f': self.L.display['nodes'] = not self.L.display['nodes'] print self.L.display['nodes'] self.update_state() return # # 'g' toggle segment nodes dislay # if self.evt=='g': self.L.display['ednodes'] = not self.L.display['ednodes'] print self.L.display['ednodes'] self.update_state() return # # '=' Increment layer # if self.evt=='=': N = len(self.L.display['layerset']) index = self.L.display['layerset'].index(self.L.display['activelayer']) self.L.display['activelayer'] = self.L.display['layerset'][(index+1) % N] self.current_layer = self.L.display['activelayer'] print self.current_layer self.update_state() return # # '=' Decrement layer # if self.evt=='$': N = len(self.L.display['layerset']) index = self.L.display['layerset'].index(self.L.display['activelayer']) self.L.display['activelayer'] = self.L.display['layerset'][(index-1) % N] self.current_layer = self.L.display['activelayer'] print self.current_layer self.update_state() return # # 'i' : Back to init state # if self.evt == 'i': self.state = 'Init' self.update_state() return # # 'e' # if state == Init # egalize points coordinates # # if state == SS # edit segment properties # if self.evt == 'e': if (self.state == 'Init'): # # averaging one point coordinate along the smallest dimension # x1 = self.ax.get_xbound() y1 = self.ax.get_ybound() # get node list and edge list ndlist, edlist = self.L.get_zone([x1[0],x1[1],y1[0],y1[1]]) for k,nd in enumerate(ndlist): try: tp = np.vstack((tp,np.array(self.L.Gs.pos[nd]))) except: tp = np.array(self.L.Gs.pos[nd]) mtp = np.sum(tp,axis=0)/(k+1) stp = np.sqrt(np.sum((tp-mtp)*(tp-mtp),axis=0)/(k+1)) # if the standard deviation is lower than 10cm # averaging coordinates along the shortest axis if min(stp) < 0.10: ind = np.where(stp==min(stp))[0][0] for nd in ndlist: x = self.L.Gs.pos[nd][0] y = self.L.Gs.pos[nd][1] if ind ==0: self.L.Gs.pos[nd]=(mtp[0],y) if ind ==1: self.L.Gs.pos[nd]=(x,mtp[1]) plt.axis('tight') self.fig,self.ax = self.show(self.fig,self.ax,clear=True) self.update_state() return() if (self.state == 'SS') | (self.state =='SSS'): self.L.edit_segment(self.selected_edge1) self.state = 'Init' self.update_state() return if self.state == 'SP1': self.L.edit_point(self.selected_pt1) self.state = 'Init' self.update_state() return if self.state == 'SMS': outdata=self.L.edit_segment(self.selectseg[0]) [self.L.edit_segment(s,outdata=outdata,gui=False) for s in self.selectseg] self.update_state() return # # "b" : enter a segment node value with keyboard # if self.evt == 'b': if self.state == 'Init': self.nsel = eval(raw_input("seg number :")) #self.L.edit_segment(nseg) self.state='SS' self.update_state() return # # j : vertical and horizontal scaling (Init) # if self.evt == 'j': if self.state == 'Init': vscale = eval(enterbox('enter vscale',argDefaultText='1.0')) hscale = eval(enterbox('enter hscale',argDefaultText='1.0')) for n in self.L.Gs.pos: self.L.Gs.pos[n]=(self.L.Gs.pos[n][0]*hscale,self.L.Gs.pos[n][1]*vscale) plt.axis('tight') self.fig,self.ax = self.show(self.fig,self.ax,clear=True) self.update_state() return # Init # h : horizontal scaling factor # add subsegment (SS) # if self.evt == 'h': # if self.state == 'Init': # hscale = eval(raw_input("horizontal scaling factor : ")) # for n in self.L.Gs.pos: # self.L.Gs.pos[n]=(self.L.Gs.pos[n][0]*hscale,self.L.Gs.pos[n][1]) # plt.axis('tight') # fig,ax = self.show(fig,ax,clear=True) # self.update_state() # return() if self.state == 'SS': result = self.L.add_subseg(self.selected_edge1,self.current_layer) if result: self.state = 'SSS' else : self.state = 'Init' self.update_state() return # # d : delete # if self.evt == 'd' or self.evt =='delete': if self.state == 'SP1': self.state = 'Init' self.L.del_points(self.selected_pt1) self.update_state() return if self.state == 'SS': self.L.del_segment(self.selected_edge1) self.state = 'Init' self.update_state() return if self.state == 'SSS': self.L.del_subseg(self.selected_edge1) self.state = 'Init' self.update_state() return if self.state=='SMP': # get boundary of the region if hasattr(self,'selectpt'): ptlist = self.selectpt self.selectpt=[] self.selectseg=[] self.L.del_points(ptlist) self.state = 'Init' self.update_state() return else : print 'no selected region' if self.state=='SMS': seglist = self.selectseg self.selectpt=[] self.selectseg=[] self.L.del_segment(seglist) self.state = 'Init' self.update_state() return else : print 'no selected region' # # r : Refresh # if self.evt == 'r' or self.evt == 'f5': #plt.axis('tight') plt.axis(self.L.display['box']) self.fig,self.ax = self.show(self.fig,self.ax,clear=True) self.state = 'Init' self.update_state() return # # o : Toggle overlay # if self.evt == 'o' and not self.ctrl_is_held: self.state='Init' self.update_state() if self.L.display['overlay']: self.L.display['overlay'] = False self.update_state() else: self.L.display['overlay'] = True self.update_state() return if self.evt == 'o' : self.set_origin = True # # F2 : Create point # if self.evt == 'f2': self.state = "CP" self.update_state() return # # m : Toggle mode edition Point | Segment # if self.evt == 'm': if self.state == "Init": self.state = "CP" elif self.state == "CP": self.state = "Init" self.update_state() return # # 'z' : change display parameters # if self.evt == 'z': self.L.displaygui() self.fig,self.ax = self.show(fig=self.fig,ax=self.ax,clear=True) return # # 'q' : quit interactive mode # # if self.evt == 'q': # plt.rcParams.update(self.rcconf) # fig.canvas.mpl_disconnect(self.L.cid1) # fig.canvas.mpl_disconnect(self.L.cid2) # return if self.evt == 'ctrl+q': plt.rcParams.update(self.rcconf) self.fig.canvas.mpl_disconnect(self.L.cid1) self.fig.canvas.mpl_disconnect(self.L.cid2) plt.close() return # # 'x' save structure # if self.evt == 'x' or self.evt =='ctrl+s': racine, ext = os.path.splitext(self.L.filename) filename = racine + '.str2' fileini = racine + '.ini' # Commented because ss_ce not updated #self.L.savestr2(filename) self.L.saveini(fileini) print "structure saved in ", filename print "structure saved in ", fileini return # # 'n' : toggle node label display # if self.evt == 'n': self.L.display['ndlabel'] = not self.L.display['ndlabel'] self.L.display['edlabel'] = not self.L.display['edlabel'] print self.L.display['activelayer'] self.fig,ax = self.show(fig=self.fig,ax=self.ax,clear=True) self.fig.canvas.draw() return # # "w" : display all layers # if self.evt == 'w': # display all layer self.L.display['activelayer'] = self.L.name.keys() print self.L.display['activelayer'] self.fig,self.ax = self.show(fig=self.fig,ax=self.ax,clear=True) return self.fig,self.ax # # Left clic and selected node is a point # if (self.evt == 'lclic') & (self.nsel < 0): # # select point 1 : Init -> SP1 # if self.state=='Init': # yellow point self.state = 'SP1' self.update_state() return # # select point 2 : SP1 --> SP2 # if self.state=='SP1': if self.nsel != self.selected_pt1: # green point self.state = 'SP2' self.update_state() return else: self.state = 'Init' # yellow point self.update_state() return # # Create point on selected segment orthogonaly to segment starting in # selected point # # Not finished # if self.state=='SS': # get the connection of the selected segment connect = self.L.Gs.node[self.selected_edge1]['connect'] if (self.nsel != connect[0]) & (self.nsel != connect[1]): self.L.add_nfpe(self.nsel,self.nsel,self.selected_edge1,self.selected_edge2) pass # # Left clic and selected node is a segment # if (self.evt == 'lclic') & (self.nsel > 0): if self.state=='Init': self.state = 'SS' self.update_state() return if self.state=='SS': self.nsel = self.selected_edge1 segdico = self.L.Gs.node[self.nsel] if 'ss_name' in segdico: self.state = 'SSS' else: self.state = 'CPS' self.update_state() return # # Right clic and selected node is a point # if (self.evt == 'rclic') & (self.nsel < 0): if self.state=='SP1': if self.nsel==self.selected_pt1: self.state = 'Init' self.update_state() return # # Right clic and selected node is a segment # if (self.evt == 'rclic') & (self.nsel > 0): if self.state=='SS': self.state = 'Init' self.update_state() return if self.state=='SSS': self.state = 'SS' self.update_state() return if self.state == 'CP': # create point on edge self.state = 'CPS' self.update_state() return if (self.state == 'CPS') & (self.nsel!= self.selected_edge1): # create point on edge self.state = 'CPSS' self.update_state() return # # Left clic # if (self.evt == 'lclic') and not (self.shift_is_held or self.alt_is_held or self.ctrl_is_held ): # add free node # or set origin if self.state == 'CP': if self.set_origin: offx = self.ptsel[0] offy = self.ptsel[1] print offx,offy xmin,xmax,ymin,ymax = self.L.display['box'] self.L.display['box'] = [xmin-offx,xmax-offx,ymin-offy,ymax-offy] self.set_origin=False self.set_x=True plt.axis('tight') self.fig,self.ax = self.show(self.fig,self.ax,clear=True) self.update_state() return if self.set_x: offx = self.ptsel[0] val = eval(enterbox('enter x value')) ratio = val/offx print ratio xmin,xmax,ymin,ymax = self.L.display['box'] self.L.display['box'] = [ratio*xmin,ratio*xmax,ymin,ymax] self.set_x=False self.set_y=True plt.axis('tight') self.fig,self.ax = self.show(self.fig,self.ax,clear=True) self.update_state() return if self.set_y: offx = self.ptsel[1] val = eval(enterbox('enter y value')) ratio = val/offx print ratio xmin,xmax,ymin,ymax = self.L.display['box'] self.L.display['box'] = [xmin,xmax,ratio*ymin,ratio*ymax] self.set_y=False plt.axis('tight') self.fig,self.ax = self.show(self.fig,self.ax,clear=True) self.update_state() return else: self.L.add_fnod(tuple(self.ptsel)) self.pt_previous = self.ptsel self.update_state() return if self.state == 'SP2': ta = self.selected_pt1 he = self.selected_pt2 segexist = self.L.isseg(ta,he) print segexist # if segment do not already exist, create it if not segexist: self.nsel = self.L.add_segment(ta, he,name=self.current_layer) else: print "segment ("+str(ta)+","+str(he)+") already exists" self.L.g2npy() self.state = 'Init' self.update_state() return # create point on segment if self.state == 'CPS': pt_new = geu.ptonseg(self.pta1, self.phe1, self.ptsel) pd1 = pt_new - self.pta1 pd2 = self.phe1 - self.pta1 alpha = np.sqrt(np.dot(pd1, pd1)) / np.sqrt(np.dot(pd2, pd2)) if (pt_new != []): # calculate alpha self.L.add_pons(self.selected_edge1, 1. - alpha) self.current_layer = self.L.Gs.node[self.selected_edge1]['name'] self.state = 'Init' self.update_state() return # # Right Clic event # if (self.evt == 'rclic') or (self.evt == 'lclic' and self.ctrl_is_held ): if self.state == 'CP': try: self.ptsel[0] = self.pt_previous[0] self.L.add_fnod(tuple(self.ptsel)) self.pt_previous = self.ptsel self.update_state() return except: return if self.state=='SP2': if self.nsel == self.selected_pt1: self.p1[0].set_visible(False) self.p2[0].set_visible(False) self.nsel = self.selected_pt2 self.state = 'SP1' self.update_state() return if self.nsel == self.selected_pt2: self.p1[0].set_visible(False) self.p2[0].set_visible(False) self.nsel = self.selected_pt1 self.state = 'SP1' self.update_state() return # # right click : back to SS from CPS # if self.state == 'CPS': self.state = 'SS' self.update_state() return # # right click : back to CPS from CPSS # if self.state == 'CPSS': self.state = 'CPS' self.update_state(self.fig,self.ax) return # # Center Clic event # if (self.evt == 'cclic') or (self.evt == 'lclic' and self.shift_is_held ): if self.state == 'CP': try: self.ptsel[1] = self.pt_previous[1] self.L.add_fnod(tuple(self.ptsel)) self.pt_previous = self.ptsel self.update_state() return except: return # # Left clic and selected node is a point # def point_select_callback(eclick, erelease): 'eclick and erelease are the press and release events' self.update_state() if not (self.shift_is_held or self.ctrl_is_held): self.selectpt=[] self.selectseg=[] x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata # print x1,x2,y1,y2 if x1>x2: x1,x2=x2,x1 if y1>y2: y1,y2=y2,y1 # try: selectpt,selectseg = self.L.get_zone([x1,x2,y1,y2]) if not self.ctrl_is_held: self.selectpt.extend(selectpt) self.selectseg.extend(selectseg) self.selectseg=filter(lambda x: self.L.Gs.node[x]['connect'][0] in self.selectpt and self.L.Gs.node[x]['connect'][1] in self.selectpt, self.selectseg) self.selectpt=np.unique(self.selectpt).tolist() self.selectseg=np.unique(self.selectseg).tolist() else: [self.selectpt.pop(self.selectpt.index(x)) for x in selectpt if x in self.selectpt] [self.selectseg.pop(self.selectseg.index(x)) for x in selectseg if x in self.selectseg] # except: # print 'empty selection' print self.selectpt,self.selectseg self.plotselptseg(self.selectpt) self.selected='pt' print self.state def toggle_selector(event): if toggle_selector.RS.active: toggle_selector.RS.set_active(False) if not toggle_selector.RS.active: toggle_selector.RS.set_active(True) if self.evt == 'f1': #avoid conflict between zoom and selection # fm=plt.get_current_fig_manager() # if fm.toolbar._active == 'PAN': # fm.toolbar.pan() # if fm.toolbar._active == 'ZOOM': # fm.toolbar.zoom() self.state='SMP' toggle_selector.RS = RectangleSelector(self.ax, point_select_callback, drawtype='box', useblit=True, button=[1,3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels') self.selector = toggle_selector.RS self.update_state() if self.evt == 'f9': print self.selectpt, self.selectseg
def save_FlowFile_BPFormat(fileinfo, adcp, rbr, params, options, debug=False): comments = [ 'data is in Polagye Tools format', 'data.east_vel and data.north_vel are relative to true north', 'The parameters were set by ' + fileinfo['paramfile'] ] day1 = date2py(adcp['mtime'][0][0]) print day1 #date_time = [date2py(tval[0]) for tval in adcp.mtime[:]] datenum = datetime(day1.year, 1, 1) + timedelta(365) datenum = datenum.toordinal() yd = adcp['mtime'][:].flatten() - datenum tind = np.where((yd > params['tmin']) & (yd < params['tmax']))[0] pres = {} time = {} time['mtime'] = adcp['mtime'][:].flatten()[tind] dt = np.nanmean(np.diff(time['mtime'])) if not rbr: print 'Depths measured by ADCP not yet coded.' comments.append('Depths as measured by ADCP') else: print 'Ensemble averaging rbr data' comments.append('Depths as measured by RBR sensor') nens = round(dt / (rbr.mtime[1] - rbr.mtime[0])) temp = np.arange(rbr.mtime[nens / 2 - 1], rbr.mtime[-1 - nens / 2], dt) #temp2 = np.r_[rbr.mtime[nens/2-1]: rbr.mtime[-1-nens/2]: dt] mtimeens = np.arange(rbr.mtime[nens / 2 - 1], rbr.mtime[-1 - nens / 2], dt) mtimeens = mtimeens + params['rbr_hr_offset'] / 24 depthens = calc_ensemble(rbr.depth, nens, 1) temp = sip.interp1d(mtimeens, depthens, kind='linear') pres['surf'] = temp(time['mtime']) + params['dabPS'] if debug: # Load in matlab values for testing filename = './140703-EcoEII_database/scripts_examples/mtime.mat' mat = sio.loadmat(filename, struct_as_record=False, squeeze_me=True) matTimes = mat['mtimeens'] filename = './140703-EcoEII_database/scripts_examples/dt.mat' mat = sio.loadmat(filename, struct_as_record=False, squeeze_me=True) matdt = mat['dt'] filename = './140703-EcoEII_database/scripts_examples/depthens.mat' mat = sio.loadmat(filename, struct_as_record=False, squeeze_me=True) matdepthens = mat['depthens'] filename = './140703-EcoEII_database/scripts_examples/time.mat' mat = sio.loadmat(filename, struct_as_record=False, squeeze_me=True) matmtime = mat['mtime'] print matTimes.shape print temp - matTimes print temp2 - matTimes print dt - matdt print depthens - matdepthens print 'time' print time['mtime'] - matmtime ## zlevels data = {} z = adcp['config']['ranges'][:] + params['dabADCP'] z = z.flatten() zind = np.where((z > params['zmin']) & (z < params['zmax']))[0] data['bins'] = z[zind] ## Currents data['vert_vel'] = adcp['vert_vel'][:][tind][:, zind] data['error_vel'] = adcp['error_vel'][:][tind][:, zind] # If compass wasn't calibrated if 'hdgmod' in params: adcp['east_vel'][:], adcp['north_vel'][:] = rotate_coords( adcp['east_vel'][:], adcp['north_vel'][:], params['hdgmod']) comments.append('East and north velocity rotated by params.hdgmod') # Rotate east_vel and north_vel to be relative to true north data['east_vel'], data['north_vel'] = \ rotate_to_true(adcp['east_vel'][:][tind][:, zind], adcp['north_vel'][:][tind][:, zind], params['declination']) # Direction data['dir_vel'] = get_DirFromN(data['east_vel'], data['north_vel']) # Signed Speed spd_all = np.sqrt(data['east_vel']**2 + data['north_vel']**2) # Determine flood and ebb based on principal direction (Polagye Routine) print 'Getting signed speed (Principal Direction Method) -- used all speeds' s_signed_all, PA_all = sign_speed(data['east_vel'], data['north_vel'], spd_all, data['dir_vel'], params['flooddir']) data['mag_signed_vel'] = s_signed_all if options['showRBRavg'] or debug: print 'Plotting RBR vs average' plt.plot(rbr.mtime + params['rbr_hr_offset'] / 24, rbr.depth + params['dabPS'], label='RBR') plt.plot(time['mtime'], pres['surf'], 'r', label='AVG') plt.xlabel('Time') plt.ylabel('Elevation') plt.legend(bbox_to_anchor=(0, 0, 1, 1), bbox_transform=plt.gcf().transFigure) plt.show() if options['showPA'] or debug: print 'Plotting PA vs mean' plt.plot(PA_all, data['bins'], label='PA') plt.plot(np.array([PA_all[0], PA_all[-1]]), np.array([np.mean(pres['surf']), np.mean(pres['surf'])]), label='mean') plt.xlabel('Principal Axis Direction\n(clockwise from north)') plt.ylabel('z (m)') plt.legend(bbox_to_anchor=(0, 0, 1, 1), bbox_transform=plt.gcf().transFigure) plt.show() ## save lon = params['lon'] lat = params['lat'] outfile = fileinfo['outdir'] + fileinfo['flowfile'] print 'Saving data to {0}'.format(outfile) saveDict = { 'data': data, 'pres': pres, 'time': time, 'lon': lon, 'lat': lat, 'params': params, 'comments': comments } #save(outfile,'data','pres','time','lon','lat','params','Comments') ## Save metadata #metadata.progname=[mfilename('fullpath')]; #metadata.date = datestr(now); #metadata.paramfile = fileinfo.paramfile; #save(outfile,'metadata','-append') return saveDict
def processKarmaRequest(msg, setOfPosts, quietMode, phbArcPaths, ageLimitHours=4): ''' By this point we know message is by an approved user, and is asking for a karma plot. We have to verify is the id associated with the request is currently in our setOfPosts. If so, make a plot, save to temp(?) and send to me ''' idTarget = msg.body.split(':')[-1].strip() input_subject_Line = msg.subject.lower() match = False for key in setOfPosts: submission, user = setOfPosts[key] if submission.id == idTarget: match = True break if match: karmaScore = [x[0] for x in submission.score_History] upvoteRatio = [x[1] for x in submission.score_History] date = [x[3] for x in submission.score_History] title = "Karma for post " + str( submission.make_shortlink()) + " by " + str(user.name) #plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M')) #plt.gcf().autofmt_xdate() # Deal with weird x min/max bug (without, scale will be improperly set to +- ~ 2 months) # See: # https://github.com/matplotlib/matplotlib/issues/5963 plt.xlim(xmin=min(date) - datetime.timedelta(minutes=20), xmax=max(date) + datetime.timedelta(minutes=20)) # Actual thing we care about # Two subplots, the axes array is 1-d f, axarr = plt.subplots(2, sharex=True) axarr[0].plot(date, karmaScore) axarr[0].set_title(title) axarr[0].set_ylabel("Karma") axarr[1].plot(date, upvoteRatio) axarr[1].set_ylabel("Upvote Ratio") axarr[1].set_xlabel("Timestamp") plt.gca().xaxis.set_major_formatter( mdates.DateFormatter('%Y-%m-%d %H:%M')) plt.gcf().autofmt_xdate() dirName = phbArcPaths['phbScoreDisplay'] outMedia = os.path.join(dirName, str(submission.id) + '.png') plt.savefig(outMedia, bbox_inches='tight') plt.close() # Send the info!!! outgoingMsg = title sbjLine = "Here's a pretty plot for you!" textSupervision.send_karma_plot(outgoingMsg, outMedia, sbjLine, input_subject_Line=input_subject_Line)
def create_class_visualization(target_y, model, dtype, **kwargs): """ Generate an image to maximize the score of target_y under a pretrained model. Inputs: - target_y: Integer in the range [0, 1000) giving the index of the class - model: A pretrained CNN that will be used to generate the image - dtype: Torch datatype to use for computations Keyword arguments: - l2_reg: Strength of L2 regularization on the image - learning_rate: How big of a step to take - num_iterations: How many iterations to use - blur_every: How often to blur the image as an implicit regularizer - max_jitter: How much to gjitter the image as an implicit regularizer - show_every: How often to show the intermediate result """ model.type(dtype) l2_reg = kwargs.pop('l2_reg', 1e-3) learning_rate = kwargs.pop('learning_rate', 25) num_iterations = kwargs.pop('num_iterations', 100) blur_every = kwargs.pop('blur_every', 10) max_jitter = kwargs.pop('max_jitter', 16) show_every = kwargs.pop('show_every', 25) # Randomly initialize the image as a PyTorch Tensor, and also wrap it in # a PyTorch Variable. img = torch.randn(1, 3, 224, 224).mul_(1.0).type(dtype) img_var = Variable(img, requires_grad=True) for t in range(num_iterations): # Randomly jitter the image a bit; this gives slightly nicer results ox, oy = random.randint(0, max_jitter), random.randint(0, max_jitter) img.copy_(jitter(img, ox, oy)) ######################################################################## # TODO: Use the model to compute the gradient of the score for the # # class target_y with respect to the pixels of the image, and make a # # gradient step on the image using the learning rate. Don't forget the # # L2 regularization term! # # Be very careful about the signs of elements in your code. # ######################################################################## #pass scores = model(img_var) scores = scores.squeeze() print(scores.size()) max_score_index = torch.max(scores, 0)[1].data[0] print(max_score_index) """ if max_score_index == target_y: print('stop!!!!!!!!!!!!!11 ',max_score_index) break """ target_score = scores[target_y] target_score.backward() dimg = img_var.grad.data img = img + learning_rate * (dimg - 2 * l2_reg * img) img_var = Variable(img, requires_grad=True) ######################################################################## # END OF YOUR CODE # ######################################################################## # Undo the random jitter img.copy_(jitter(img, -ox, -oy)) # As regularizer, clamp and periodically blur the image for c in range(3): lo = float(-SQUEEZENET_MEAN[c] / SQUEEZENET_STD[c]) hi = float((1.0 - SQUEEZENET_MEAN[c]) / SQUEEZENET_STD[c]) img[:, c].clamp_(min=lo, max=hi) if t % blur_every == 0: blur_image(img, sigma=0.5) # Periodically show the image if t == 0 or (t + 1) % show_every == 0 or t == num_iterations - 1: plt.imshow(deprocess(img.clone().cpu())) class_name = class_names[target_y] plt.title('%s\nIteration %d / %d' % (class_name, t + 1, num_iterations)) plt.gcf().set_size_inches(4, 4) plt.axis('off') plt.savefig('/home/hongyin/file/cs231n-assignment3/vis1/' + str(t) + '.png') return deprocess(img.cpu())
def new_songs_plays(): mysql_cn = pymysql.connect(host='10.25.0.118', port=3306, user='******', passwd='111111', db='music') artist_list = pd.read_sql( 'select album, plays from album_list order by album desc', mysql_cn).values.tolist() album_list = [(x[0], x[1]) for x in artist_list] count = 0 X_train = None y_train = None first = False X_test = [] y_test = [] inverse = [] album_set = [] yt_index = [] for album, plays in album_list: df = pd.read_sql( ''' SELECT plays from new_songs_plays WHERE album = '{album}' and ds >= '{start}' order by ds; '''.format(album=album, start=album[-8:]), mysql_cn) if np.max(df.values) < 1000: continue y_index = df.values.argmax() y = df.astype(float).values[y_index:] ss = MinMaxScaler(feature_range=(0.1, 0.9)) ss = ss.fit(y) y = ss.transform(y) y = y.reshape((y.shape[0])) X = np.arange(1, y.shape[0] + 1) X = X.reshape((-1, 1)) # if random.randint(0, 10) <= 1 and X.shape[0] <= 30: if album[-8:] >= '20150701': y_test.append(y) X_test.append(X) inverse.append(ss) album_set.append(album) yt_index.append(y_index) else: if not first: y_train = y X_train = X first = True else: y_train = np.hstack((y_train, y)) X_train = np.vstack((X_train, X)) lr = LinearRegression() X_train = xx(X_train) lr.fit(X_train, y_train) for xt, yt, ss in zip(X_test, y_test, inverse): df = pd.DataFrame(yt) res = lr.predict(xx(xt)) #res = 1 / (np.exp(lr.predict(xt)) + 1) df['predict'] = pd.DataFrame(res) df.columns = ['origin', 'predict'] df.plot() plt.title('%s' % album) fig = plt.gcf() fig.savefig('./img/nlog_No{No:0>3}.png'.format(No=count)) plt.close() count += 1 X_all = np.arange(1, 365) X_all = X_all.reshape((-1, 1)) result = [] for album, ss, index in zip(album_set, inverse, yt_index): gapday = datetime.timedelta(days=index) dateFrom = datetime.datetime.strptime(album[-8:], '%Y%m%d') if dateFrom.strftime('%Y%m%d') >= '20150701': continue print album, index pred = ss.inverse_transform(lr.predict(xx(X_all)).reshape( (-1, 1))).reshape((-1)) # pred = pred - np.max(pred) for plays in pred.tolist(): dateNow = (dateFrom + gapday).strftime('%Y%m%d') gapday += datetime.timedelta(days=1) if dateNow > '20151030': break result.append([album[:-8], dateNow, float(plays)]) result = pd.DataFrame(result) # print result result.columns = ['artist_id', 'ds', 'plays'] # result.to_sql('new_songs_decay', mysql_cn, flavor='mysql', if_exists='replace', index = False) result.to_csv('./new_songs_incr.csv', index=False) mysql_cn.close()
vmin, vmax = np.min(max_score), np.max(max_score) plot_topomap(max_score, raw.info, cmap=cm.viridis, vmin=vmin, vmax=vmax, contours=0) # Add colorbar plt.figure(figsize=[2, 4]) sm = cm.ScalarMappable(cmap='viridis', norm=colors.Normalize(vmin=vmin, vmax=vmax)) sm.set_array(np.linspace(vmin, vmax)) cbar = plt.colorbar(sm, orientation='vertical', label='Score') plt.gca().set_visible(False) plt.gcf().subplots_adjust(right=0.5) ################################################################################################### # Plot frequency with most dominant rhythmicity vmin, vmax = np.min(max_freq) - 2, np.max(max_freq) + 2 plot_topomap(max_freq, raw.info, cmap=cm.viridis, vmin=vmin, vmax=vmax, contours=0) # Add colorbar plt.figure(figsize=[2, 4]) sm = cm.ScalarMappable(cmap='viridis',
def draw(G, pos=None, ax=None, **kwds): """Draw the graph G with Matplotlib. Draw the graph as a simple representation with no node labels or edge labels and using the full Matplotlib figure area and no axis labels by default. See draw_networkx() for more full-featured drawing that allows title, axis labels etc. Parameters ---------- G : graph A networkx graph pos : dictionary, optional A dictionary with nodes as keys and positions as values. If not specified a spring layout positioning will be computed. See :py:mod:`networkx.drawing.layout` for functions that compute node positions. ax : Matplotlib Axes object, optional Draw the graph in specified Matplotlib axes. kwds : optional keywords See networkx.draw_networkx() for a description of optional keywords. Examples -------- >>> G = nx.dodecahedral_graph() >>> nx.draw(G) >>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout See Also -------- draw_networkx() draw_networkx_nodes() draw_networkx_edges() draw_networkx_labels() draw_networkx_edge_labels() Notes ----- This function has the same name as pylab.draw and pyplot.draw so beware when using `from networkx import *` since you might overwrite the pylab.draw function. With pyplot use >>> import matplotlib.pyplot as plt >>> import networkx as nx >>> G = nx.dodecahedral_graph() >>> nx.draw(G) # networkx draw() >>> plt.draw() # pyplot draw() Also see the NetworkX drawing examples at https://networkx.github.io/documentation/latest/auto_examples/index.html """ try: import matplotlib.pyplot as plt except ImportError: raise ImportError("Matplotlib required for draw()") except RuntimeError: print("Matplotlib unable to open display") raise if ax is None: cf = plt.gcf() else: cf = ax.get_figure() cf.set_facecolor('w') if ax is None: if cf._axstack() is None: ax = cf.add_axes((0, 0, 1, 1)) else: ax = cf.gca() if 'with_labels' not in kwds: kwds['with_labels'] = 'labels' in kwds draw_networkx(G, pos=pos, ax=ax, **kwds) ax.set_axis_off() plt.draw_if_interactive() return
def myhist(a): a.hist(edgecolor='black', linewidth=1.2) fig = plt.gcf() fig.set_size_inches(12,10) plt.show()
loc=2, frameon=True, pad=0.5, borderpad=1, sep=4, linekw=dict(color="black")) ax.add_artist(ob) cbar = 1 if cbar == 1: # create color bar divider = make_axes_locatable(ax) cax = divider.append_axes('right', size='5%', pad=0.1) fig.colorbar(im, cax=cax, orientation='vertical') #,format='%.0f') #get color bar object cbar = plt.gcf().axes[-1] #format colorbar cbar.set_ylabel('Cu (ug/cm2)', rotation=90, va="bottom", size=12, labelpad=20) # change number of tick labels on colorbar #cbar.locator_params(nbins=4) #change colorbar tick label sizes cbar.tick_params(labelsize=12) # change scale label, e.g. 1e-8 #cbar.set_title('1e4', size=11,loc='left') #change color bar scale label size, e.g. 1e-8 cbar.yaxis.get_offset_text().set(size=12) #change color bar scale label position
def __init__ (self , ax = None , fig = None ) : """ set the axis and figure. Find it if not given """ self.ax = plt.gca() if ax is None else ax self.fig = plt.gcf() if fig is None else fig
for i in np.linspace(0, 1, num=50): alter_list.append(i) temp_list.append(cal_TD(probToState=0.81, valueEstimates=[0.0, 4.0, 25.7, 0.0, 20.1, 12.2, 0.0], rewards=[7.9, -5.1, 2.5, -7.2, 9.0, 0.0, 1.6], lambd=i, gamma=1)) plt.grid() # ylim = (0, 1.1) # plt.ylim(*ylim) plt.plot(alter_list, temp_list, color="r") plt.savefig('example1.png') plt.gcf().clear() # cal_TD(lambd=1, # probToState=0.81, # valueEstimates=[0.0, 4.0, 25.7, 0.0, 20.1, 12.2, 0.0], # rewards=[7.9, -5.1, 2.5, -7.2, 9.0, 0.0, 1.6], # gamma=1) # '''example set 1''' # # Use scipy.optimize.fslove to calculate the numerical solution on what value can make cal_TD = 0. # print("============start finding lambda to make TD(lambda) = TD(1)===============") # result = fsolve(cal_TD, # x0=0.5, # args=(0.81, # [0.0, 4.0, 25.7, 0.0, 20.1, 12.2, 0.0],
print(Table_S1_Bias[2, column_id]) print('SE for IE:') Table_S1_SE[2, column_id] = np.std(IE_BS) / np.sqrt(rep - 1) print(Table_S1_SE[2, column_id]) print('Bias for DM:') Table_S1_Bias[3:13, column_id] = np.mean(DM_BS, 0) - true_DM print(Table_S1_Bias[3:13, column_id]) print('SE for DM:') Table_S1_SE[3:13, column_id] = np.std(DM_BS, 0) / np.sqrt(rep - 1) print(Table_S1_SE[3:13, column_id]) print('Bias for IM:') Table_S1_Bias[13:, column_id] = np.mean(IM_BS, 0) - true_IM print(Table_S1_Bias[13:, column_id]) print('SE for DM:') Table_S1_SE[13:, column_id] = np.std(IM_BS, 0) / np.sqrt(rep - 1) print(Table_S1_SE[13:, column_id]) # Calculate the averaged estimated weighted matrix B average_B = np.mean(all_Bs, 0) plt.matshow(average_B.T, cmap = 'bwr', vmin = -1, vmax = 1) fig1 = plt.gcf() plt.colorbar() plt.show() fig1.savefig('Figures/MATplot_ANOCE_' + scenario + '_Gauss_' + samplesize + '.pdf') np.savetxt("Table_S1_Bias.csv", Table_S1_Bias, delimiter = ",") np.savetxt("Table_S1_SE.csv", Table_S1_SE, delimiter = ",")
def mk_bush_lc_plot(snfitres=None): from astropy.io import ascii import numpy as np from scipy.interpolate import interp1d from matplotlib import pyplot as pl, ticker from pytools import plotsetup, colorpalette as cp import time start = time.time() if snfitres is not None: sn, fit, res = snfitres else: sn, fit, res = dofit( '/Users/rodney/Dropbox/MEDBAND/DATFILES/HST_CANDELS4_bushALL.sncosmo.dat', z=1.15, dz=0.001, t0=55803.1, dt0=25.0, model='s11-2006fo', noUV=True) snid = 'GSD11Bus' ymax = 0.8 # optbands = ['f350lp','f606w','f814w','f850lp'] allbands = np.unique(sn['filter']) broadbands = [ band for band in allbands if band in ['f814w', 'f105w', 'f125w', 'f140w', 'f160w'] ] nax = 5 medbanddict = { 'f105w': 'f098m', 'f125w': 'f127m', 'f140w': 'f139m', 'f160w': 'f153m' } bands = sn['filter'] mjd = sn['mjd'] flux = sn['flux'] * 10**(-0.4 * (sn['zpt'] - 25)) fluxerr = sn['fluxerr'] * 10**(-0.4 * (sn['zpt'] - 25)) alpha2filter = { 'H': 'f160w', 'N': 'f140w', 'J': 'f125w', 'Y': 'f105w', 'Z': 'f850l', 'I': 'f814w', 'V': 'f606w', 'L': 'f098m', 'O': 'f127m', 'P': 'f139m', 'Q': 'f153m', } plotsetup.fullpaperfig([8, 3]) pl.clf() fig = pl.gcf() #mjdmin = mjd.min()-10 #mjdmax = mjd.max()+25 ymax = 0.7 ymaxMB = 0.39 mjdmin = 55701 mjdmax = 55995 mjdmod = np.arange(mjdmin, mjdmax, 1) z, mjdpeak = 1.15, 55802. snlabel = 'GSD11Bus' trestmin = (mjdmin - mjdpeak) / (1 + z) trestmax = (mjdmax - mjdpeak) / (1 + z) ax1w = pl.subplot2grid([4, 4], [0, 0], rowspan=3) ax2w = pl.subplot2grid([4, 4], [0, 1], rowspan=3, sharex=ax1w, sharey=ax1w) ax3w = pl.subplot2grid([4, 4], [0, 2], rowspan=3, sharex=ax1w, sharey=ax1w) ax4w = pl.subplot2grid([4, 4], [0, 3], rowspan=3, sharex=ax1w, sharey=ax1w) #ax5w = pl.subplot2grid( [4,5], [0,4], rowspan=3, sharex=ax1w, sharey=ax1w ) ax1m = pl.subplot2grid([4, 4], [3, 0], sharex=ax1w) ax2m = pl.subplot2grid([4, 4], [3, 1], sharex=ax1w, sharey=ax1m) ax3m = pl.subplot2grid([4, 4], [3, 2], sharex=ax1w, sharey=ax1m) ax4m = pl.subplot2grid([4, 4], [3, 3], sharex=ax1w, sharey=ax1m) #ax5m = pl.subplot2grid( [4,5], [3,4], sharex=ax1w, sharey=ax1m ) iax = 0 for bb, mb in zip(['f105w', 'f125w', 'f140w', 'f160w'], ['f098m', 'f127m', 'f139m', 'f153m']): iax += 1 ibb = np.where(bands == bb) imb = np.where(bands == mb) yval = flux yerr = fluxerr ymod_bb = fit.bandflux(bb, mjdmod, zp=25, zpsys='ab') if iax == 1: axw = ax1w axm = ax1m axw.text(0.05, 0.92, snlabel, color='k', fontsize='large', fontweight='heavy', ha='left', va='top', transform=axw.transAxes) # axw.text( -0.28, 1.2, snlabel, backgroundcolor='w', color='k', fontsize='large', fontweight='heavy', ha='left',va='top', transform=axw.transAxes, zorder=1000 ) axw.set_ylabel('flux (zp$_{AB}$=25)') axm.set_ylabel('$\Delta$f$_{25}$') elif iax == 2: axw = ax2w axm = ax2m elif iax == 3: axw = ax3w axm = ax3m elif iax == 4: axw = ax4w axm = ax4m axw.yaxis.set_ticks_position('right') axw.yaxis.set_ticks_position('both') axm.yaxis.set_ticks_position('right') axm.yaxis.set_ticks_position('both') axtop = axw.twiny() axtop.set_xlim(trestmin, trestmax) if iax in [2, 3]: pl.setp(axw.get_yticklabels(), visible=False) pl.setp(axm.get_yticklabels(), visible=False) if iax == 2: axtop.set_xlabel('rest frame time (days from peak)') axm.set_xlabel('observer frame time (MJD)') pl.setp(axw.get_xticklabels(), visible=False) axw.text(0.95, 0.92, bb.upper(), ha='right', va='top', color='k', transform=axw.transAxes) color = 'k' axw.plot(mjdmod, ymod_bb, marker=None, color='0.5', ls='-', zorder=-10) axw.errorbar(mjd[ibb], yval[ibb], yerr[ibb], ms=8, marker='o', color=color, mfc=color, mec=color, capsize=0, ls=' ', zorder=10) if not mb: continue axm.text(0.95, 0.5, mb.upper(), ha='right', va='center', backgroundcolor='w', color=color, transform=axm.transAxes) mbfluxdiff = yval[imb] - fit.bandflux(mb, mjd[imb], zp=25, zpsys='ab') axm.errorbar(mjd[imb], mbfluxdiff, fluxerr[imb], color='k', marker='o', mfc='w', ls=' ') # axm.fill_between( mjdmod, fluxerr[imodmb], -fluxerr[imodmb], # color=color, alpha=0.3, zorder=-1000 ) axm.axhline(0, color='k', lw=0.8, ls='--') ax1w.set_xlim(mjdmin, mjdmax) ax1w.set_ylim(-0.08, ymax) ax1m.set_ylim(-ymaxMB, ymaxMB) ax1w.xaxis.set_major_locator(ticker.MultipleLocator(100)) ax1w.xaxis.set_minor_locator(ticker.MultipleLocator(25)) ax1w.yaxis.set_major_locator(ticker.MultipleLocator(0.2)) ax1w.yaxis.set_minor_locator(ticker.MultipleLocator(0.1)) ax1m.xaxis.set_major_locator(ticker.MultipleLocator(100)) ax1m.xaxis.set_minor_locator(ticker.MultipleLocator(25)) ax1m.yaxis.set_major_locator(ticker.MultipleLocator(0.2)) ax1m.yaxis.set_minor_locator(ticker.MultipleLocator(0.1)) fig.subplots_adjust(left=0.1, bottom=0.18, right=0.95, top=0.82, wspace=0., hspace=0) pl.draw()
price_date = data['Date'] price_close = data['High'] price_300ma = data['300 MA'] plt.plot_date(price_date, price_close, linestyle='solid', linewidth=1, markersize=.2) plt.plot_date(price_date, price_300ma, linestyle='solid', linewidth=1, markersize=.5, color="#6d904f") plt.xticks(rotation='-70', ha='center') # horizontal alignment does not seem to work? plt.gcf().autofmt_xdate() plt.legend(loc='upper left') plt.title('Bitcoin Price with 300MA') # plt.xlabel('Date') plt.ylabel('Closing Price (USD)') plt.tight_layout() plt.show()
def plot_light_curve_fit_from_SNANA(snid='colfax', plotmags=False): """ make a plot showing the light curve fit, extracted from a SNANA output .TEXT file generated by D.Scolnic""" from pytools import plotsetup, colorpalette as cp from astropy.io import ascii import numpy as np from matplotlib import pyplot as pl from scipy.interpolate import interp1d from matplotlib import ticker import os import sys from hstphot import hstzpt alpha2filter = { 'H': 'f160w', 'N': 'f140w', 'J': 'f125w', 'Y': 'f105w', 'Z': 'f850l', 'I': 'f814w', 'V': 'f606w', 'L': 'f098m', 'O': 'f127m', 'P': 'f139m', 'Q': 'f153m', } colordict = { 'H': 'k', 'J': cp.darkgold, 'Y': cp.cadetblue, 'N': cp.darkgreen, 'V': cp.coral } fluxdat = ascii.read('CANDELs-%s.LCPLOT.TEXT' % snid) name = fluxdat['col1'] mjd = fluxdat['col2'] tobs = fluxdat['col3'] fluxcal = fluxdat['col4'] fluxcalerr = fluxdat['col5'] obsflag = fluxdat['col6'] bandletter = fluxdat['col7'] flux = fluxcal * 0.1 fluxerr = fluxcalerr * 0.1 # mag = np.where( flux>0, -2.5*np.log10( flux ) + 25, 35 ) # magerr = np.where( flux>0, 1.0857 * fluxerr / flux, 0.2 ) # medbanddict = {'f105w':'f098m','f125w':'f127m', 'f140w':'f139m', 'f160w':'f153m'} colors = [cp.purple, cp.bluegray, cp.darkgreen, cp.red] plotsetup.fullpaperfig([8, 3]) pl.clf() fig = pl.gcf() mjdmin = mjd.min() - 10 mjdmax = mjd.max() + 25 mjdmod = np.arange(mjdmin, mjdmax, 1) if snid == 'colfax': ymax = 0.7 ymaxMB = 0.3 mjdmin = 56025 mjdmax = 56220 z, mjdpeak = 2.1, 56080. snlabel = 'GND12Col' elif snid == 'stone': ymax = 1.2 ymaxMB = 0.35 mjdmin = 56430 mjdmax = 56600 z, mjdpeak = 1.8, 56485. snlabel = 'GND13Sto' trestmin = (mjdmin - mjdpeak) / (1 + z) trestmax = (mjdmax - mjdpeak) / (1 + z) ax1w = pl.subplot2grid([4, 3], [0, 0], rowspan=3) ax2w = pl.subplot2grid([4, 3], [0, 1], rowspan=3, sharex=ax1w, sharey=ax1w) ax3w = pl.subplot2grid([4, 3], [0, 2], rowspan=3, sharex=ax1w, sharey=ax1w) ax1m = pl.subplot2grid([4, 3], [3, 0], sharex=ax1w) ax2m = pl.subplot2grid([4, 3], [3, 1], sharex=ax1w, sharey=ax1m) ax3m = pl.subplot2grid([4, 3], [3, 2], sharex=ax1w, sharey=ax1m) iax = 0 for bbl, mbl, color in zip(['Y', 'J', 'N', 'H'], ['L', 'O', 'P', 'Q'], colors): if bbl not in bandletter: continue iax += 1 filternamew = alpha2filter[bbl].upper() filternamem = alpha2filter[mbl].upper() if iax == 1: axw = ax1w axm = ax1m axw.text(0.05, 0.92, snlabel, color='k', fontsize='large', fontweight='heavy', ha='left', va='top', transform=axw.transAxes) # axw.text( -0.28, 1.2, snlabel, backgroundcolor='w', color='k', fontsize='large', fontweight='heavy', ha='left',va='top', transform=axw.transAxes, zorder=1000 ) axw.set_ylabel('flux (zp$_{AB}$=25)') axm.set_ylabel('$\Delta$f$_{25}$') elif iax == 2: axw = ax2w axm = ax2m else: axw = ax3w axm = ax3m axw.yaxis.set_ticks_position('right') axw.yaxis.set_ticks_position('both') axm.yaxis.set_ticks_position('right') axm.yaxis.set_ticks_position('both') axtop = axw.twiny() axtop.set_xlim(trestmin, trestmax) if iax == 2: axtop.set_xlabel('rest frame time (days from peak)') axm.set_xlabel('observer frame time (MJD)') pl.setp(axw.get_yticklabels(), visible=False) pl.setp(axm.get_yticklabels(), visible=False) pl.setp(axw.get_xticklabels(), visible=False) axw.text(0.95, 0.92, filternamew, ha='right', va='top', color=color, transform=axw.transAxes) iobs = np.where((bandletter == bbl) & (obsflag > 0))[0] imod = np.where((bandletter == bbl) & (obsflag == 0))[0] # import pdb; pdb.set_trace() axw.errorbar(mjd[iobs], flux[iobs], fluxerr[iobs], color=color, marker='D', ls=' ', zorder=-100) axw.plot(mjd[imod], flux[imod], color=color, marker=' ', ls='-', zorder=-100) axw.fill_between(mjd[imod], flux[imod] + fluxerr[imod], flux[imod] - fluxerr[imod], color=color, alpha=0.3, zorder=-1000) if mbl not in bandletter: continue axm.text(0.95, 0.5, filternamem, ha='right', va='center', backgroundcolor='w', color=color, transform=axm.transAxes) iobsmb = np.where((bandletter == mbl) & (obsflag > 0))[0] imodmb = np.where((bandletter == mbl) & (obsflag == 0))[0] mbfluxinterp = interp1d(mjd[imodmb], flux[imodmb], fill_value=0, bounds_error=False) mbfluxdiff = flux[iobsmb] - mbfluxinterp(mjd[iobsmb]) axm.errorbar(mjd[iobsmb], mbfluxdiff, fluxerr[iobsmb], color=color, marker='o', mfc='w', ls=' ') axm.fill_between(mjd[imodmb], fluxerr[imodmb], -fluxerr[imodmb], color=color, alpha=0.3, zorder=-1000) axm.axhline(0, color=color, lw=0.8, ls='--') ax1w.set_xlim(mjdmin, mjdmax) ax1w.set_ylim(-0.08, ymax) ax1m.set_ylim(-ymaxMB, ymaxMB) ax1w.xaxis.set_major_locator(ticker.MultipleLocator(100)) ax1w.xaxis.set_minor_locator(ticker.MultipleLocator(25)) ax1w.yaxis.set_major_locator(ticker.MultipleLocator(0.2)) ax1w.yaxis.set_minor_locator(ticker.MultipleLocator(0.1)) ax1m.xaxis.set_major_locator(ticker.MultipleLocator(100)) ax1m.xaxis.set_minor_locator(ticker.MultipleLocator(25)) ax1m.yaxis.set_major_locator(ticker.MultipleLocator(0.2)) ax1m.yaxis.set_minor_locator(ticker.MultipleLocator(0.1)) fig.subplots_adjust(left=0.1, bottom=0.18, right=0.95, top=0.82, wspace=0., hspace=0) pl.draw()
### output from one episode for idx in range(0, 300): plt.gca().cla() obs = obs_data[idx] z_decoded = vae.full_model.predict(np.array([obs]))[0] plt.subplot(121) plt.imshow(obs) plt.subplot(122) plt.imshow(z_decoded) # plt.show() display.clear_output(wait=True) display.display(plt.gcf()) # %% ### output from the full_model DIR_NAME = './data/rollout/' file = os.listdir(DIR_NAME)[179] obs_data = np.load(DIR_NAME + file)['obs'] obs = obs_data[50] reconstruction = vae.full_model.predict(np.array([obs]))[0] ax1 = plt.subplot(121) plt.imshow(obs) ax1.axis('off') ax1.text(0.5, -0.1, "INPUT", size=12, ha="center", transform=ax1.transAxes)
def main(): # LOAD, FILTER, GET SMOOTH raw_values, wave_file = utils.process.load_raw( utils.audio_filepath(AUDIO_DIR, FILENAME), SECONDS) spectrum, spec_extent = utils.process.calc_spectrum(raw_values, FS) filtered_values = utils.process.adaptive_bandpass_filter( raw_values, spectrum, FS) amplitude = pd.Series(filtered_values).apply(np.abs) ampl_sm: pd.Series = amplitude.rolling(72, center=True).mean() utils.plot.draw_time_series(ampl_sm, wave_file=wave_file, seconds=SECONDS, interactive=INTERACTIVE, save_to=utils.plot_filepath( PLOTS_DIR, 'amplitude.png')) # FIND THRESHOLD FUNCTION default_dash_duration = 1000 # in points window_size = 6 * default_dash_duration window_min = ampl_sm.rolling(window_size, center=True, min_periods=int(0.1 * window_size)).min() window_max = ampl_sm.rolling(window_size, center=True, min_periods=int(0.1 * window_size)).max() min_max_threshold: pd.Series = (window_max + window_min) / 2 utils.plot.draw_time_series(ampl_sm, min_max_threshold, wave_file=wave_file, seconds=SECONDS, interactive=INTERACTIVE, save_to=utils.plot_filepath( PLOTS_DIR, 'amplitude_minmax.png')) # BEATS DURATION discr_step_one = ampl_sm > min_max_threshold # noinspection PyTypeChecker nulls, beats = utils.process.split_sign_series(discr_step_one) null_info = utils.process.intervals_data(ampl_sm, nulls, np.min) beat_info = utils.process.intervals_data(ampl_sm, beats, np.max) utils.plot.draw_time_series_with_points(ampl_sm, min_max_threshold, beat_info=beat_info, null_info=null_info, wave_file=wave_file, fs=FS, seconds=SECONDS, interactive=INTERACTIVE, save_to=utils.plot_filepath( PLOTS_DIR, 'amplitude_minmax_points.png')) utils.plot.draw_hist(beat_info['dur'], FS, 'dash&dot', INTERACTIVE, save_to=utils.plot_filepath(PLOTS_DIR, 'beats_hist.png')) utils.plot.draw_hist(null_info['dur'], FS, 'null', INTERACTIVE, save_to=utils.plot_filepath(PLOTS_DIR, 'nulls_hist.png')) peak_filtered = beat_info[beat_info['dur'] / FS > 0.01] peak_points_x, peak_points_y = peak_filtered['p_mid'], peak_filtered[ 'ampl_extr'] peak_tck = interpolate.splrep(peak_points_x, peak_points_y) tl = utils.process.time_labels_interval(wave_file, SECONDS, len(ampl_sm)) def interp(n_point): return interpolate.splev(n_point, peak_tck) ip = np.vectorize(interp) max_inter = ip(np.arange(0, len(tl))) low_filtered = null_info[null_info['dur'] / FS > 0.1] low_points_x, low_points_y = low_filtered['p_mid'], low_filtered[ 'ampl_extr'] low_tck = interpolate.splrep(low_points_x, low_points_y) def interp(n_point): return interpolate.splev(n_point, low_tck) il = np.vectorize(interp) min_inter = il(np.arange(0, len(tl))) plt.plot(tl, ampl_sm) plt.plot(tl, max_inter, 'r') plt.plot(SECONDS[0] + (peak_points_x / FS), peak_points_y, 'rx') plt.plot(tl, min_inter, 'k') plt.plot(SECONDS[0] + (low_points_x / FS), low_points_y, 'kx') plt.plot(tl, (min_inter + max_inter) / 2, 'm') plt.gcf().set_size_inches(15, 5) plt.gca().set_xlim(*SECONDS) if INTERACTIVE: plt.show() else: fn = utils.plot_filepath(PLOTS_DIR, 'full_step_one.png') plt.savefig(fn, dpi=100) plt.close() di = beat_info['dur'] idi = di[di > 100] # beat_len_delta, desired_bin_width = idi.max() - idi.min(), 30 # np.histogram(idi, bins=(int(beat_len_delta / desired_bin_width))) dots, dashes = idi[idi < idi.mean()], idi[idi > idi.mean()] reg = LinearRegression().fit( np.array(len(dots) * [1] + len(dashes) * [3]).reshape(-1, 1), np.concatenate( [np.array(dots).astype(np.int), np.array(dashes).astype(np.int)])) r1_dur, dot_len, r2_dur = reg.predict([[0.], [1.], [3.5]]) plt.plot(len(dots) * [1], dots) plt.plot(len(dashes) * [3], dashes) plt.plot([0, 3.5], [r1_dur, r2_dur]) plt.gca().set_xlim(0, 3.5) plt.gca().set_ylim(0, 3000) if INTERACTIVE: plt.show() else: fn = utils.plot_filepath(PLOTS_DIR, 'durations_regr.png') plt.savefig(fn, dpi=100) plt.close() # noinspection PyTypeChecker nnb_inter = utils.process.sign_series(discr_step_one) result = utils.process.predict(nnb_inter, dot_len) print(result)
def lcplot(snid='colfax', yunits='flux', snfitres=None): from matplotlib import pyplot as pl, ticker from pytools import plotsetup, colorpalette as cp import time start = time.time() if snfitres is not None: sn, fit, res = snfitres else: sn, fit, res = dofitIa(snid) if snid == 'bush': snid = 'GSD11Bus' ymax = 0.8 labelcorner = 'upper right' elif snid == 'colfax': snid = 'GND12Col' ymax = 0.7 labelcorner = 'upper right' elif snid == 'stone': snid = 'GND13Sto' ymax = 1.2 labelcorner = 'upper right' else: ymax = 1.2 labelcorner = 'upper right' # optbands = ['f350lp','f606w','f814w','f850lp'] allbands = np.unique(sn['filter']) broadbands = [ band for band in allbands if band in ['f105w', 'f125w', 'f140w', 'f160w'] ] nax = len(broadbands) medbanddict = { 'f105w': 'f098m', 'f125w': 'f127m', 'f140w': 'f139m', 'f160w': 'f153m' } bands = sn['filter'] markers = ['^', 'o', 's', 'd'] colors = [cp.purple, cp.bluegray, cp.darkgreen, cp.red] mjd = sn['mjd'] mag = sn['mag'] magerr = sn['magerr'] flux = sn['flux'] * 10**(-0.4 * (sn['zpt'] - 25)) fluxerr = sn['fluxerr'] * 10**(-0.4 * (sn['zpt'] - 25)) plotsetup.fullpaperfig(2, [8, 3]) pl.clf() fig = pl.gcf() mjdmin = mjd.min() - 10 mjdmax = mjd.max() + 25 mjdmod = np.arange(mjdmin, mjdmax, 1) z = res['parameters'][res['param_names'].index('z')] mjdpeak = res['parameters'][res['param_names'].index('t0')] trestmin = (mjdmin - mjdpeak) / (1 + z) trestmax = (mjdmax - mjdpeak) / (1 + z) iax = 0 for bb, marker, color in zip(broadbands, markers, colors): t1 = time.time() iax += 1 ibb = np.where(bands == bb) mb = medbanddict[bb] imb = np.where(bands == mb) if iax == 1: ax = fig.add_subplot(1, nax, iax) ax1 = ax axtop = ax.twiny() ax1.text(-0.3, 1.22, snid, color='k', fontsize='large', fontweight='heavy', ha='left', va='top', transform=ax.transAxes) elif iax == 2: ax = fig.add_subplot(1, nax, iax, sharex=ax1, sharey=ax1) axtop = ax.twiny() axtop.set_xlabel('rest frame time (days from peak)') ax.set_xlabel('observer frame time (MJD)') pl.setp(ax.get_yticklabels(), visible=False) elif iax == nax: ax = fig.add_subplot(1, nax, iax, sharex=ax1, sharey=ax1) axtop = ax.twiny() ax.yaxis.set_ticks_position('right') ax.yaxis.set_ticks_position('both') else: ax = fig.add_subplot(1, nax, iax, sharex=ax1, sharey=ax1) axtop = ax.twiny() pl.setp(ax.get_yticklabels(), visible=False) if yunits == 'mag': yval = mag yerr = magerr ymod_bb = fit.bandmag(bb, 'ab', mjdmod) ymod_mb = fit.bandmag(mb, 'ab', mjdmod) if iax == 1: ax.set_ylabel('AB mag') # ax.set_ylim( 30.6, 25.2 ) else: yval = flux yerr = fluxerr ymod_bb = fit.bandflux(bb, mjdmod, zp=25, zpsys='ab') ymod_mb = fit.bandflux(mb, mjdmod, zp=25, zpsys='ab') if iax == 1: ax.set_ylabel('flux (zp$_{AB}$=25)') ax.set_ylim(-0.09, ymax) ax.plot(mjdmod, ymod_bb, marker=None, color='0.5', ls='-', zorder=-10) ax.errorbar(mjd[ibb], yval[ibb], yerr[ibb], ms=8, marker='o', color=color, mfc=color, mec=color, capsize=0, ls=' ', zorder=10) if mb in allbands: ax.plot(mjdmod, ymod_mb, marker=None, color='0.5', ls='--', zorder=-10) ax.errorbar(mjd[imb], yval[imb], yerr[imb], ms=9, marker='o', color='k', mfc='w', mec='k', capsize=0, ls=' ', alpha=0.5, zorder=20) if labelcorner == 'lower right': ax.text(0.92, 0.42, '%s' % (bb.upper()), color=color, fontsize='medium', fontweight='heavy', ha='right', va='top', transform=ax.transAxes) if mb in allbands: ax.text(0.92, 0.32, '%s' % (mb.upper()), color='k', fontsize='medium', fontweight='heavy', ha='right', va='top', transform=ax.transAxes) elif labelcorner == 'upper left': ax.text(0.08, 0.92, '%s' % (bb.upper()), color=color, fontsize='medium', fontweight='heavy', ha='left', va='top', transform=ax.transAxes) if mb in allbands: ax.text(0.08, 0.82, '%s' % (mb.upper()), color='k', fontsize='medium', fontweight='heavy', ha='left', va='top', transform=ax.transAxes) if labelcorner == 'upper right': ax.text(0.92, 0.92, '%s' % (bb.upper()), color=color, fontsize='medium', fontweight='heavy', ha='right', va='top', transform=ax.transAxes) if mb in allbands: ax.text(0.92, 0.82, '%s' % (mb.upper()), color='k', fontsize='medium', fontweight='heavy', ha='right', va='top', transform=ax.transAxes) ax.set_xlim(mjdmin, mjdmax) axtop.set_xlim(trestmin, trestmax) ax.xaxis.set_major_locator(ticker.MultipleLocator(100)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(20)) axtop.xaxis.set_major_locator(ticker.MultipleLocator(20)) axtop.xaxis.set_minor_locator(ticker.MultipleLocator(5)) ax.yaxis.set_major_locator(ticker.MultipleLocator(0.2)) ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.1)) for tick in axtop.get_xaxis().get_major_ticks(): tick.set_pad(5.) tick.label1 = tick._get_text1() t2 = time.time() print("%s %.1f %.1f " % (bb.upper(), t2 - start, t2 - t1)) fig.subplots_adjust(left=0.1, bottom=0.18, right=0.95, top=0.82, wspace=0., hspace=0.15) pl.draw() t3 = time.time() print("All %.1f" % (t3 - start))
plt.title('Bstem Project') #Setting the title plt.xlabel('x label') plt.ylabel('y label') readFile = open('newdata.txt', 'r') sepFile = readFile.read().split('\n') readFile.close() for plotpair in sepFile: XANDY = plotpair.split(',') if len(XANDY) > 1: x.append(int(float(XANDY[0]))) y.append(int(float(XANDY[1]))) #plt.clf() plt.plot([x], [y], 'o', color='blue') plt.plot([x[0]], [y[0]], 'o', color='red') #for i in range (82): # plt.plot(i,0,'o',color='green') def quit_figure(event): if event.key == 'q': plt.close(event.canvas.figure) cid = plt.gcf().canvas.mpl_connect('key_press_event', quit_figure) plt.show() #plt.close(im)
def makeMovie(fname, env, poses, linkLength): ani = animation.FuncAnimation(plt.gcf(), drawPose, \ fargs=(env, poses, linkLength), frames=poses.shape[0], \ blit=True) ani.save(fname, bitrate=300, fps=20)
def add_stat_annotation(ax, plot='boxplot', data=None, x=None, y=None, hue=None, units=None, order=None, hue_order=None, box_pairs=None, width=0.8, perform_stat_test=True, pvalues=None, test_short_name=None, test=None, text_format='star', pvalue_format_string=DEFAULT, text_annot_custom=None, loc='inside', show_test_name=True, pvalue_thresholds=DEFAULT, stats_params=dict(), comparisons_correction='bonferroni', use_fixed_offset=False, line_offset_to_box=None, line_offset=None, line_height=0.02, text_offset=1, color='0.2', linewidth=1.5, fontsize='medium', verbose=1): """ Optionally computes statistical test between pairs of data series, and add statistical annotation on top of the boxes/bars. The same exact arguments `data`, `x`, `y`, `hue`, `order`, `width`, `hue_order` (and `units`) as in the seaborn boxplot/barplot function must be passed to this function. This function works in one of the two following modes: a) `perform_stat_test` is True: statistical test as given by argument `test` is performed. b) `perform_stat_test` is False: no statistical test is performed, list of custom p-values `pvalues` are used for each pair of boxes. The `test_short_name` argument is then used as the name of the custom statistical test. :param plot: type of the plot, one of 'boxplot' or 'barplot'. :param line_height: in axes fraction coordinates :param text_offset: in points :param box_pairs: can be of either form: For non-grouped boxplot: `[(cat1, cat2), (cat3, cat4)]`. For boxplot grouped by hue: `[((cat1, hue1), (cat2, hue2)), ((cat3, hue3), (cat4, hue4))]` :param pvalue_format_string: defaults to `"{.3e}"` :param pvalue_thresholds: list of lists, or tuples. Default is: For "star" text_format: `[[1e-4, "****"], [1e-3, "***"], [1e-2, "**"], [0.05, "*"], [1, "ns"]]`. For "simple" text_format : `[[1e-5, "1e-5"], [1e-4, "1e-4"], [1e-3, "0.001"], [1e-2, "0.01"]]` :param pvalues: list or array of p-values for each box pair comparison. :param comparisons_correction: Method for multiple comparisons correction. `bonferroni` or None. """ def find_x_position_box(box_plotter, boxName): """ boxName can be either a name "cat" or a tuple ("cat", "hue") """ if box_plotter.plot_hues is None: cat = boxName hue_offset = 0 else: cat = boxName[0] hue = boxName[1] hue_offset = box_plotter.hue_offsets[box_plotter.hue_names.index( hue)] group_pos = box_plotter.group_names.index(cat) box_pos = group_pos + hue_offset return box_pos def get_box_data(box_plotter, boxName): """ boxName can be either a name "cat" or a tuple ("cat", "hue") Here we really have to duplicate seaborn code, because there is not direct access to the box_data in the BoxPlotter class. """ cat = box_plotter.plot_hues is None and boxName or boxName[0] index = box_plotter.group_names.index(cat) group_data = box_plotter.plot_data[index] if box_plotter.plot_hues is None: # Draw a single box or a set of boxes # with a single level of grouping box_data = remove_na(group_data) else: hue_level = boxName[1] hue_mask = box_plotter.plot_hues[index] == hue_level box_data = remove_na(group_data[hue_mask]) return box_data # Set default values if necessary if pvalue_format_string is DEFAULT: pvalue_format_string = '{:.3e}' simple_format_string = '{:.2f}' else: simple_format_string = pvalue_format_string if pvalue_thresholds is DEFAULT: if text_format == "star": pvalue_thresholds = [[1e-4, "****"], [1e-3, "***"], [1e-2, "**"], [0.05, "*"], [1, "ns"]] else: pvalue_thresholds = [[1e-5, "1e-5"], [1e-4, "1e-4"], [1e-3, "0.001"], [1e-2, "0.01"]] fig = plt.gcf() # Validate arguments if perform_stat_test: if test is None: raise ValueError( "If `perform_stat_test` is True, `test` must be specified.") if pvalues is not None or test_short_name is not None: raise ValueError( "If `perform_stat_test` is True, custom `pvalues` " "or `test_short_name` must be `None`.") valid_list = [ 't-test_ind', 't-test_welch', 't-test_paired', 'Mann-Whitney', 'Mann-Whitney-gt', 'Mann-Whitney-ls', 'Levene', 'Wilcoxon', 'Kruskal' ] if test not in valid_list: raise ValueError( "test value should be one of the following: {}.".format( ', '.join(valid_list))) else: if pvalues is None: raise ValueError( "If `perform_stat_test` is False, custom `pvalues` must be specified." ) if test is not None: raise ValueError( "If `perform_stat_test` is False, `test` must be None.") if len(pvalues) != len(box_pairs): raise ValueError( "`pvalues` should be of the same length as `box_pairs`.") if text_annot_custom is not None and len(text_annot_custom) != len( box_pairs): raise ValueError( "`text_annot_custom` should be of same length as `box_pairs`.") assert_is_in(loc, ['inside', 'outside'], label='argument `loc`') assert_is_in(text_format, ['full', 'simple', 'star'], label='argument `text_format`') assert_is_in(comparisons_correction, ['bonferroni', None], label='argument `comparisons_correction`') if verbose >= 1 and text_format == 'star': print("p-value annotation legend:") pvalue_thresholds = pd.DataFrame(pvalue_thresholds).sort_values( by=0, ascending=False).values for i in range(0, len(pvalue_thresholds)): if i < len(pvalue_thresholds) - 1: print('{}: {:.2e} < p <= {:.2e}'.format( pvalue_thresholds[i][1], pvalue_thresholds[i + 1][0], pvalue_thresholds[i][0])) else: print('{}: p <= {:.2e}'.format(pvalue_thresholds[i][1], pvalue_thresholds[i][0])) print() ylim = ax.get_ylim() yrange = ylim[1] - ylim[0] if line_offset is None: if loc == 'inside': line_offset = 0.05 if line_offset_to_box is None: line_offset_to_box = 0.06 # 'outside', see valid_list else: line_offset = 0.03 if line_offset_to_box is None: line_offset_to_box = line_offset else: if loc == 'inside': if line_offset_to_box is None: line_offset_to_box = 0.06 elif loc == 'outside': line_offset_to_box = line_offset y_offset = line_offset * yrange y_offset_to_box = line_offset_to_box * yrange if plot == 'boxplot': # Create the same plotter object as seaborn's boxplot box_plotter = sns.categorical._BoxPlotter(x, y, hue, data, order, hue_order, orient=None, width=width, color=None, palette=None, saturation=.75, dodge=True, fliersize=5, linewidth=None) elif plot == 'barplot': # Create the same plotter object as seaborn's barplot box_plotter = sns.categorical._BarPlotter(x, y, hue, data, order, hue_order, estimator=np.mean, ci=95, n_boot=1000, units=None, orient=None, color=None, palette=None, saturation=.75, errcolor=".26", errwidth=None, capsize=None, dodge=True) # Build the list of box data structures with the x and ymax positions group_names = box_plotter.group_names hue_names = box_plotter.hue_names if box_plotter.plot_hues is None: box_names = group_names labels = box_names else: box_names = [(group_name, hue_name) for group_name in group_names for hue_name in hue_names] labels = [ '{}_{}'.format(group_name, hue_name) for (group_name, hue_name) in box_names ] box_structs = [{ 'box': box_names[i], 'label': labels[i], 'x': find_x_position_box(box_plotter, box_names[i]), 'box_data': get_box_data(box_plotter, box_names[i]), 'ymax': np.amax(get_box_data(box_plotter, box_names[i])) if len(get_box_data(box_plotter, box_names[i])) > 0 else np.nan } for i in range(len(box_names))] # Sort the box data structures by position along the x axis box_structs = sorted(box_structs, key=lambda x: x['x']) # Add the index position in the list of boxes along the x axis box_structs = [ dict(box_struct, xi=i) for i, box_struct in enumerate(box_structs) ] # Same data structure list with access key by box name box_structs_dic = { box_struct['box']: box_struct for box_struct in box_structs } # Build the list of box data structure pairs box_struct_pairs = [] for i_box_pair, (box1, box2) in enumerate(box_pairs): if box1 not in box_names or box2 not in box_names: raise ValueError( f"box_pairs contains an invalid box pair, expected {box1 if not box1 in box_names else box2} in {box_names}" ) # i_box_pair will keep track of the original order of the box pairs. box_struct1 = dict(box_structs_dic[box1], i_box_pair=i_box_pair) box_struct2 = dict(box_structs_dic[box2], i_box_pair=i_box_pair) if box_struct1['x'] <= box_struct2['x']: pair = (box_struct1, box_struct2) else: pair = (box_struct2, box_struct1) box_struct_pairs.append(pair) # Draw first the annotations with the shortest between-boxes distance, in order to reduce # overlapping between annotations. box_struct_pairs = sorted(box_struct_pairs, key=lambda x: abs(x[1]['x'] - x[0]['x'])) # Build array that contains the x and y_max position of the highest annotation or box data at # a given x position, and also keeps track of the number of stacked annotations. # This array will be updated when a new annotation is drawn. y_stack_arr = np.array([[box_struct['x'] for box_struct in box_structs], [box_struct['ymax'] for box_struct in box_structs], [0 for i in range(len(box_structs))]]) if loc == 'outside': y_stack_arr[1, :] = ylim[1] ann_list = [] test_result_list = [] ymaxs = [] y_stack = [] for box_struct1, box_struct2 in box_struct_pairs: box1 = box_struct1['box'] box2 = box_struct2['box'] label1 = box_struct1['label'] label2 = box_struct2['label'] box_data1 = box_struct1['box_data'] box_data2 = box_struct2['box_data'] x1 = box_struct1['x'] x2 = box_struct2['x'] xi1 = box_struct1['xi'] xi2 = box_struct2['xi'] ymax1 = box_struct1['ymax'] ymax2 = box_struct2['ymax'] i_box_pair = box_struct1['i_box_pair'] # Find y maximum for all the y_stacks *in between* the box1 and the box2 i_ymax_in_range_x1_x2 = xi1 + np.nanargmax( y_stack_arr[1, np.where((x1 <= y_stack_arr[0, :]) & (y_stack_arr[0, :] <= x2))]) ymax_in_range_x1_x2 = y_stack_arr[1, i_ymax_in_range_x1_x2] if perform_stat_test: result = stat_test(box_data1, box_data2, test, comparisons_correction, len(box_struct_pairs), **stats_params) else: test_short_name = test_short_name if test_short_name is not None else '' result = StatResult('Custom statistical test', test_short_name, None, None, pvalues[i_box_pair]) result.box1 = box1 result.box2 = box2 test_result_list.append(result) if verbose >= 1: print("{} v.s. {}: {}".format(label1, label2, result.formatted_output)) if text_annot_custom is not None: text = text_annot_custom[i_box_pair] else: if text_format == 'full': text = "{} p = {}".format('{}', pvalue_format_string).format( result.test_short_name, result.pval) elif text_format is None: text = None elif text_format is 'star': text = pval_annotation_text(result.pval, pvalue_thresholds) elif text_format is 'simple': test_short_name = show_test_name and test_short_name or "" text = simple_text(result.pval, simple_format_string, pvalue_thresholds, test_short_name) yref = ymax_in_range_x1_x2 yref2 = yref # Choose the best offset depending on wether there is an annotation below # at the x position in the range [x1, x2] where the stack is the highest if y_stack_arr[2, i_ymax_in_range_x1_x2] == 0: # there is only a box below offset = y_offset_to_box else: # there is an annotation below offset = y_offset y = yref2 + offset h = line_height * yrange line_x, line_y = [x1, x1, x2, x2], [y, y + h, y + h, y] if loc == 'inside': ax.plot(line_x, line_y, lw=linewidth, c=color) elif loc == 'outside': line = lines.Line2D(line_x, line_y, lw=linewidth, c=color, transform=ax.transData) line.set_clip_on(False) ax.add_line(line) # why should we change here the ylim if at the very end we set it to the correct range???? # ax.set_ylim((ylim[0], 1.1*(y + h))) if text is not None: ann = ax.annotate(text, xy=(np.mean([x1, x2]), y + h), xytext=(0, text_offset), textcoords='offset points', xycoords='data', ha='center', va='bottom', fontsize=fontsize, clip_on=False, annotation_clip=False) ann_list.append(ann) plt.draw() y_top_annot = None got_mpl_error = False if not use_fixed_offset: try: bbox = ann.get_window_extent() bbox_data = bbox.transformed(ax.transData.inverted()) y_top_annot = bbox_data.ymax except RuntimeError: got_mpl_error = True if use_fixed_offset or got_mpl_error: if verbose >= 1: print( "Warning: cannot get the text bounding box. Falling back to a fixed" " y offset. Layout may be not optimal.") # We will apply a fixed offset in points, # based on the font size of the annotation. fontsize_points = FontProperties( size='medium').get_size_in_points() offset_trans = mtransforms.offset_copy( ax.transData, fig=fig, x=0, y=1.0 * fontsize_points + text_offset, units='points') y_top_display = offset_trans.transform((0, y + h)) y_top_annot = ax.transData.inverted().transform( y_top_display)[1] else: y_top_annot = y + h y_stack.append( y_top_annot ) # remark: y_stack is not really necessary if we have the stack_array ymaxs.append(max(y_stack)) # Fill the highest y position of the annotation into the y_stack array # for all positions in the range x1 to x2 y_stack_arr[1, (x1 <= y_stack_arr[0, :]) & (y_stack_arr[0, :] <= x2)] = y_top_annot # Increment the counter of annotations in the y_stack array y_stack_arr[2, xi1:xi2 + 1] = y_stack_arr[2, xi1:xi2 + 1] + 1 y_stack_max = max(ymaxs) if loc == 'inside': ax.set_ylim((ylim[0], max(1.03 * y_stack_max, ylim[1]))) elif loc == 'outside': ax.set_ylim((ylim[0], ylim[1])) return ax, test_result_list
def test_polar(): ax = plt.subplot(111, polar=True) fig = plt.gcf() pf = pickle.dumps(fig) pickle.loads(pf) plt.draw()
def make_velocity_plots(fdir, u, mask, sfx): """Make some plots of velocity and velocity magnitude""" names = ["u", "v", "umag"] nlevels = 10 min_plt = [-0.4, -1] max_plt = [1.5, 1] xbnd = [-2.0, 15.0] ybnd = [-4.258317025440313, 4.258317025440313] extent = [xbnd[0], xbnd[1], ybnd[0], ybnd[1]] cmap = cm.RdBu_r for k in range(len(u)): data = np.ma.masked_where(mask < 0.5, u[k]) fig, ax = plt.subplots(1) ax.cla() ax.set_aspect("equal") img = ax.imshow( data.data, cmap=cmap, extent=extent, vmin=min_plt[k], vmax=max_plt[k] ) add_colorbar(img) ax.contour( data.data, nlevels, colors="k", extent=extent, linewidths=0.5, linestyles="solid", ) coll = PatchCollection( [patches.Circle((0, 0), 0.5, linewidth=1, color="w", ec=None, fc="w")], zorder=10, match_original=True, ) ax.add_collection(coll) plt.xlabel(r"$x / D$", fontsize=22, fontweight="bold") plt.ylabel(r"$y / D$", fontsize=22, fontweight="bold") plt.setp(ax.get_xmajorticklabels(), fontsize=18, fontweight="bold") plt.setp(ax.get_ymajorticklabels(), fontsize=18, fontweight="bold") plt.gcf().subplots_adjust(bottom=0.15) plt.savefig( os.path.join(fdir, "{0:s}{1:s}.png".format(names[k], sfx)), format="png", dpi=300, bbox_inches="tight", ) fig, ax = plt.subplots(1) ax.cla() ax.set_aspect("equal") cmap.set_bad(color="black") img = ax.imshow( data, cmap=cmap, extent=extent, vmin=min_plt[k], vmax=max_plt[k] ) add_colorbar(img) coll = PatchCollection( [patches.Circle((0, 0), 0.5, linewidth=1, color="w", ec=None, fc="w")], zorder=10, match_original=True, ) ax.add_collection(coll) plt.xlabel(r"$x / D$", fontsize=22, fontweight="bold") plt.ylabel(r"$y / D$", fontsize=22, fontweight="bold") plt.setp(ax.get_xmajorticklabels(), fontsize=18, fontweight="bold") plt.setp(ax.get_ymajorticklabels(), fontsize=18, fontweight="bold") plt.gcf().subplots_adjust(bottom=0.15) plt.savefig( os.path.join(fdir, "{0:s}{1:s}_masked.png".format(names[k], sfx)), format="png", dpi=300, bbox_inches="tight", ) umag = np.sqrt(sum(map(lambda x: x * x, u))) data = np.ma.masked_where(mask < 0.5, umag) cmap = cm.viridis max_plt = 1.5 fig, ax = plt.subplots(1) ax.cla() ax.set_aspect("equal") img = ax.imshow(data.data, cmap=cmap, extent=extent, vmin=0, vmax=max_plt) add_colorbar(img) plt.contour( data.data, nlevels, colors="k", extent=extent, linewidths=0.5, linestyles="solid", ) coll = PatchCollection( [patches.Circle((0, 0), 0.5, linewidth=1, color="w", ec=None, fc="w")], zorder=10, match_original=True, ) ax.add_collection(coll) plt.xlabel(r"$x / D$", fontsize=22, fontweight="bold") plt.ylabel(r"$y / D$", fontsize=22, fontweight="bold") plt.setp(ax.get_xmajorticklabels(), fontsize=18, fontweight="bold") plt.setp(ax.get_ymajorticklabels(), fontsize=18, fontweight="bold") plt.gcf().subplots_adjust(bottom=0.15) plt.savefig( os.path.join(fdir, "{0:s}{1:s}.png".format(names[-1], sfx)), format="png", dpi=300, bbox_inches="tight", ) fig, ax = plt.subplots(1) ax.cla() ax.set_aspect("equal") cmap = cm.viridis cmap.set_bad(color="black") img = ax.imshow(data, cmap="viridis", extent=extent, vmin=0, vmax=max_plt) add_colorbar(img) coll = PatchCollection( [patches.Circle((0, 0), 0.5, linewidth=1, color="w", ec=None, fc="w")], zorder=10, match_original=True, ) ax.add_collection(coll) plt.xlabel(r"$x / D$", fontsize=22, fontweight="bold") plt.ylabel(r"$y / D$", fontsize=22, fontweight="bold") plt.setp(ax.get_xmajorticklabels(), fontsize=18, fontweight="bold") plt.setp(ax.get_ymajorticklabels(), fontsize=18, fontweight="bold") plt.gcf().subplots_adjust(bottom=0.15) plt.savefig( os.path.join(fdir, "{0:s}{1:s}_masked.png".format(names[-1], sfx)), format="png", dpi=300, bbox_inches="tight", ) plt.close("all")
def test_empty_layout(): """Test that tight layout doesn't cause an error when there are no axes.""" fig = plt.gcf() fig.tight_layout()
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("autoscout_datasucker_stat_2.csv", sep=";", usecols=["model", "make", "run_time", "images", "errors"]) df = df.groupby("make").sum() df = df.sort_values(by=['images'], ascending=False) df = df.head(10) labels = df.index.tolist() img = df["images"].tolist() plt.bar(labels, df["images"], label="Num. of images") plt.plot(df["run_time"], 'y', label="Run time in sec") plt.plot(df["errors"], 'r', label="Errors") plt.legend() plt.xticks(rotation=90) plt.gcf().subplots_adjust(bottom=0.3) plt.show()
color=line_color3, label=curve_text3, linewidth=curve_linewidth, markersize=20) left_axis.plot(plot_data[:, 0], plot_data[:, 9], marker='o', color=line_color4, label=curve_text4, linewidth=curve_linewidth, markersize=20) left_axis.legend( loc=legend_location, fontsize=legend_font) #legend needs to be after all the plot data plot.get_current_fig_manager().resize(width, height) plot.gcf().set_size_inches((0.01 * width), (0.01 * height)) # ####### # # save # plot.savefig(title, dpi=current_dpi) # ####### # # plot to screen # plot.show() # ######################################################################## #
def plot_roc( context, y_labels, y_probs, key="roc", plots_dir: str = "plots", fmt="png", fpr_label: str = "false positive rate", tpr_label: str = "true positive rate", title: str = "roc curve", legend_loc: str = "best", clear: bool = True, ): """plot roc curves **legacy version please deprecate in functions and demos** :param context: the function context :param y_labels: ground truth labels, hot encoded for multiclass :param y_probs: model prediction probabilities :param key: ("roc") key of plot in artifact store :param plots_dir: ("plots") destination folder relative path to artifact path :param fmt: ("png") plot format :param fpr_label: ("false positive rate") x-axis labels :param tpr_label: ("true positive rate") y-axis labels :param title: ("roc curve") title of plot :param legend_loc: ("best") location of plot legend :param clear: (True) clear the matplotlib figure before drawing """ # clear matplotlib current figure if clear: gcf_clear(plt) # draw 45 degree line plt.plot([0, 1], [0, 1], "k--") # labelling plt.xlabel(fpr_label) plt.ylabel(tpr_label) plt.title(title) plt.legend(loc=legend_loc) # single ROC or multiple if y_labels.shape[1] > 1: # data accumulators by class fpr = dict() tpr = dict() roc_auc = dict() for i in range(y_labels[:, :-1].shape[1]): fpr[i], tpr[i], _ = metrics.roc_curve( y_labels[:, i], y_probs[:, i], pos_label=1 ) roc_auc[i] = metrics.auc(fpr[i], tpr[i]) plt.plot(fpr[i], tpr[i], label=f"class {i}") else: fpr, tpr, _ = metrics.roc_curve(y_labels, y_probs[:, 1], pos_label=1) plt.plot(fpr, tpr, label="positive class") fname = f"{plots_dir}/{key}.html" return context.log_artifact(PlotArtifact(key, body=plt.gcf()), local_path=fname)
plt.errorbar( mean_error.index, mean_error.ui_merror, # yerr=std_error.ui_merror, color=cmap[1], mec=cmap[1], mfc=cmap[1], marker=markertype[1], ms=10, capsize=3, ) plt.xlabel(r"$L_m / D$", fontsize=22, fontweight="bold") plt.ylabel(r"$L_2(u)$", fontsize=22, fontweight="bold") plt.setp(ax.get_xmajorticklabels(), fontsize=18, fontweight="bold") plt.setp(ax.get_ymajorticklabels(), fontsize=18, fontweight="bold") plt.gcf().subplots_adjust(bottom=0.14) plt.gcf().subplots_adjust(left=0.16) plt.savefig( os.path.join(odir, "cyl_error_u.{0:s}".format(fmt)), format=fmt, dpi=300 ) plt.figure(1) ax = plt.gca() plt.errorbar( mean_error.index, mean_error.vr_merror, # yerr=std_error.vr_merror, color=cmap[0], mec=cmap[0], mfc=cmap[0], marker=markertype[0],