def __init__(self, top, mid1, mid2, mid3, bottom): """ Shows a given array in a 2d-viewer. Input: 2d arrays. For each slice level selected Also where the buttons on the viewer are added """ self.top = top self.fig = plt.figure(figsize=(12, 8)) #Doing some layout with subplots: self.fig.subplots_adjust(0.05, 0.05, 0.98, 0.98, 0.1) self.top_im = plt.subplot2grid((7, 2), (0, 0), rowspan=1, colspan=2) self.top_im.imshow(self.top) self.top_im.autoscale(1, 'both', 1) self.mid1 = mid1 self.mid1_im = plt.subplot2grid((7, 2), (1, 0), rowspan=1, colspan=2) self.mid1_im.imshow(self.mid1) self.mid1_im.autoscale(1, 'both', 1) self.mid2 = mid2 self.mid2_im = plt.subplot2grid((7, 2), (2, 0), rowspan=1, colspan=2) self.mid2_im.imshow(self.mid2) self.mid2_im.autoscale(1, 'both', 1) self.mid3 = mid3 self.mid3_im = plt.subplot2grid((7, 2), (3, 0), rowspan=1, colspan=2) self.mid3_im.imshow(self.mid3) self.mid3_im.autoscale(1, 'both', 1) self.bottom = bottom self.bottom_im = plt.subplot2grid((7, 2), (4, 0), rowspan=1, colspan=2) self.bottom_im.imshow(self.bottom) self.bottom_im.autoscale(1, 'both', 1) # internal storage for coordinates self.top_list = [] self.mid1_list = [] self.mid2_list = [] self.mid3_list = [] self.bottom_list = [] self.last = None self.cell_number = 1 #Adding widgets, to not be gc'ed, they are put in a list: top_cursor = Cursor(self.top_im, useblit=True, color='black', linewidth=2) mid1_cursor = Cursor(self.mid1_im, useblit=True, color='black', linewidth=2) mid2_cursor = Cursor(self.mid2_im, useblit=True, color='black', linewidth=2) mid3_cursor = Cursor(self.mid3_im, useblit=True, color='black', linewidth=2) bottom_cursor = Cursor(self.bottom_im, useblit=True, color='black', linewidth=2) but_ax = plt.subplot2grid((7, 3), (5, 0), colspan=1) undo_button = Button(but_ax, 'Undo') but_ax2 = plt.subplot2grid((7, 3), (5, 2), colspan=1) save_button = Button(but_ax2, 'Save') but_ax3 = plt.subplot2grid((7, 3), (5, 1), colspan=1) next_button = Button(but_ax3, 'Next Cell') self._widgets = [ top_cursor, bottom_cursor, mid1_cursor, mid2_cursor, mid3_cursor, undo_button, save_button, next_button ] # connect events undo_button.on_clicked(self.delete_last) save_button.on_clicked(self.save) next_button.on_clicked(self.next_cell) self.fig.canvas.mpl_connect('button_press_event', self.click)
def open_file(self, event=None, filename=''): """ Get the image """ # ask for file if filename == '': filename = filedialog.askopenfilename( initialdir=os.getcwd(), title='Select Image File', filetypes=(('All', '*'), ('jpg', '*.jpg'), ('png', '*.png'), ('gif', '*.gif'))) # get file as np array self.img = mpimg.imread(filename) self.img = self.img[::-1] # make axes if not hasattr(self, 'ax'): self.ax = self.fig.add_subplot(111) self.toolbar.ax = self.ax self.toolbar.fig = self.fig self.cursor = Cursor(self.ax, useblit=True, color='red', linewidth=1, ls=':') else: self.ax.clear() self.ax.tick_params(axis='both', labelsize='small') # draw basic image self.ax.imshow(self.img, origin='lower') self.ax.set_aspect(1) self.fig.canvas.draw_idle() self.filename = filename # get limits of image xlim = self.ax.get_xlim() ylim = self.ax.get_xlim() xrng = xlim[1] - xlim[0] yrng = ylim[1] - ylim[0] self.xl_pix = xlim[0] + xrng * 0.1 self.xh_pix = xlim[1] - xrng * 0.1 self.yl_pix = ylim[0] + yrng * 0.1 self.yh_pix = ylim[1] - yrng * 0.1 self.x_slider_for_y = xlim[0] + xrng * 0.05 self.y_slider_for_x = ylim[0] + yrng * 0.05 # intialize self.xdata = [] self.ydata = [] # rescale axes for the first time self.set_lines() self.xh_img.set('1') self.xl_img.set('0') self.yh_img.set('1') self.yl_img.set('0') self.scale_axes() self.xh_img.set('') self.xl_img.set('') self.yh_img.set('') self.yl_img.set('') self.set_lines() # clear data self.clear_data() # set home view self.toolbar.update() # make sure scale button is correct self.button_scale['text'] = 'Scale Axes'
yf = butter_lowpass_filter(y, lcutoff, fs) yf = butter_highpass_filter(yf, hcutoff, fs) yfft = abs(ifft(y)) to = (len(yfft)/2) yfft = yfft[0:int(to)] yffft = abs(ifft(yf)) tof = (len(yffft)/2) yffft = yffft[0:int(tof)] fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(311) ax.plot(t, y, 'b-', label='data') cursor = Cursor(ax, useblit=True, color='red', linewidth=1) ax.plot(t, yf, 'g-', linewidth=2, label='filtered data') ax2 = fig.add_subplot(312) ax2.plot(yfft, 'b-', label='data') cursor2 = Cursor(ax2, useblit=True, color='red', linewidth=1) ax3 = fig.add_subplot(313) ax3.plot(yffft, 'g-', label='data') cursor3 = Cursor(ax3, useblit=True, color='red', linewidth=1) plt.show()
# Defino la figura fig, (ax1, ax2) = plt.subplots(figsize=(12, 4), ncols=2) # Mostramos la imagen como un mapa de grises ax1.imshow(img, cmap='gray', interpolation='nearest') ax1.axis('off') # Agrego la línea inicial en un valor inicial x0 = 100 l1 = ax1.axvline(x0, color='r', ls='--', lw=3) # Grafico de la derecha l2, = ax2.plot(img[:, x0], 'r-', lw=2, label='corte') ax2.set_ylim((0, ymax)) ax2.set_xlabel(u'posición en eje $y$ (pixels)') ax2.set_ylabel('Intensidad') ax2.legend(loc='best') fig.tight_layout() # Agrego el cursor y conecto la accion de presionar a la funcion click cursor = Cursor(ax1, horizOn=False, vertOn=True, useblit=True, color='blue', linewidth=1) fig.canvas.mpl_connect('button_press_event', seleccionar) plt.show()
def main(sta1, sta2, filterid, components, mov_stack=1, show=True, outfile=None, refilter=None, **kwargs): db = connect() maxlag = float(get_config(db, 'maxlag')) cc_sampling_rate = float(get_config(db, 'cc_sampling_rate')) start, end, datelist = build_movstack_datelist(db) if refilter: freqmin, freqmax = refilter.split(':') freqmin = float(freqmin) freqmax = float(freqmax) fig = plt.figure(figsize=(12, 9)) sta1 = sta1.replace('.', '_') sta2 = sta2.replace('.', '_') if sta2 >= sta1: pair = "%s:%s" % (sta1, sta2) print("New Data for %s-%s-%i-%i" % (pair, components, filterid, mov_stack)) nstack, stack_total = get_results(db, sta1, sta2, filterid, components, datelist, mov_stack, format="matrix") xextent = (date2num(start), date2num(end), -maxlag, maxlag) ax = plt.subplot(111) data = stack_total if refilter: for i, d in enumerate(data): data[i] = bandpass(data[i], freqmin, freqmax, cc_sampling_rate, zerophase=True) vmax = np.nanmax(data) * 0.9 plt.imshow(data.T, extent=xextent, aspect="auto", interpolation='none', origin='lower', cmap='seismic', vmin=-vmax, vmax=vmax) plt.ylabel("Lag Time (s)") plt.axhline(0, lw=0.5, c='k') plt.grid() # ax.xaxis.set_major_locator(DayLocator()) # ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) ax.xaxis.set_major_formatter(DateFormatter("%Y-%m-%d")) # ax.xaxis.set_minor_locator(DayLocator()) # ax.xaxis.set_minor_formatter(DateFormatter('%Y-%m-%d %H:%M')) for filterdb in get_filters(db, all=True): if filterid == filterdb.ref: low = float(filterdb.low) high = float(filterdb.high) break if "ylim" in kwargs: plt.ylim(kwargs["ylim"][0], kwargs["ylim"][1]) else: plt.ylim(-maxlag, maxlag) title = '%s : %s, %s, Filter %d (%.2f - %.2f Hz), Stack %d' % \ (sta1.replace('_', '.'), sta2.replace('_', '.'), components, filterid, low, high, mov_stack) if refilter: title += ", Re-filtered (%.2f - %.2f Hz)" % (freqmin, freqmax) plt.title(title) fig.autofmt_xdate() cursor = Cursor(ax, useblit=True, color='black', linewidth=1.2) if outfile: if outfile.startswith("?"): pair = pair.replace(':', '-') outfile = outfile.replace( '?', '%s-%s-f%i-m%i' % (pair, components, filterid, mov_stack)) outfile = "interferogram " + outfile print("output to:", outfile) plt.savefig(outfile) if show: plt.show()
for i, object_data in enumerate(objects_orig_shuffled[::-1]): object_data_scaled_y = object_data + i * wavefrom_offset line_input_data[num_ray - i - 1], = plt.plot( grid, object_data_scaled_y, color_line) plt.text(len(object_data_scaled_y) * 1.1, object_data_scaled_y[-1], str(num_ray - i), verticalalignment='center', fontsize=txt_font_size, horizontalalignment='center') # plt.gca().invert_yaxis() plt.yticks([]) # plt.xlabel('x') plt.ylabel('scaled intensity') # plt.tight_layout() cursor1 = Cursor(ax2, useblit=True, **lineprops) #plt.subplot2grid((plot_nrows, plot_ncols), (1, 2)) #plt.title("ordered process dataset") #plt.pcolormesh(objects_list_ordered, cmap='seismic') #plt.gca().invert_yaxis() # invert the y axis #plt.colorbar() # plt.xlabel("x") # plt.ylabel("original index") line_process_data = [0] * num_ray ax4 = plt.subplot2grid((plot_nrows, plot_ncols), (1, 3)) plt.title('ordered process dataset') for i, object_data in enumerate(objects_list_ordered[::-1]): object_data_scaled_y = object_data + i * wavefrom_offset line_process_data[num_ray - i - 1], = plt.plot( grid_half, object_data_scaled_y, 'k')
def __init__(self, filename="templates/nowwhat.png"): """ Initialized with filename of image file containing the equirectangular map data. """ self.filename = filename self.load_image() # Setup display: self.fig = plt.figure(1) self.ax = plt.subplot(111) plt.clf() plt.subplots_adjust(left=0.1, bottom=0.20) self.meridian = -90 self.parallel = 22.5 self.projection = "orthographic" self.parallels = 16 self.meridians = 16 self.setup_display() # Setup mouse interaction: self.click = self.hemisphere_axes.figure.canvas.mpl_connect( 'button_press_event', self.mouseclick) self.cursor = Cursor(self.hemisphere_axes, useblit=True, color='red', linewidth=1) # Setup axes: self.axes_step = plt.axes([0.13, 0.15, 0.60, 0.03]) self.axes_meridians = plt.axes([0.13, 0.10, 0.60, 0.03]) self.axes_parallels = plt.axes([0.13, 0.05, 0.60, 0.03]) self.update_axes = plt.axes([0.79, 0.095, 0.08, 0.04]) self.reset_axes = plt.axes([0.79, 0.05, 0.08, 0.04]) self.radio_axes = plt.axes([0.88, 0.05, 0.11, 0.15]) # Setup sliders: self.step = 22.5 self.slider_step = Slider(self.axes_step, 'Step', 0, 90, valinit=self.step, valfmt='%2.1f') self.slider_meridians = Slider(self.axes_meridians, 'Meridians', 0, 64, valinit=self.parallels, valfmt='%2d') self.slider_parallels = Slider(self.axes_parallels, 'Parallels', 0, 64, valinit=self.parallels, valfmt='%2d') self.slider_step.on_changed(self.update) self.slider_meridians.on_changed(self.update) self.slider_parallels.on_changed(self.update) # Setup button(s): self.update_button = Button(self.update_axes, 'Update') self.update_button.on_clicked(self.update_display) self.button = Button(self.reset_axes, 'Reset') self.button.on_clicked(self.reset) # Setup radio buttons: self.radio = RadioButtons(self.radio_axes, ('ortho', 'eq.dist', 'rect'), active=0) self.radio.on_clicked(self.set_mode) self.projections = {"ortho": ("orthographic", "ortho"), "eq.dist": ("equidistant", "aeqd"), "rect": ("rectangular", "cyl")} # Almost done: self.update() plt.show()
def womcatfinal(blue_data, red_data): """concatenate data with overlapping wavelength regions""" import numpy as np import math import logging import matplotlib.pyplot as plt from tmath.wombat.inputter import inputter from tmath.wombat.inputter_single import inputter_single from tmath.wombat.womget_element import womget_element from tmath.wombat.yesno import yesno from tmath.wombat.get_screen_size import get_screen_size from tmath.wombat.womwaverange2 import womwaverange2 from tmath.wombat import HOPSIZE from matplotlib.widgets import Cursor from tmath.wombat.womspectres import spectres plt.ion() screen_width, screen_height = get_screen_size() screenpos = '+{}+{}'.format(int(screen_width * 0.2), int(screen_height * 0.05)) fig = plt.figure() ax = fig.add_subplot(111) cursor = Cursor(ax, useblit=True, color='k', linewidth=1) fig.canvas.manager.window.wm_geometry(screenpos) fig.canvas.set_window_title('Cat') fig.set_size_inches(9, 6) # turns off key stroke interaction fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id) # print("\nThis will combine blue and red pieces from two hoppers\n") # hopnum1=0 # hopnum2=0 # while (hopnum1 < 1) or (hopnum1 > HOPSIZE): # hopnum1=inputter('Enter first hopper: ','int',False) # while (hopnum2 < 1) or (hopnum2 > HOPSIZE): # hopnum2=inputter('Enter second hopper: ','int',False) # if (hop[hopnum1].wave[0] > hop[hopnum2].wave[0]): # hopnum1,hopnum2=hopnum2,hopnum1 # wdelt1 = hop[hopnum1].wave[1]-hop[hopnum1].wave[0] # wdelt2 = hop[hopnum2].wave[1]-hop[hopnum2].wave[0] # # check if wavelength dispersion same # if (abs(wdelt1 - wdelt2) > 0.00001): # print('Spectra do not have same Angstrom/pixel') # print('Blue side: {}'.format(wdelt1)) # print('Red side: {}'.format(wdelt2)) # return hop # if hop[hopnum1].wave[-1] < hop[hopnum2].wave[0]: # print('Spectra do not overlap\n') # return hop # print("\nOverlap range is {} to {}".format(hop[hopnum2].wave[0], # hop[hopnum1].wave[-1])) # print("\nPlotting blue side as blue, red side as red\n") waveblue = np.asarray(blue_data[0]) fluxblue = np.asarray(blue_data[1]) varblue = np.asarray(blue_data[2]) wavered = np.asarray(red_data[0]) fluxred = np.asarray(red_data[1]) varred = np.asarray(red_data[2]) blue_dw = waveblue[1] - waveblue[0] red_dw = wavered[1] - wavered[0] if red_dw > blue_dw: print("Interpolating to {} A/pix".format(red_dw)) interp_wave = np.arange(math.ceil(waveblue[0]) + 1. * red_dw, math.floor(wavered[-1]) - 1. * red_dw, dtype=float, step=red_dw) blue_range = np.where((interp_wave >= waveblue[0] + 1. * red_dw) & (interp_wave <= waveblue[-1] - 1. * red_dw)) red_range = np.where((interp_wave >= wavered[0] + 1. * red_dw) & (interp_wave <= wavered[-1] - 1. * red_dw)) blue_interp = spectres(interp_wave[blue_range], waveblue, fluxblue, spec_errs=np.sqrt(varblue)) red_interp = spectres(interp_wave[red_range], wavered, fluxred, spec_errs=np.sqrt(varred)) waveblue = blue_interp[0] fluxblue = blue_interp[1] varblue = blue_interp[2]**2. wavered = red_interp[0] fluxred = red_interp[1] varred = red_interp[2]**2. else: print("Interpolating to {} A/pix".format(blue_dw)) interp_wave = np.arange(math.ceil(waveblue[0]) + 1. * blue_dw, math.floor(wavered[-1]) - 1. * blue_dw, dtype=float, step=blue_dw) blue_range = np.where((interp_wave >= waveblue[0] + 1 * blue_dw) & (interp_wave <= waveblue[-1] - 1 * blue_dw)) red_range = np.where((interp_wave >= wavered[0] + 1 * blue_dw) & (interp_wave <= wavered[-1] - 1 * blue_dw)) blue_interp = spectres(interp_wave[blue_range], waveblue, fluxblue, spec_errs=np.sqrt(varblue)) red_interp = spectres(interp_wave[red_range], wavered, fluxred, spec_errs=np.sqrt(varred)) waveblue = blue_interp[0] fluxblue = blue_interp[1] varblue = blue_interp[2]**2. wavered = red_interp[0] fluxred = red_interp[1] varred = red_interp[2]**2. indexblue = womget_element(waveblue, wavered[0]) indexred = womget_element(wavered, waveblue[-1]) fluxcor = 1.0 blue_mean = np.mean(fluxblue[indexblue:]) red_mean = np.mean(fluxred[0:indexred + 1]) if (blue_mean / red_mean < 0.8) or (blue_mean / red_mean > 1.2): fluxcor = blue_mean / red_mean print("Averages very different, scaling red to blue for plot") print("Red multiplied by {}".format(fluxcor)) plt.cla() plt.plot(waveblue[indexblue:], fluxblue[indexblue:], drawstyle='steps-mid', color='b') plt.plot(wavered[0:indexred], fluxred[0:indexred] * fluxcor, drawstyle='steps-mid', color='r') plt.xlabel('Wavelength') plt.ylabel('Flux') plt.pause(0.01) print('Change scale?') answer = yesno('n') if (answer == 'y'): xmin_old, xmax_old = plt.xlim() ymin_old, ymax_old = plt.ylim() done = False while (not done): plt.xlim([xmin_old, xmax_old]) plt.ylim([ymin_old, ymax_old]) print('Click corners of box to change plot scale') newlims = plt.ginput(2, timeout=-1) xmin = newlims[0][0] ymin = newlims[0][1] xmax = newlims[1][0] ymax = newlims[1][1] plt.xlim([xmin, xmax]) plt.ylim([ymin, ymax]) print('Is this OK?') loopanswer = yesno('y') if (loopanswer == 'y'): done = True print('\nEnter method to select wavelength ranges\n') mode = inputter_single( 'Enter (w)avelengths or mark with the (m)ouse? (w/m) ', 'wm') print('\nChoose end points of region to compute average\n') waveb, waver, mode = womwaverange2(waveblue[indexblue:], fluxblue[indexblue:], wavered[0:indexred], fluxred[0:indexred] * fluxcor, mode) indexblueb = womget_element(waveblue, waveb) indexbluer = womget_element(waveblue, waver) indexredb = womget_element(wavered, waveb) indexredr = womget_element(wavered, waver) mean_blue = np.mean(fluxblue[indexblueb:indexbluer + 1]) mean_red = np.mean(fluxred[indexredb:indexredr + 1]) print("\nAverage for {}:{}".format(waveb, waver)) print("Blue side: {}".format(mean_blue)) print("Red side: {}\n".format(mean_red)) brscale = inputter_single('Scale to blue or red (b/r)? ', 'br') if (brscale == 'b'): brscalefac = mean_blue / mean_red logging.info('Cat scaling to blue by {}'.format(brscalefac)) fluxred = fluxred * brscalefac varred = varred * brscalefac**2 else: brscalefac = mean_red / mean_blue logging.info('Cat scaling to red by {}'.format(brscalefac)) fluxblue = fluxblue * brscalefac varblue = varblue * brscalefac**2 # print("\nPlotting blue side as blue, red side as red\n") # plt.cla() # plt.plot(waveblue[indexblueb:indexbluer+1],fluxblue[indexblueb:indexbluer+1],drawstyle='steps-mid',color='b') # plt.plot(wavered[indexredb:indexredr+1],fluxred[indexredb:indexredr+1],drawstyle='steps-mid',color='r') # plt.xlabel('Wavelength') # plt.ylabel('Flux') # plt.pause(0.01) # print('Change scale?') # answer=yesno('n') # if (answer == 'y'): # xmin_old,xmax_old=plt.xlim() # ymin_old,ymax_old=plt.ylim() # done=False # while (not done): # plt.xlim([xmin_old,xmax_old]) # plt.ylim([ymin_old,ymax_old]) # print('Click corners of box to change plot scale') # newlims=plt.ginput(2,timeout=-1) # xmin=newlims[0][0] # ymin=newlims[0][1] # xmax=newlims[1][0] # ymax=newlims[1][1] # plt.xlim([xmin,xmax]) # plt.ylim([ymin,ymax]) # print('Is this OK?') # loopanswer=yesno('y') # if (loopanswer == 'y'): # done=True # print('\nChoose end points of region to compute average\n') # waveb,waver,mode=womwaverange2(waveblue[indexblueb:indexbluer+1], # fluxblue[indexblueb:indexbluer+1], # wavered[indexredb:indexredr+1], # fluxred[indexredb:indexredr+1],mode) # indexblueb=womget_element(waveblue,waveb) # indexbluer=womget_element(waveblue,waver) # indexredb=womget_element(wavered,waveb) # indexredr=womget_element(wavered,waver) # ewadd=inputter_single('Add overlap region (e)qually or with (w)eights (e/w)?','ew') # if (ewadd == 'e'): # overflux=(fluxblue[indexblueb:indexbluer+1]+fluxred[indexredb:indexredr+1])/2. # overvar=(varblue[indexblueb:indexbluer+1]+varred[indexredb:indexredr+1]) #replacing with inverse variance weighted average overflux = np.average([ fluxblue[indexblueb:indexbluer + 1], fluxred[indexredb:indexredr + 1] ], weights=[ 1. / varblue[indexblueb:indexbluer + 1], 1. / varred[indexredb:indexredr + 1] ], axis=0) overvar = np.sum( [varblue[indexblueb:indexbluer + 1], varred[indexredb:indexredr + 1]], axis=0) # logging.info('Cat combined sides with inverse variance weighted average') # else: # wei_done = False # while (not wei_done): # weiblue=inputter('Enter fractional weight for blue side: ','float',False) # weired=inputter('Enter fractional weight for red side: ','float',False) # if (np.abs((weiblue+weired)-1.0) > 0.000001): # print('Weights do not add to 1.0') # else: # wei_done = True # overflux=(fluxblue[indexblueb:indexbluer+1]*weiblue+ # fluxred[indexredb:indexredr+1]*weired) # overvar=(varblue[indexblueb:indexbluer+1]*weiblue**2+ # varred[indexredb:indexredr+1]*weired**2) # logging.info('Cat adds blue side with weight {} and red side with weight {}'.format(weiblue, weired)) newbluewave = waveblue[:indexblueb] newblueflux = fluxblue[:indexblueb] newbluevar = varblue[:indexblueb] overwave = waveblue[indexblueb:indexbluer + 1] newredwave = wavered[indexredr + 1:] newredflux = fluxred[indexredr + 1:] newredvar = varred[indexredr + 1:] newwave = np.concatenate([newbluewave, overwave, newredwave]) newflux = np.concatenate([newblueflux, overflux, newredflux]) newvar = np.concatenate([newbluevar, overvar, newredvar]) # logging.info('File {} and'.format(hop[hopnum1].obname)) # logging.info('File {} concatenated'.format(hop[hopnum2].obname)) # logging.info('over wavelength range {} to {}'.format(waveblue[indexblueb], # waveblue[indexbluer])) plt.clf() axarr = fig.subplots(2) axarr[0].plot(overwave, overflux, drawstyle='steps-mid', color='k') axarr[0].plot(waveblue[indexblueb:indexbluer + 1], fluxblue[indexblueb:indexbluer + 1], drawstyle='steps-mid', color='b') axarr[0].plot(wavered[indexredb:indexredr + 1], fluxred[indexredb:indexredr + 1], drawstyle='steps-mid', color='r') axarr[0].set_title('Overlap region, with inputs and combination') axarr[1].set_ylabel('Flux') axarr[1].plot(newwave, newflux, drawstyle='steps-mid', color='k') axarr[1].plot(newwave[indexblueb:indexbluer + 1], newflux[indexblueb:indexbluer + 1], drawstyle='steps-mid', color='r') plt.pause(0.01) check = inputter('Check plot [enter when done]: ', 'string', False) # hopout=0 # while (hopout < 1) or (hopout > HOPSIZE): # hopout=inputter('Enter hopper to store combined spectrum: ','int',False) # hop[hopout].wave=newwave # hop[hopout].flux=newflux # hop[hopout].var=newvar # hop[hopout].obname=hop[hopnum1].obname # hop[hopout].header=hop[hopnum1].header # plt.close() #fig.clf() # #plt.cla() # return hop return newwave, newflux, newvar
def tick_attendence(self,img_name = None,save_annotated = True,add_vector = True,n_neighbors = 1): global Label_test global location_list global vector_list global mode def line_select_callback(click,release): global Label_test global location_list global target row1,col2,row2,col1 = int(click.ydata),int(release.xdata),int(release.ydata),int(click.xdata) Label_test.append(int(target)) location_list.append((row1,col2,row2,col1)) print(special_layout(f"Added {self.dict_[str(target)]['name']} to annotated image.\n\ Amount of targets: {len(location_list)}")) plt.close() def onclick(event): global Label_test global location_list global vector_list global mode col, row = event.xdata, event.ydata for i in range(len(location_list)): row1,col2,row2,col1 = location_list[i] if row > row1 and row < row2 and col > col1 and col < col2: if mode == '2': try: correction = input(special_layout(f"You select {self.dict_[str(Label_test[i])]['name']} ({Label_test[i]})\n***correction -> 1 No correction -> 0")) if int(correction): correct_label = input(special_layout(f"Who is this? :\n\n\ {dict_5row_layout(self.dict_,'name',blank = 15,each_row =5,count_value = False)}\n***Please type number")) print(special_layout(f"{self.dict_[str(Label_test[i])]['name']} -> {self.dict_[str(correct_label)]['name']}")) Label_test[i] = correct_label except: pass break elif mode == '3': try: delete = input(special_layout(f"You confirm to delete {self.dict_[str(Label_test[i])]['name']} ({Label_test[i]}) on [{row1}:{row2},{col1}:{col2}]?\n***yes -> 1 No no -> 0")) except: pass break try: if int(delete): Label_test.pop(i) location_list.pop(i) vector_list.pop(i) except: pass plt.close() def toggle_selector(event): toggle_selector.RS.set_active(True) def object_mode_change(event): global target global mode if event.key == '1': mode = '1' print(special_layout(f" Add label on annotated image.")) try: target = input(special_layout(f"Select target label:\n\n\ {dict_5row_layout(self.dict_,'name',blank = 15,each_row =5,count_value = False)}")) print(f"You will annotate {self.dict_[str(target)]['name']} ({target})") plt.close() except: pass elif event.key == '2': mode = '2' print(special_layout(f" Change label on annotated image.")) plt.close() elif event.key == '3': mode = '3' print(special_layout(f" Delete label on annotated image.")) plt.close() elif event.key == 'q': mode = 'q' print(special_layout(f"Finish correction...")) plt.close() else: print(special_layout(f"Please press the followings key:\n\nAdd annotation -> 1\nClick show label and change label -> 2\nDelete annotation -> 3\n\ Exit correction -> q")) # change name if img_name == None: try: img_name = change_image_name(self.classname) except: img_name = [path for path in sorted(Path(f"./data/{self.classname}/image/class").glob("*.jpg"))][-1].name img_path = f'./data/{self.classname}/image/class/{img_name}' print(special_layout(f"Detect and encode faces on image({img_name})")) array = load_image(img_path) location_list, vector_list = face_location_encoding(array) Label_test = list(face_prediction(self.classname, vector_list)) annotated = draw_box(load_image(img_path), location_list,False,Label_test ,self.dict_) count = 0 while True: print(special_layout(f"Show you the annotated image...\nEnter q")) fig, ax = plt.subplots(1) plt.imshow(annotated) plt.show() if count%2==0: indivdual = input(special_layout(f"Try individual model?\n1:yes 0:no")) if int(indivdual): Label_test = list(face_prediction(self.classname, vector_list,only_individual=True)) annotated = draw_box(load_image(img_path), location_list,False,Label_test ,self.dict_) else: break else: back = input(special_layout(f"Try the previous model?\n1:yes 0:no")) if int(back): Label_test = list(face_prediction(self.classname, vector_list)) annotated = draw_box(load_image(img_path), location_list,False,Label_test ,self.dict_) plt.close() else: print(123) break count += 1 print(special_layout(f"Show you the annotated image...\nPress H to watch instruction:)")) mode = '2' while True: annotated = draw_box(load_image(img_path), location_list,False,Label_test ,self.dict_) fig, ax = plt.subplots(1) plt.imshow(annotated) if mode == '1': toggle_selector.RS = RectangleSelector( ax,line_select_callback, drawtype='box',useblit=True, button=[1],minspanx=5,minspany=5, spancoords='pixels',interactive=True ) plt.connect('key_press_event', toggle_selector) plt.connect('key_press_event',object_mode_change) elif mode == '2' or mode == '3': Cursor(ax, horizOn=False, # Controls the visibility of the horizontal line vertOn=False, # Controls the visibility of the vertical line ) fig.canvas.mpl_connect('button_press_event', onclick) plt.connect('key_press_event',object_mode_change) plt.show() if mode == 'q': break if save_annotated: create_annotated_dir(self.classname) plt.imsave(img_path.replace('class','annotated'),annotated) # write table write_table(self.dict_,self.classname,Label_test,img_name) # add vector # Modelling if add_vector: vector_correct = input(special_layout(f"Add all face into our knn model?\n***yes -> 1 no -> 0")) if int(vector_correct)-1: mode = '2' while True: annotated = draw_box(load_image(img_path), location_list,False,Label_test ,self.dict_) fig, ax = plt.subplots(1) plt.imshow(annotated) if mode == '1': toggle_selector.RS = RectangleSelector( ax,line_select_callback, drawtype='box',useblit=True, button=[1],minspanx=5,minspany=5, spancoords='pixels',interactive=True ) plt.connect('key_press_event', toggle_selector) plt.connect('key_press_event',object_mode_change) elif mode == '2' or mode == '3': Cursor(ax, horizOn=False, # Controls the visibility of the horizontal line vertOn=False, # Controls the visibility of the vertical line ) fig.canvas.mpl_connect('button_press_event', onclick) plt.connect('key_press_event',object_mode_change) plt.show() if mode == 'q': break add_vector_location_img(self.dict_,self.classname,vector_list,Label_test,location_list,img_name) vector_train=[] label_train=[] print(special_layout(f"Vector amount summary:")) print(col_layout('Label','Vector(individual) amount','Vector(class) amount','Total')) for label,each_dict in self.dict_.items(): total = len(each_dict['vector(individual)'])+len(each_dict['vector(class)']) print(col_layout(str(label)+'.'+each_dict['name'],len(each_dict['vector(individual)']),len(each_dict['vector(class)']),total)) vector_train = vector_train + each_dict['vector(individual)']+each_dict['vector(class)'] label_train += [int(label) for i in range(total)] knn_modelling(self.classname,vector_train,label_train,n_neighbors =n_neighbors) # Final: output to dir with open(json_path,'w') as doc: doc.write(json.dumps(self.dict_)) # reminder print(special_layout(f'Renew label dictionary: {json_path}'))
def rmcplot(path, stem, pdf_type, recip_type, **kwargs): """ ---- Main Parameters: path = RMC refinement folder \n stem = RMC files stem name \n pdf_type = "ft_fq", "gr" \n recip_type = "fq", "sq" \n \n ---- Example: \n path = r"C:\\RMCProfile\\RMCProfile_package\\tutorial\\ex_6\\rmc_neutron\\run" \n stem_name = "gapo4_neutron" \n pdf_type = "gr" \n recip_type = "sq" \n ---- kwargs: \n partials="Combine_partials" # When specified requires user input of partials, which is useful for mixed site materials \n partials_matrix=partials # Each column of this matrix corresponds to a partial pair, with the first column being the x-axis \n partials_labels=labels # Labels for each column of the partials_matrix \n recip_diff_fact=float # If specified will multiply the recip. difference curve by float for magnification \n pdf_diff_fact=float # If specified will multiply the pdf difference curve by float for magnification \n """ path_stem = path + "\\" + stem # fig = plt.figure(figsize=c2i.cm2inch(60,30)) #width, height fig = plt.figure(figsize=c2i.cm2inch(40, 20)) #width, height ax = plt.subplot(221) # PDF ax1 = plt.subplot(223, sharex=ax) # PDF partials ax2 = plt.subplot(324) # Bragg ax3 = plt.subplot(322) # Chi2 data ax2_chi = ax3.twinx() # Chi2 data ax4 = plt.subplot(326) # Recip data ## ----- PDF ----- if pdf_type == "ft_fq": PDF_data_file = path_stem + "_FT_XFQ1.csv" elif pdf_type == "gr": PDF_data_file = path_stem + "_PDF1.csv" elif pdf_type == "gr_x": PDF_data_file = path_stem + "_Xray_PDF1.csv" ax.set_xlabel(r'r($\AA$)') ax.set_ylabel('G(r)') ax.set_title('PDF fit') ax.xaxis.set_minor_locator(AutoMinorLocator()) ax.yaxis.set_minor_locator(AutoMinorLocator()) if os.path.exists(PDF_data_file): pdf_data = np.loadtxt(PDF_data_file, delimiter=",", skiprows=1) pdf_labels = np.genfromtxt(PDF_data_file, dtype='str', delimiter=",", max_rows=1) # pdf_rfd = np.loadtxt(path_stem+'.gr', skiprows=2) #original raw data file pdf_labels = remove_space(pdf_labels) diff_zoom = 1.0 diff_label = 'diff' if kwargs.get("pdf_diff_fact"): diff_zoom = kwargs.get("pdf_diff_fact") diff_label = 'diff' + 'x' + str(diff_zoom) pdf_r = pdf_data[:, 0] pdf_fit = pdf_data[:, 1] pdf_data = pdf_data[:, 2] pdf_diff = pdf_data - pdf_fit pdf_diff = pdf_diff * diff_zoom diff_offset = abs(min(min(pdf_fit), min(pdf_data))) + abs( max(pdf_diff[100:])) + 0.05 pdf_diff = pdf_diff - diff_offset # Black line through difference ax.axhline(-diff_offset, color='k') # ax.plot(pdf_rfd[:,0], pdf_rfd[:,1], 'bo-', markerfacecolor='white', label='.gr', markersize=4) ax.plot(pdf_r, pdf_data, 'bo-', markerfacecolor='white', label=pdf_labels[2], markersize=4) ax.plot(pdf_r, pdf_fit, color='red', label=pdf_labels[1]) ax.plot(pdf_r, pdf_diff, color='green', label=diff_label) ax.set_xlim(left=min(pdf_r) - 0.1, right=max(pdf_r) + 0.1) ax.set_ylim(bottom=min(pdf_diff)) ax.legend(loc=2, ncol=3) if kwargs.get('plot_baseline'): num_density = kwargs.get("num_density") bl_r = -pdf_r * 4 * np.pi * num_density # ax.plot(pdf_r, bl_r, 'k', zorder=-1000) ax.plot(pdf_r, bl_r, 'k', zorder=1000) else: middle_text(ax, 'No PDF fit') ## ----- Recip ----- if recip_type == "fq": Recip_Data_File = path_stem + "_FQ1.csv" elif recip_type == "sq": Recip_Data_File = path_stem + "_SQ1.csv" ax4.set_xlabel(r'Q($\AA^{-1}$)') ax4.set_ylabel('F(Q),S(Q),etc.') ax4.set_title('Reciprocal space fit') ax4.xaxis.set_minor_locator(AutoMinorLocator()) ax4.yaxis.set_minor_locator(AutoMinorLocator()) if os.path.exists(Recip_Data_File): rec_data = np.loadtxt(Recip_Data_File, delimiter=",", skiprows=1) rec_labels = np.genfromtxt(Recip_Data_File, dtype='str', delimiter=",", max_rows=1) rec_labels = remove_space(rec_labels) diff_zoom = 1.0 diff_label = 'diff' if kwargs.get("recip_diff_fact"): diff_zoom = kwargs.get("recip_diff_fact") diff_label = 'diff' + 'x' + str(diff_zoom) rec_q = rec_data[:, 0] rec_fit = rec_data[:, 1] rec_data = rec_data[:, 2] rec_diff = rec_data - rec_fit rec_diff = rec_diff * diff_zoom diff_offset = abs(min(min(rec_fit), min(rec_data))) + abs( max(rec_diff)) + 0.05 rec_diff = rec_diff - diff_offset # Black line through difference ax4.axhline(-diff_offset, color='k') # ax4.plot(rec_q,rec_data, 'bo-', markerfacecolor='white', label=rec_labels[2], markersize=4) ax4.plot(rec_q, rec_data, 'b-', lw=1.5, label=rec_labels[2], markersize=4) ax4.plot(rec_q, rec_fit, color='red', lw=1, label=rec_labels[1]) ax4.plot(rec_q, rec_diff, color='green', label=diff_label) ax4.set_xlim(min(rec_q) - 0.1, max(rec_q) + 0.1) ax4.legend(loc=1) else: middle_text(ax4, 'No Reciprocal space fit') ## ----- Bragg ----- Bragg_Data_File = path_stem + "_bragg.csv" ax2.set_xlabel('2Theta, TOF, etc.') ax2.set_ylabel('Intensity') ax2.set_title('Bragg fit') ax2.xaxis.set_minor_locator(AutoMinorLocator()) ax2.yaxis.set_minor_locator(AutoMinorLocator()) if os.path.exists(Bragg_Data_File): # bragg_data = np.loadtxt(Bragg_Data_File, delimiter=",", skiprows=1) bragg_data = np.loadtxt(Bragg_Data_File, delimiter=",", skiprows=0) # bragg_labels = np.genfromtxt(Bragg_Data_File, dtype='str', delimiter=",", max_rows=1) # bragg_labels = remove_space(bragg_labels) diff_zoom = 1.0 diff_label = 'diff' if kwargs.get("recip_diff_fact"): diff_zoom = kwargs.get("recip_diff_fact") diff_label = 'diff' + 'x' + str(diff_zoom) bragg_x = bragg_data[:, 0] bragg_exp = bragg_data[:, 1] bragg_fit = bragg_data[:, 2] bragg_diff = bragg_exp - bragg_fit bragg_diff = bragg_diff * diff_zoom max_bragg = max(max(bragg_exp), max(bragg_fit)) min_bragg = min(min(bragg_exp), min(bragg_fit)) diff_offset = -(min_bragg - max(bragg_diff) - 0.03 * (max_bragg - min_bragg)) bragg_diff = bragg_diff - diff_offset if kwargs.get('plot_Bragg_in_Q'): bragg_q = TOF_2_Q(bragg_x, kwargs.get('L_path'), kwargs.get('two_theta')) bragg_x = bragg_q ax2.set_xlabel(r'Q($\AA^{-1}$)') if kwargs.get('plot_Bragg_in_d'): bragg_q = TOF_2_Q(bragg_x, kwargs.get('L_path'), kwargs.get('two_theta')) bragg_x = 2 * np.pi / bragg_q ax2.set_xlabel(r'd($\AA$)') # Black line through difference ax2.axhline(-diff_offset, color='k') # ax2.plot(bragg_x,bragg_exp, 'b', marker='x', markersize=4, label=bragg_labels[1], linewidth=1.5) ax2.plot(bragg_x, bragg_exp, 'b', marker='x', markersize=3, label='data', linewidth=1.5) # ax2.plot(bragg_x,bragg_fit, color='red', label=bragg_labels[2]) ax2.plot(bragg_x, bragg_fit, color='red', label='fit') ax2.plot(bragg_x, bragg_diff, color='green', label=diff_label) ax2.set_xlim(min(bragg_x) - 0.1, max(bragg_x) + 0.1) ax2.legend(loc=1) else: middle_text(ax2, Bragg_text) ## ----- Partials ----- partials_data_file = path_stem + "_PDFpartials.csv" ax1.set_title('Partials') ax1.set_xlabel(r'r($\AA$)') ax1.set_ylabel('g(r)') ax1.xaxis.set_minor_locator(AutoMinorLocator()) ax1.yaxis.set_minor_locator(AutoMinorLocator()) if os.path.exists(partials_data_file): if kwargs.get("partials") == "Combine_partials": labels = kwargs.get("partials_labels") partials = kwargs.get("partials_matrix") for i in range(len(labels) - 1): ax1.plot(partials[:, 0], partials[:, i + 1], label=labels[i + 1]) # ax1.set_xlim(right = max(partials[:,0])+0.1) else: with open(partials_data_file) as f: ncols = len(f.readline().split(',')) partial_labels = np.genfromtxt(partials_data_file, delimiter=",", dtype='str', max_rows=1) partial_data = np.loadtxt(partials_data_file, delimiter=",", skiprows=1, usecols=range(0, ncols)) x_par = partial_data[:, 0] # r(Ang) Va_cols = np.char.find(partial_labels, 'Va') non_Va_cols = np.where(Va_cols == -1)[0].tolist() if kwargs.get("remove_Va"): partial_labels = partial_labels[non_Va_cols] partial_data = partial_data[:, non_Va_cols] ncols = partial_data.shape[1] for n in range(1, ncols): PDF_par = partial_data[:, n] par_label = partial_labels[n] ax1.plot(x_par, PDF_par, label=par_label) # ax1.set_xlim(right = max(x_par)+0.1) ax1.set_ylim(bottom=0, ) ax1.legend(loc=1, ncol=3) ## ----- Chi2 ----- # Create a list of the log files present in the directory l_c = 0 log_check = stem + '-*.log' for file in os.listdir(path): if fnmatch.fnmatch(file, log_check): if l_c == 0: log_files = np.array([file]) else: log_files = np.append(log_files, file) l_c += 1 n_logs = len(log_files) log_data_File = os.path.join(path, log_files[0]) # Set the labels ax3.set_xlabel('moves generated') ax3.set_ylabel(r'chi$^2$') ax3.set_title(r'moves and chi$^2$') # ax2_chi.set_ylabel('moves generated') ax2_chi.set_ylabel('moves') ax3.xaxis.set_minor_locator(AutoMinorLocator()) ax3.yaxis.set_minor_locator(AutoMinorLocator()) if os.path.exists(log_data_File): # Time, moves_acc, moves_gen, fit1, fit2, fit3, etc. chi2_labels = np.genfromtxt(log_data_File, dtype='str', max_rows=1) chi2_data = np.genfromtxt(log_data_File, skip_header=2) # print(chi2_data.shape) # Set the moves and time if len(chi2_data.shape) == 0: pass elif len(chi2_data.shape) == 1: time_rmc = np.array([chi2_data[0]]) move_acc = np.array([chi2_data[1]]) move_gen = np.array([chi2_data[2]]) else: time_rmc = chi2_data[:, 0] move_acc = chi2_data[:, 1] move_gen = chi2_data[:, 2] moves_log = np.array([max(move_gen)]) if n_logs > 1: for ln in range(1, n_logs): log_data_File = os.path.join(path, log_files[ln]) # Time, moves_acc, moves_gen, fit1, fit2, fit3, etc. chi2_data_log = np.genfromtxt(log_data_File, skip_header=2) # Set the moves and time if chi2_data_log.shape[0] == 0: pass else: if len(chi2_data_log.shape) == 1: # time_rmc_i = np.array([chi2_data_log[0]]) # move_acc_i = np.array([chi2_data_log[1]]) # move_gen_i = np.array([chi2_data_log[2]]) time_rmc_log = np.array([chi2_data_log[0] ]) + max(time_rmc) move_acc_log = np.array([chi2_data_log[1] ]) + max(move_acc) move_gen_log = np.array([chi2_data_log[2] ]) + max(move_gen) else: # time_rmc_i = chi2_data_log[:,0] # move_acc_i = chi2_data_log[:,1] # move_gen_i = chi2_data_log[:,2] time_rmc_log = chi2_data_log[:, 0] + max(time_rmc) move_acc_log = chi2_data_log[:, 1] + max(move_acc) move_gen_log = chi2_data_log[:, 2] + max(move_gen) # m_t = max(time_rmc); print(m_t) # m_a = max(move_acc); print(m_a) # m_g = max(move_gen); print(m_g) # if max(time_rmc_i) < m_t: pass # elif max(time_rmc_i) > m_t: time_rmc_i -= m_t # if max(move_acc_i) < m_t: pass # elif max(move_acc_i) > m_t: move_acc_i -= m_t # if max(move_gen_i) < m_t: pass # elif max(move_gen_i) > m_t: move_gen_i -= m_t # time_rmc_log = time_rmc_i + max(time_rmc) # move_acc_log = move_acc_i + max(move_acc) # move_gen_log = move_gen_i + max(move_gen) moves_log = np.append(moves_log, max(move_gen_log)) chi2_data = np.row_stack((chi2_data, chi2_data_log)) time_rmc = np.append(time_rmc, time_rmc_log) move_acc = np.append(move_acc, move_acc_log) move_gen = np.append(move_gen, move_gen_log) num_data = len(chi2_labels) - 3 #first 3 columns are time and moves # Set and plot the moves on its axis ax2_chi.plot(move_gen, move_acc, 'r', marker='o', ms=4, label=chi2_labels[1]) ax2_chi.plot(move_gen, move_gen, 'k', marker='o', ms=4, label=chi2_labels[2]) min_y = min(np.min(move_gen), np.min(move_acc)) max_y = max(np.max(move_gen), np.max(move_acc)) moves_del = 1 * (max_y - min_y) min_y = min_y - 0.001 * moves_del max_y = max_y + 0.03 * moves_del # ax2_chi.set_ylim(bottom=min_y,top=max_y) ax2_chi.set_xlim(left=min_y, right=max_y) ax2_chi.legend(loc=1, title='moves') # Plot each of the fit chi2 sets max_chi = -1000 min_chi = 1000 for i in range(0, num_data): fit_col = i + 3 try: if len(chi2_data.shape) == 1: chi_fit_plot = chi2_data[fit_col] else: chi_fit_plot = chi2_data[:, fit_col] max_chi = max(max_chi, np.max(chi_fit_plot)) min_chi = min(min_chi, np.min(chi_fit_plot)) ax3.semilogy(move_gen, chi_fit_plot, marker='o', ms=4, label=chi2_labels[fit_col]) # ax3.plot(move_gen,chi_fit_plot,marker='o',ms=4, label=chi2_labels[fit_col]) except: pass ax3.legend(loc=2, title=r'chi$^2$') # Add vertical black lines corresponding to each RMC run moves_log_y = np.zeros(len(moves_log)) moves_log_y[:] = 0.1 for i in range(len(moves_log)): ax3.axvline(moves_log[i], color='k') # ax3.semilogy(moves_log,moves_log_y, marker='|', linewidth=0, color='k', markersize=1000) ax2_chi.format_coord = make_format(ax2_chi, ax3) moves_del_min = 0.01 * (max_chi - min_chi) if moves_del_min < 0: moves_del_min = 0 moves_del_max = 0.10 * (max_chi - min_chi) ax3.set_ylim(bottom=min_chi - moves_del_min, top=max_chi + moves_del_max) from matplotlib.ticker import ScalarFormatter as SF f = SF(useMathText=True) f.set_scientific(True) f.set_powerlimits((0, 3)) ax3.yaxis.set_major_formatter(f) ax3.xaxis.set_major_formatter(f) ax2_chi.yaxis.set_major_formatter(f) ax2_chi.xaxis.set_major_formatter(f) ## ----- Final touches cursor1 = Cursor(ax2_chi, useblit=True, color='k', linewidth=1) cursor2 = Cursor(ax4, useblit=True, color='k', linewidth=1) multi = MultiCursor(fig.canvas, (ax, ax1), useblit=True, color='k', lw=1) plt.suptitle('RMCProfile results: ' + stem, fontsize=12, fontweight='bold') plt.subplots_adjust(left=0.07, right=0.93, top=0.93, bottom=0.07, hspace=0.4) # return fig, cursor1, multi return fig, cursor1, cursor2, multi
selected_points.append(point) # Lista con todos los puntos del cuadrante quadrant_points = [] for point in all_points: if point.quadrant == selected_quadrant: quadrant_points.append(point) X_quadrant, Y_quadrant, Z_quadrant = get_cords(quadrant_points) X_selected, Y_selected, Z_selected = get_cords(selected_points) fig = plt.figure(dpi=100, frameon=False) figure = fig.add_subplot() figure.set_title(selected_quadrant) cursor = Cursor(figure, horizOn=True, vertOn=True, color='b', linewidth=1) if selected_quadrant == 'Upper' or selected_quadrant == 'Lower' or selected_quadrant == 'Superior' or selected_quadrant == 'Inferior': figure.plot(X_quadrant, Y_quadrant, 'o', markersize=1, color='black') figure.plot(X_selected, Y_selected, 'o', markersize=2, color='red', picker=5) elif selected_quadrant == 'Right' or selected_quadrant == 'Left' or selected_quadrant == 'Derecho' or selected_quadrant == 'Izquierdo': figure.plot(X_quadrant, Z_quadrant, 'o', markersize=1, color='black') figure.plot(X_selected, Z_selected, 'o', markersize=2, color='red',
plt.figure('Raw C-Scan Test') # select the raw c-scan figure raw_axis.set_title('Raw C-Scan Test', fontsize=20) raw_axis.set_xlabel('X Scan Location (mm)') raw_axis.set_ylabel('Y Scan Location (mm)') raw_image = plt.imshow(data.c_scan, cmap='gray', interpolation='none', extent=data.c_scan_extent, origin='upper', picker=True) raw_axis.grid() # instantiate a colorbar object for the raw C-Scan, this is necessary so it can be updated raw_cb = plt.colorbar(raw_image, orientation='horizontal') # add the cursor to the raw c-scan image cursor = Cursor(raw_axis, color='red') plt.figure('Interpolated C-Scan Test') # select the interpolated C-Scan figure interp_axis.set_title('Interpolated C-Scan Test', fontsize=20) interp_axis.set_xlabel('X Scan Location (mm)') interp_axis.set_ylabel('Y Scan Location (mm)') interp_image = plt.imshow(data.c_scan, cmap='jet', interpolation='bilinear', extent=data.c_scan_extent, origin='upper') interp_axis.grid() # instantiate a colorbar object for interpolated C-Scan, this is necessary so it can be updated interp_cb = plt.colorbar(interp_image, orientation='horizontal') plt.show()
run.save_result("peakODX", pOptX[0]) run.save_result("widthX", widthX) run.save_result("tempX", tempX) run.save_result("centerX", centerX) run.save_result("peakODZ", pOptZ[0]) run.save_result("widthZ", widthZ) run.save_result("tempZ", tempZ) run.save_result("centerZ", centerZ) run.save_result("avgWidth", avgWidth) run.save_result("avgPeakOD", avgPeakOD) run.save_result("avgTemp", avgTemp) # Set Center event cursor = Cursor(ax, useblit=True, color='white', linewidth=1) cursor.set_active(False) def set_center(event): if event.key in ['C', 'c'] and not cursor.active: cursor.set_active(True) elif event.key in ['C', 'c'] and cursor.active: cursor.set_active(False) center = (int(event.xdata), int(event.ydata)) print(center) with h5py.File('current_roi.h5', 'w') as f: if 'center' not in f: f.attrs.create('center', center) else: f.attrs['center'] = center
def plot_all_sel_records(self): # {{{ ## Setting persistent view is somewhat kafkaesque with matplotlib. ## self.xlim remembers the correct view from the last GUI resize , but ## ax.get_xlim from the start of this method returns the wrong (autoscaled) limits, why? if not w('chk_autoscale_x').get_active() and self.xlim: self.ax.set_xlim(self.xlim) if not w('chk_autoscale_y').get_active() and self.ylim: self.ax.set_ylim(self.ylim) ## Load all row data (model, pathlist) = w('treeview1').get_selection().get_selected_rows() if len(pathlist) == 0: return error_counter = 0 row_data = [] row_labels = [] plotted_paths = [] for path in pathlist: try: row_data.append(self.load_row_data( self.tsFiles.get_iter(path))) plotted_paths.append(path) except (RuntimeError, ValueError): traceback.print_exc() error_counter += 1 w('statusbar1').push( 0, ('%d records loaded' % len(pathlist)) + ('with %d errors' % error_counter) if error_counter else '') if row_data == []: return False xs, ys, labels, params, xlabels, ylabels = zip(*row_data) #for n,v in zip('xs, ys, labels, params, xlabels, ylabels'.split(), [xs, ys, labels, params, xlabels, ylabels]): #print(n,v) ## TODO: check if there is exactly one column in the 'params' table that differs among files: label="%s=%s" % (labelkey, labelval) ## If it is, append its name and value to the respective 'labels' field, so that all plotted lines are distinguishable by this value! ## If there is none, or too many, the curves will be labeled just by their column label found in the header. ## TODO allow also to name the curves by the file name, if the column names do not exist or are all the same! ## Generate the color palette for curves color_pre_map = np.linspace(0.05, .95, len(plotted_paths) + 1)[:-1] colors = matplotlib.cm.gist_rainbow( color_pre_map * .5 + np.sin(color_pre_map * np.pi / 2)**2 * .5) for path, color_from_palette in zip(plotted_paths, colors): ## If no exception occured during loading, colour the icon according to the line colour icon = self.row_prop(self.tsFiles.get_iter(path), 'plotstyleicon') if icon: icon.fill(self.array2rgbhex(color_from_palette)) plotted_paths.append(path) ## TODO: decide what is the distinguishing parameter for the given set of rows ---> <str> labelkey, <labelvals # 1) (almost) all curves should have it defined # 2) it should differ among (almost) all curves # 3) it may be in the params dict, or in the filename (for csvtwocolumn), or in the header of csvcolumn, opjcolumn etc. #print("self.ax.axis", self.ax.axis()) ## Plot all curves sequentially plot_cmd_buffer = w('txt_rc').get_buffer() plot_command = plot_cmd_buffer.get_text( plot_cmd_buffer.get_start_iter(), plot_cmd_buffer.get_end_iter(), include_hidden_chars=True) #print("BEFORE COMMAND") #print(row_data) if plot_command.strip() != '': #np = numpy def dedup(l): return list( dict.fromkeys(l[::-1]) )[:: -1] ## deduplicates items, preserves order of first occurence exec_env = { 'np': np, 'sc': sc, 'matplotlib': matplotlib, 'cm': matplotlib.cm, 'ax': self.ax, 'fig': self.fig, 'xs': np.array(xs), 'ys': np.array(ys), 'labels': labels, 'params': np.array(params), 'xlabels': xlabels, 'ylabels': ylabels, 'xlabelsdedup': ', '.join(dedup(xlabels))[:100], 'ylabelsdedup': ', '.join(dedup(ylabels))[:100], 'colors': colors } #self.fig.clf() ## clear figure try: exec(plot_command, exec_env) #print("JUST AFTER COMMAND") except SyntaxError: #print("SYNTAX ERROR:") traceback.print_exc() ## TODO locate the error except: #print("SOME ERROR") traceback.print_exc() ## TODO locate the error #print("AFTER COMMAND") #code = compile(plot_command, "somefile.py", 'exec') TODO #exec(code, global_vars, local_vars) #else: #plot_command = default_plot_command #plot_cmd_buffer.set_text(default_plot_command) cursor = Cursor( self.ax, color='red', linewidth=.5 ) ## , useblit=True .. fixme: useblit made the cursor disappear # Note: blit cannot be used: AttributeError: 'FigureCanvasGTK3Cairo' object has no attribute 'copy_from_bbox' #self.ax.legend(loc="best") self.ax.grid(True) self.ax.set_xscale( 'log' if w('chk_xlogarithmic').get_active() else 'linear') ##XXX self.ax.set_yscale( 'log' if w('chk_ylogarithmic').get_active() else 'linear') ##XXX self.ax.relim() self.ax.autoscale_view( ) # Autoscale the view limits using the data limits. self.canvas.draw() return True
ax[1].set_title("A2A loop sine") ax[1].plot(time, a2a_ls, color='teal') ax[1].grid() ax[2].set_title("A2A sense") ax[2].plot(time, a2a_sns, color="purple") ax[2].grid() plt.subplots_adjust(hspace=1) plt.rc('font', size=15) figs = plt.gcf() figs.set_size_inches(16, 9) cursor0 = Cursor(ax[0], horizOn=True, vertOn=True, color='grey', linestyle='dotted', linewidth=1.0) cursor1 = Cursor(ax[1], horizOn=True, vertOn=True, color='grey', linestyle='dotted', linewidth=1.0) cursor2 = Cursor(ax[2], horizOn=True, vertOn=True, color='grey', linestyle='dotted', linewidth=1.0) fig.canvas.mpl_connect('button_press_event', onclick)
def plot_summary(fig, exit_profit, entry_best, entry_worst, entry_nbar_best, entry_nbar_worst, exit_nbar_best, exit_nbar_worst, profits_more, risks, NBAR): fig.canvas.set_window_title('summary') ax11 = fig.add_subplot(3, 2, 1) ax12 = fig.add_subplot(3, 2, 2) ax21 = fig.add_subplot(3, 2, 3) ax22 = fig.add_subplot(3, 2, 4) ax31 = fig.add_subplot(3, 2, 5) ax32 = fig.add_subplot(3, 2, 6) #plt.subplots_adjust(left=0, right=1) # Profits Distribution shift = pd.Series([0]*len(exit_profit[exit_profit<=0])) temp = pd.concat([shift, exit_profit[exit_profit>0]]) temp.index = range(len(temp)) temp.plot(ax=ax11, grid=False, use_index=False, style="r", label='profit') ax11.fill_between(range(len(temp)), [0]*len(temp), temp.tolist(), facecolor='r') temp = 0 - exit_profit[exit_profit<=0] temp.index = range(len(temp)) ax11.plot(temp, 'y', label='lost') ax11.fill_between(range(len(temp)), [0]*len(temp), temp.tolist(), facecolor='y') ax11.plot(range(len(entry_worst)), entry_worst, 'b', label='entry_worst') ax11.axhline(color='black') ax11.legend(loc='upper left').get_frame().set_alpha(0.5) # Profits Distribution Bins #exit_profit.hist(ax=ax12, bins=50, normed=True, color='r') #n, bins = np.histogram(exit_profit.tolist(), 50, normed=True) #ax12.plot([0, 0], [0, max(n)], color='y', linewidth=2) #ax12.grid(False) exit_profit.plot(ax=ax12, kind='kde', color='b', label="") binwidth = abs(exit_profit.min()/9) bins = np.arange(exit_profit.min(), exit_profit.max() + binwidth, binwidth) ax12.hist(exit_profit[exit_profit>0], bins=bins, color = 'red' , normed=False, label='profit distribution') ax12.hist(exit_profit[exit_profit<0], bins=bins, color = 'y' , normed=False, label='lost distribution') plot_contribution(ax12, bins, exit_profit, 'bo--') ax12.legend(loc='upper left').get_frame().set_alpha(0.5) #ax12.set_yscale('log') # MAE MAE = entry_worst.reindex(exit_profit[exit_profit>0].index) MAE.order().plot(ax=ax21,style='r', grid=False, use_index=False, label='entry_worst of profit') exit_profit[exit_profit<0].plot(ax=ax21, style='y', grid=False, use_index=False, label='lose distribution') worst = MAE.min() six.print_("最大不利偏移: %s" % worst) bb = exit_profit[exit_profit<0] aa = [worst]*len(bb) ax21.fill_between(range(len(exit_profit[exit_profit<0])), aa, bb, where=bb<aa, color='red') ax21.set_ylim((min(exit_profit.min(), MAE.min())-10), 0) ax21.legend(loc='upper left').get_frame().set_alpha(0.5) # Potential Profits When Lose temp = entry_best.reindex(exit_profit[exit_profit<0].index) ax22.plot(temp.tolist(), color='r', label="best profit of lose" ) ax22.fill_between(range(len(temp)), temp.tolist(), [0]*len(temp), facecolor='r') ax22.plot(temp.order().tolist(), color='b', label="ordered bpol" ) ax22.plot(exit_profit[exit_profit<0].tolist(), color='y', label='lose') ax22.set_ylim((min(exit_profit.min(), MAE.min())-10, temp.max()+10)) ax22.legend(loc='upper left').get_frame().set_alpha(0.5) ax22.axhline(0, c='black') if NBAR > 0: # Entry N Bar enbest = entry_nbar_best.reindex(entry_nbar_best[entry_nbar_best>0].index).order() enbest.plot(ax=ax31,style='r', grid=False, use_index=False, label="%s bar mean best: %s"%(NBAR, entry_nbar_best[entry_nbar_best>0].mean())) enworst = (0-entry_nbar_worst.reindex(entry_nbar_worst[entry_nbar_worst<0].index).order(ascending=False)) enworst.plot(ax=ax31, style='y', grid=False, use_index=False, label="%s bar mean worst: %s"%(NBAR, entry_nbar_worst[entry_nbar_worst<0].mean())) ax31.axhline(0, c='black') ax31.legend(loc='upper left').get_frame().set_alpha(0.5) # Exit N Bar profits_more.reindex(profits_more[profits_more>0].index).order().plot(ax=ax32,style='r', grid=False, use_index=False, label="%s bar mean best: %s"%(NBAR, profits_more[profits_more>0].mean())) (0-risks.reindex(risks[risks<0].index).order(ascending=False)).plot(ax=ax32, style='y', grid=False, use_index=False, label="%s bar mean worst: %s"%(NBAR,risks[risks<0].mean())) ax32.legend(loc='upper left').get_frame().set_alpha(0.5) # #ax31.xaxis_date() map(lambda x: x.set_xticklabels([]), [ax11, ax21, ax22, ax31, ax32]) map(lambda x: x.set_xlabel(""), [ax11, ax12, ax21, ax22, ax31, ax32]) map(lambda x: x.set_ylabel(""), [ax11, ax12, ax21, ax22, ax31, ax32]) #ax11.set_xlabel("盈利分布", fontproperties=font_big) #ax12.set_ylabel("盈利统计", fontproperties=font_big) #ax21.set_xlabel("最大不利偏移和亏损", fontproperties=font_big) #ax22.set_xlabel("亏损交易的潜在盈利空间", fontproperties=font_big) #ax31.set_xlabel("进场后%s根"%NBAR, fontproperties=font_big) #ax32.set_xlabel("离场后%s根"%NBAR, fontproperties=font_big) ax11.set_xlabel("profit distribution") ax12.set_ylabel("profit statics") ax21.set_xlabel("最大不利偏移和亏损") ax22.set_xlabel("亏损交易的潜在盈利空间") ax31.set_xlabel("进场后%s根"%NBAR) ax32.set_xlabel("离场后%s根"%NBAR) cursors = [] for ax in [ax11, ax12, ax21, ax22, ax31, ax32]: cursors.append(Cursor(ax, useblit=True, color='red', linewidth=1, vertOn = True, horizOn = True)) return [ax11, ax12, ax21, ax22, ax31, ax32], cursors
def init_ui(self): # variables self.tab = {'x': [], 'z': []} self.selected = {} self.mnt = {'x': [], 'z': []} self.x0 = None self.flag = False self.image = None self.topoSelect = None self.order_topo = 0 self.bt_transla = self.ui.btTools_profil_translation self.bt_select = self.ui.btTools_point_selection self.bt_select_z = self.ui.btTools_zone_selection self.ui.bt_add_point.setDisabled(True) # self.ui.bt_topo_save.hide() # self.ui.bt_topo_save.setDisabled(True) # *********************************************** # bouton retiré par rapport au plugin originale # (non fonctionnel ) # *********************************************** self.ui.bt_img_load.hide() self.ui.bt_img_load.setDisabled(True) # ********************************************** # tableau self.tableau = self.ui.tableWidget self.tableau.itemChanged.connect(self.modifie) self.tableau.selectionModel().selectionChanged.connect( self.select_changed) self.tableau.addAction(CopySelectedCellsAction(self.tableau)) # figure self.axes = self.fig.add_subplot(111) self.axes.grid(True) # courbe self.courbeProfil, = self.axes.plot([], [], zorder=100, label='Profile') self.courbeMNT, = self.axes.plot([], [], color='grey', marker='o', markeredgewidth=0, zorder=90, label='MNT') self.courbeTopo = [] for i in range(5): temp, = self.axes.plot([], [], color='green', marker='+', mew=2, zorder=95, label='Topo', picker=5) self.courbeTopo.append(temp) self.etiquetteTopo = [] self.courbes = [self.courbeProfil, self.courbeMNT] # Selelection Zones rect = patches.Rectangle((0, -9999999), 0, 2 * 9999999, color='pink', alpha=0.5, lw=1, zorder=80) self.litMineur = self.axes.add_patch(rect) rect = patches.Rectangle((0, -9999999), 0, 2 * 9999999, color='green', alpha=0.3, lw=1, zorder=80) self.stockgauche = self.axes.add_patch(rect) rect = patches.Rectangle((0, -9999999), 0, 2 * 9999999, color='green', alpha=0.3, lw=1, zorder=80) self.stockdroit = self.axes.add_patch(rect) rect = patches.Rectangle((0, -9999999), 0, 2 * 9999999, color='yellow', alpha=0.5, lw=1, zorder=80) self.rectSelection = self.axes.add_patch(rect) self.rectSelection.set_visible(False) self.courbeSelection, = self.axes.plot([], [], marker='o', linewidth=0, color='yellow', zorder=110) self.RS = RectangleSelector(self.axes, self.onselect, drawtype='box') self.RS.set_active(False) self.span = SpanSelector(self.axes, self.onselect_zone, 'horizontal', rectprops=dict(alpha=0, facecolor='yellow'), onmove_callback=self.onselect_zone, useblit=False) self.span.visible = False self.curseur = Cursor(self.axes, useblit=True, color="red") self.curseur.visible = False # figure suite # self.extrait_mnt() # self.fichierDecalage() self.extrait_profil() self.extrait_topo() self.maj_graph() self.maj_legende() self.maj_limites() self.fig.tight_layout() self.fig.patch.set_facecolor((0.94, 0.94, 0.94)) self.fig.canvas.mpl_connect('pick_event', self.onpick) self.fig.canvas.mpl_connect('button_press_event', self.onclick) self.fig.canvas.mpl_connect('button_release_event', self.onrelease) self.fig.canvas.mpl_connect('motion_notify_event', self.onpress) # zoom_fun = zoom mollette self.fig.canvas.mpl_connect('scroll_event', self.zoom_fun)
def plot_compare(exit_profits, entry_bests, entry_worsts, entry_nbar_bests, entry_nbar_worsts, exit_nbar_bests, exit_nbar_worsts, profits_mores, risks, colors, names, NBAR): fig = plt.figure(facecolor='white') fig.canvas.set_window_title('画图汇总一') ax11 = fig.add_subplot(3, 2, 1) ax12 = fig.add_subplot(3, 2, 2) ax21 = fig.add_subplot(3, 2, 3) ax22 = fig.add_subplot(3, 2, 4) ax31 = fig.add_subplot(3, 2, 5) ax32 = fig.add_subplot(3, 2, 6) #plt.subplots_adjust(left=0, right=1) for i in range(len(exit_profits)): nm = names[i] exit_profit = exit_profits[i] entry_best = entry_bests[i] entry_worst = entry_worsts[i] entry_nbar_best = entry_nbar_bests[i] entry_nbar_worst = entry_nbar_worsts[i] exit_nbar_best = exit_nbar_bests[i] exit_nbar_worst = exit_nbar_worsts[i] profits_more = profits_mores[i] risk = risks[i] c = colors[i] # Profits Distribution shift = pd.Series([0]*len(exit_profit[exit_profit<=0])) temp = pd.concat([shift, exit_profit[exit_profit>0]]) temp.index = range(len(temp)) temp.plot(ax=ax11, grid=False, use_index=False, style=c, label='%s盈利'%nm) temp = 0 - exit_profit[exit_profit<=0] ax11.plot(temp.tolist(), c, label='%s亏损'%nm) ax11.plot(entry_worst.tolist(), c, label='%s最差偏移'%nm) #ax11.set_xscale('log') # Profits Distribution Bins #exit_profit.hist(ax=ax12, bins=50, normed=True, color=c) #exit_profit.plot(ax=ax12, kind='kde', color='b', label="") #ax12.legend(prop=font, loc='upper left').get_frame().set_alpha(0.5) a = np.histogram(exit_profit.tolist(), 50, normed=True) n = pd.Series(a[0]) bins = pd.Series(a[1][:-1]) temp = bins[bins>0] ax12.plot(temp.tolist(), n.reindex(temp.index).tolist(), c, label='%s盈利分布'%nm) temp = bins[bins<0] ax12.plot(temp.tolist(), n.reindex(temp.index).tolist(), '%s--'%c, label='%s亏损分布'%nm) ax12.legend(loc='upper left').get_frame().set_alpha(0.5) # MAE MAE = entry_worst.reindex(exit_profit[exit_profit>0].index) MAE.order().plot(ax=ax21,style=c, grid=False, use_index=False, label='%s最大不利偏移'%nm) exit_profit[exit_profit<0].plot(ax=ax21, style='%s--'%c, grid=False, use_index=False, label='%s亏损分布'%nm) # Potential Profits When Lose temp = entry_best.reindex(exit_profit[exit_profit<0].index) ax22.plot(temp.tolist(), c, label="%s最优盈利" % nm) ax22.plot(temp.order().tolist(), '%s--'%c, label="%s有序最优盈利" % nm) ax22.plot(exit_profit[exit_profit<0].tolist(), '%s--'%c, label='%s实际亏损'%nm) if len(entry_nbar_best)>0: # Entry N Bar entry_nbar_best.reindex(entry_nbar_best[entry_nbar_best>0].index).order().plot(ax=ax31,style=c, grid=False, use_index=False, label="%s%s根最优平均: %s"%(nm, NBAR, entry_nbar_best[entry_nbar_best>0].mean())) (0-entry_nbar_worst.reindex(entry_nbar_worst[entry_nbar_worst<0].index).order(ascending=False)).plot(ax=ax31, style='%s--'%c, grid=False, use_index=False, label="%s%s根最差平均: %s"%(nm, NBAR, entry_nbar_worst[entry_nbar_worst<0].mean())) # Exit N Bar profits_more.reindex(profits_more[profits_more>0].index).order().plot(ax=ax32,style=c, grid=False, use_index=False, label="%s%s根最优平均: %s"%(nm,NBAR, profits_more[profits_more>0].mean())) (0-risk.reindex(risk[risk<0].index).order(ascending=False)).plot(ax=ax32, style='%s--'%c, grid=False, use_index=False, label="%s%s根最差平均: %s"%(nm,NBAR,risk[risk<0].mean())) # #ax31.xaxis_date() map(lambda x: x.set_xticklabels([]), [ax11, ax21, ax22, ax31, ax32]) map(lambda x: x.set_xlabel(""), [ax11, ax12, ax21, ax22, ax31, ax32]) map(lambda x: x.set_ylabel(""), [ax11, ax12, ax21, ax22, ax31, ax32]) #ax11.set_xlabel("盈利分布", fontproperties=font_big) #ax12.set_ylabel("盈利统计", fontproperties=font_big) ax11.set_xlabel("盈利分布") ax12.set_ylabel("盈利统计") ax12.axvline(color='black') ax21.legend(loc='upper left').get_frame().set_alpha(0.5) #ax21.set_xlabel("最大不利偏移和亏损", fontproperties=font_big) #ax22.set_xlabel("亏损交易的潜在盈利空间", fontproperties=font_big) #ax31.set_xlabel("进场后%s根"%NBAR, fontproperties=font_big) #ax32.set_xlabel("离场后%s根"%NBAR, fontproperties=font_big) ax21.set_xlabel("最大不利偏移和亏损") ax22.set_xlabel("亏损交易的潜在盈利空间") ax31.set_xlabel("进场后%s根"%NBAR) ax32.set_xlabel("离场后%s根"%NBAR) ax11.axhline(color='black') ax11.legend(loc='upper left').get_frame().set_alpha(0.5) ax22.legend(loc='upper left').get_frame().set_alpha(0.5) ax22.axhline(0, c='black') ax31.axhline(0, c='black') ax31.legend(loc='upper left').get_frame().set_alpha(0.5) ax32.legend(loc='upper left').get_frame().set_alpha(0.5) ax12.set_xlim((np.min(a[1][:-1])-100, np.max(a[1][:-1])+50)) ax21.set_ylim((min(exit_profit.min(), MAE.min())-10), 0) ax22.set_ylim((min(exit_profit.min(), MAE.min())-10, temp.max()+10)) cursors = [] for ax in [ax11, ax12, ax21, ax22, ax31, ax32]: cursors.append(Cursor(ax, useblit=True, color='red', linewidth=1, vertOn = True, horizOn = True)) return fig, cursors
axyield = plt.axes([0.25, 0.09, 0.65, 0.03]) axdistance = plt.axes([0.25, 0.05, 0.65, 0.03]) axheight = plt.axes([0.25, 0.01, 0.65, 0.03]) syield = Slider(axyield, 'Yield ($kT$):', 1.0, 1000.0, valinit=y0) sdistance = Slider(axdistance, 'Distance ($m$):', 0.1, 2000.0, valinit=r0) sheight = Slider(axheight, 'Burst altitude ($m$):', 0.1, 2000.0, valinit=h0) def update(val): burst_distance = sdistance.val burst_height = sheight.val bomb_yield = syield.val l1.set_ydata( convert_units( _overpressureatscaledtime(burst_distance, bomb_yield, burst_height, t), 'Pa', 'kg/cm^2')) l2.set_ydata( convert_units( _dynamicpressureatscaledtime(burst_distance, bomb_yield, burst_height, t), 'Pa', 'kg/cm^2')) fig.canvas.draw_idle() syield.on_changed(update) sdistance.on_changed(update) sheight.on_changed(update) cursor = Cursor(ax, useblit=False, color='red', linewidth=2) plt.show()
def plot_summary2(fig, rtn, entry_best, data_win, data_lose, exit_profit, exit_nbar_best, exit_nbar_worst, nbar): ''' ren: 最大回测 ''' cursors = [] winrtn = rtn.reindex(data_win.index) losertn = rtn.reindex(data_lose.index) fig.canvas.set_window_title('Summary2') ax11 = fig.add_subplot(2, 2, 1) ax11.plot(range(len(losertn)), losertn.tolist(), 'yo--', label='lost return') ax11.plot(len(losertn)+np.arange(len(winrtn)), winrtn.tolist(), 'ro--', label='win return') ax11.plot(rtn.order().tolist(), 'b') ax11.legend(loc='upper left').get_frame().set_alpha(0.5) cursors.append(Cursor(ax11, useblit=True, color='red', linewidth=1, vertOn = True, horizOn = True)) #ax11.set_xlabel('回撤', fontproperties=font_big) ax11.set_xlabel('max return') ax12 = fig.add_subplot(2, 2, 2) binwidth = (rtn.max() - rtn.min()) / 30 bins = np.arange(rtn.min(), rtn.max() + binwidth, binwidth) rst = ax12.hist(rtn, bins=bins, color = 'y' , normed=False, label='Return Distribution') n, bins = rst[0], rst[1] plot_contribution(ax12, bins, rtn, 'bo--') ax12.legend(loc='upper left').get_frame().set_alpha(0.5) cursors.append(Cursor(ax12, useblit=True, color='red', linewidth=1, vertOn = True, horizOn = True)) #ax21 = fig.add_subplot(3, 2, 3) #ds = entry_best.reindex(data_lose.index)-data_lose['exit_profit'] #ax21.plot(range(len(ds)), ds, 'yo--', label='亏损回吐') #dl = (entry_best.reindex(data_win.index)-data_win['exit_profit']).tolist() #ax21.plot(len(ds)+np.arange(len(dl)), dl, 'ro--', label='盈利回吐') #ax21.set_xticklabels([]) #ax21.set_xlabel('回吐', fontproperties=font_big) #ax21.legend(prop=font, loc='upper left').get_frame().set_alpha(0.5) #cursors.append(Cursor(ax21, useblit=True, color='red', linewidth=1, #vertOn = True, horizOn = True)) #diff = entry_best - exit_profit #ax22 = fig.add_subplot(3, 2, 4) #binwidth = (diff.max() - diff.min()) / 30 ##diff.plot(ax=ax22, kind='kde', color='b', label="") #bins = np.arange(diff.min(), diff.max() + binwidth, binwidth) #rst = ax22.hist(diff, bins=bins, color = 'y' , normed=False, label='回吐分布') #n, bins = rst[0], rst[1] #plot_contribution(ax22, bins, diff, 'bo--') #ax22.legend(prop=font, loc='upper left').get_frame().set_alpha(0.5) #cursors.append(Cursor(ax22, useblit=True, color='red', linewidth=1, #vertOn = True, horizOn = True)) if nbar>0: ax31 = fig.add_subplot(2, 2, 3) bl = (exit_nbar_best.reindex(data_lose.index)-data_lose['exit_profit']).order(ascending=False) wl = (exit_nbar_worst.reindex(data_lose.index)-data_lose['exit_profit']).reindex(bl.index) ax31.plot(range(len(bl)), bl, color='y') ax31.plot(range(len(wl)), wl, color='k') ax31.fill_between(range(len(bl)), bl, wl, facecolor='y') bw = (exit_nbar_best.reindex(data_win.index)-data_win['exit_profit']).order() ww = (exit_nbar_worst.reindex(data_win.index)-data_win['exit_profit']).reindex(bw.index) ax31.plot(len(bl)+np.arange(len(bw)), bw.tolist(), 'r') ax31.plot(len(bl)+np.arange(len(ww)), ww.tolist(), 'k') ax31.fill_between(len(bl)+np.arange(len(ww)), bw, ww, facecolor='r', label='hello') ax31.plot(range(len(bl)), data_lose['exit_profit'].abs().reindex(bl.index), 'b') cursors.append(Cursor(ax31, useblit=True, color='red', linewidth=1, vertOn = True, horizOn = True)) ax31.axhline(color='k') return [ax11, ax12, ax31], cursors
ax3.grid(True) # 画网格 # 绘制KDJ K, D, J = matix[:, 9], matix[:, 10], matix[:, 11] # 取出KDJ值 ax4.axhline(0, ls='-', c='g', lw=0.5) # 水平线 ax4.yaxis.set_ticks_position('right') # y轴显示在右边 ax4.plot(xdates, K, c='y', label='K') # 绘制K线 ax4.plot(xdates, D, c='c', label='D') # 绘制D线 ax4.plot(xdates, J, c='m', label='J') # 绘制J线 ax4.legend(loc='upper right') # 图例放置于右上角 ax4.grid(True) # 画网格 # set useblit = True on gtkagg for enhanced performance from matplotlib.widgets import Cursor # 处理鼠标 cursor = Cursor(ax1, useblit=True, color='w', linewidth=0.5, linestyle='--') plt.show() def calc_macd(df, fastperiod=12, slowperiod=26, signalperiod=9): ewma12 = df['close'].ewm(span=fastperiod, adjust=False).mean() ewma26 = df['close'].ewm(span=slowperiod, adjust=False).mean() df['dif'] = ewma12 - ewma26 df['dea'] = df['dif'].ewm(span=signalperiod, adjust=False).mean() df['bar'] = (df['dif'] - df['dea']) * 2 # df['macd'] = 0 # series = df['dif']>0 # df.loc[series[series == True].index, 'macd'] = 1 return df
def plot_entry(fig, exit_profit, entry_best, entry_worst, entry_nbar_best, entry_nbar_worst, nbar, binwidth=1): fig.canvas.set_window_title('入场信息') axescolor = '#f6f6f6' # the axes background color left, width = 0.1, 0.8 rect1 = [left, 0.7, width, 0.2]#left, bottom, width, height rect2 = [left, 0.3, width, 0.4] rect3 = [left, 0.1, width, 0.2] ax1 = fig.add_axes(rect1, facecolor=axescolor) ax2 = fig.add_axes(rect2, facecolor=axescolor, sharex = ax1) ax3 = fig.add_axes(rect3, facecolor=axescolor, sharex = ax1) (entry_best-exit_profit).plot(ax=ax1, kind='bar', grid=False, use_index=False, label="best possible profit") entry_worst.plot(ax=ax1, kind='bar', grid=False, use_index=False, color='y', label="max risk offset") if nbar>0: entry_nbar_best.plot(ax=ax3, kind='bar', color='red', grid=False, use_index=False, label="%s entry best"%nbar) entry_nbar_worst.plot(ax=ax3, kind='bar', color='y', grid=False, use_index=False, label="%s entry worst"%nbar) temp = entry_nbar_worst[entry_nbar_worst<0] ax3.plot(range(len(entry_nbar_best)), [temp.mean()]*len(entry_nbar_best), 'y--', label="av risk: %s"%temp.mean()) temp = entry_nbar_best[entry_nbar_best>0] ax3.plot(range(len(entry_nbar_best)), [temp.mean()]*len(entry_nbar_best), 'r--', label='av best: %s'%temp.mean() ) ax3.legend(loc='upper left').get_frame().set_alpha(0.5) for i in range(len(exit_profit)): if(entry_best[i]>0 and exit_profit[i]>0): px21 = ax2.bar(i, exit_profit[i], width=binwidth, color='blue') px22 = ax2.bar(i, entry_best[i]-exit_profit[i], width=binwidth, color='red', bottom = exit_profit[i]) elif(entry_best[i]<0 and exit_profit[i]<0): ax2.bar(i, entry_best[i], width=binwidth, color='red') ax2.bar(i, exit_profit[i]-entry_best[i], width=binwidth, color='blue', bottom = entry_best[i]) else: ax2.bar(i, entry_best[i], width=binwidth, color='red') ax2.bar(i, exit_profit[i], width=binwidth, color='blue') ax2.legend((px21[0], px22[0]), ('actual profit', 'entry_best profit'), loc='upper left').get_frame().set_alpha(0.5) ax1.legend(loc='upper left').get_frame().set_alpha(0.5) #ax1.set_ylabel("交易区间内的差值") #ax2.set_ylabel("交易区间内的盈利") for ax in ax1, ax2, ax3: ax.set_xticklabels([]) ax.axhline(color='k') ax3.set_xlabel("") #ax1.set_title("入场相关信息", fontproperties=font_big) ax1.set_title("entry info") c1 = Cursor(ax2, useblit=True, color='red', linewidth=1, vertOn = True, horizOn = True) multi = MultiCursor(fig.canvas, fig.axes, color='r', lw=1, horizOn=False, vertOn=True) #handle = EventHandler(exit_profit, fig) #fig.canvas.mpl_connect('motion_notify_event', handle.on_move) #fig.canvas.mpl_connect('pick_event', handle.on_pick) def format_coord(x, y): '''''' i = int(x)/1 c = pd.to_datetime(exit_profit.index[i]).strftime("%Y-%m-%d %H:%M:%S") + " Profit: %s MAE: %s"%(exit_profit[i], entry_worst[i]) return str(c) ax1.format_coord = format_coord ax2.format_coord = format_coord ax3.format_coord = format_coord return [ax1, ax2, ax3], [multi, c1]
def process(self, utc_base, ts, acc, file_name, selected=0, labels=None): self.labels = [] self.selected = selected data_len = len(acc) self.data_len = data_len aligned_utc = ts.copy() aligned_utc[0] = utc_base for i, t in enumerate(ts[1:], 1): aligned_utc[i] = aligned_utc[0] + (t - ts[0]) // 1e6 utc_date = [] for t in aligned_utc: utc_date.append( datetime.fromtimestamp(t / 1000).strftime('%m-%d %H:%M:%S')) print(f'UTC date from {utc_date[0]} to {utc_date[-1]}') print(f'Acc data shape: {acc.shape}') acc_lp = signal.filtfilt(FILTER_B, FILTER_A, acc, axis=0) mag = np.linalg.norm(acc, axis=1) mag_lp = np.linalg.norm(acc_lp, axis=1) print(f'Acc magnitude shape: {mag.shape}') # fig, ax = plt.subplots() plt.figure(file_name, figsize=(15, 8)) plt.title(file_name) plt.xticks(rotation=0) plt.locator_params(nbins=8) plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.2) plt.locator_params(axis='x', nbins=10) plt.subplot(311) plt.title(self.label_items[selected]) plt.plot(mag_lp, label='Acc low pass magnitude') ax = plt.gca() self.label_ax = ax _ = Cursor(ax, useblit=True, color='red', linewidth=2) def format_func(x_tick, pos=None): this_index = np.clip(int(x_tick + 0.5), 0, data_len - 1).item() return utc_date[this_index] ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_func)) _ = widgets.SpanSelector(ax, self.onselect, 'horizontal', rectprops=dict(facecolor='blue', alpha=0.5)) if labels is not None and len(labels) > 0: for style, start_idx, end_idx in labels: span = ax.axvspan(start_idx, end_idx, alpha=0.5) self.label_vspans.append(span) plt.grid() plt.legend(loc='upper right') plt.subplot(312, sharex=ax) plt.plot(acc_lp.T[0], label='acc_lp x') plt.plot(acc_lp.T[1], label='acc_lp y') plt.plot(acc_lp.T[2], label='acc_lp z') plt.grid() plt.legend(loc='upper right') plt.subplot(313, sharex=ax) plt.plot(mag, label='Acc raw magnitude') plt.grid() plt.legend(loc='upper right') plt.show() print(f'Label done, segments num: {len(self.labels)}: {self.labels}') return self.labels
maxLengthTimeStp = len(Zeitstempel) timeLine = [] timeTick = 0 for n in range(maxLengthTimeStp): timeLine.append(timeTick) timeTick += 1 fig, ax1 = plt.subplots() plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.10) ax1.plot(timeLine, Nettogewicht, lw=0.5, label='Nettogewicht', color='red') # Einstellungen für x/y-Achsen ax1.set_xticks(np.arange(0, timeLine[-1], 250)) ax1.set_ylim([-2, 30]) ax1.minorticks_on() cursor = Cursor(ax1, useblit=True, color='k', linewidth=1) for tick in ax1.get_xticklabels(): tick.set_rotation(75) # Weiter Kurven hinzufügen ax1.plot(timeLine, Nettoprozessgewicht, lw=0.5, label='Nettoprozessgewicht', color='purple') ax1.plot(timeLine, Grobabschaltpunkt, lw=0.5, label='Grobabschaltpunkt',
def main(sta1, sta2, filterid, components, mov_stack=1, ampli=5, seismic=False, show=False, outfile=None): db = connect() maxlag = float(get_config(db, 'maxlag')) samples = get_maxlag_samples(db) cc_sampling_rate = float(get_config(db, 'cc_sampling_rate')) start, end, datelist = build_movstack_datelist(db) base = mdates.date2num(start) plt.figure(figsize=(12, 9)) sta1 = sta1.replace('.', '_') sta2 = sta2.replace('.', '_') t = np.arange(samples) / cc_sampling_rate - maxlag if sta2 >= sta1: # alphabetical order filtering! pair = "%s:%s" % (sta1, sta2) print("New Data for %s-%s-%i-%i" % (pair, components, filterid, mov_stack)) format = "matrix" nstack, stack_total = get_results(db, sta1, sta2, filterid, components, datelist, mov_stack, format=format) ax = plt.subplot(111) for i, line in enumerate(stack_total): line /= line.max() plt.plot(t, line * ampli + i + base, c='k') if seismic: y1 = np.ones(len(line)) * i y2 = line * ampli + i + base plt.fill_between(t, y1, y2, where=y2 >= y1, facecolor='k', interpolate=True) for filterdb in get_filters(db, all=True): if filterid == filterdb.ref: low = float(filterdb.low) high = float(filterdb.high) break plt.xlabel("Lag Time (s)") plt.axhline(0, lw=0.5, c='k') plt.grid() plt.title('%s : %s, %s, Filter %d (%.2f - %.2f Hz), Stack %d' % (sta1.replace('_', '.'), sta2.replace( '_', '.'), components, filterid, low, high, mov_stack)) plt.scatter(0, [ start, ], alpha=0) plt.ylim(start, end) plt.xlim(-maxlag, maxlag) ax.fmt_ydata = mdates.DateFormatter('%Y-%m-%d') cursor = Cursor(ax, useblit=True, color='red', linewidth=1.2) if outfile: if outfile.startswith("?"): pair = pair.replace(':', '-') outfile = outfile.replace( '?', '%s-%s-f%i-m%i' % (pair, components, filterid, mov_stack)) outfile = "ccftime " + outfile print("output to:", outfile) plt.savefig(outfile) if show: plt.show()
def plot_ohlc(self): plt.sca(self.ax) self.ax.cla() self.ax1.cla() if self.d.selected_set.size == 0: print('Error: No data set is selected to display') return dt = self.d.selected_set[1, 0] - self.d.selected_set[0, 0] if dt > 0.05: widthtmp = 0.6 else: widthtmp = 0.0003 candlestick_ohlc(self.ax, self.d.selected_set, width=widthtmp, colorup='#77d879', colordown='#db3f3f') if len(self.d.holdings) > 0: try: holding = self.d.holdings[self.d.ts[self.ind]['symbol']] plt.axhline(y=holding, linewidth=4, color='r') except: pass plt.subplots_adjust(bottom=0.2) plt.title(self.d.ts[self.ind]['symbol']) for label in self.ax.xaxis.get_ticklabels(): label.set_rotation(0) self.ax.grid(True) self.ax.xaxis_date() self.ax.autoscale_view() plt.sca(self.ax1) plt.bar(self.d.ts_result[self.ind][:, 0], self.d.ts_result[self.ind][:, -1], width=widthtmp) if self.d.period >= 5: self.ax.xaxis.set_major_locator(self.months) self.ax.xaxis.set_minor_locator(self.mondays) self.ax.xaxis.set_major_formatter(self.monthFormatter) self.ax1.xaxis.set_major_locator(self.months) self.ax1.xaxis.set_minor_locator(self.mondays) self.ax1.xaxis.set_major_formatter(self.monthFormatter) elif self.d.period >= 1: self.ax.xaxis.set_major_locator(self.mondays) # self.ax.xaxis.set_minor_locator(self.alldays) self.ax.xaxis.set_major_formatter(self.weekFormatter) self.ax1.xaxis.set_major_locator(self.mondays) # self.ax1.xaxis.set_minor_locator(self.alldays) self.ax1.xaxis.set_major_formatter(self.weekFormatter) else: self.ax.xaxis.set_major_locator(self.hoursloc) self.ax.xaxis.set_minor_locator(self.minloc) self.ax.xaxis.set_major_formatter(self.minFormatter) self.ax1.xaxis.set_major_locator(self.hoursloc) self.ax1.xaxis.set_minor_locator(self.minloc) self.ax1.xaxis.set_major_formatter(self.minFormatter) self.multi = MultiCursor(self.fig_ohlc.canvas, (self.ax, self.ax1), color='r', lw=1) self.cursor = Cursor(self.ax, useblit=True, color='red', linewidth=0.2) plt.draw()
def __init__(self, window): self.window = window Counter = 0 threshold = 1100 impactThreshold = 0 threshCounter = 0 impactCounter = 0 threshTot = 0 seconds = 0 totalCount = 0 size = 0.3 yVal = 800 #window = Toplevel(main_screen) menubar = Menu(window) window.config(menu=menubar) window.geometry("1500x1500") # Set overall size of screen fileMenu = Menu(menubar) fileMenu.add_command(label="Exit", command=window.quit) menubar.add_cascade(label="Menu", menu=fileMenu) #val2=np.array([[20.,20.],[80.,80.],[20.,20.]]) threshold = 1200 cmap = plt.get_cmap("tab20c") outer_colors = cmap(np.arange(3) * 4) inner_colors = cmap([1, 2, 5, 6, 9, 10]) y = [] x = [] with open('test.txt', 'r') as csvfile: # Set file designation plots = csv.reader(csvfile) for row in plots: y.append(int(row[0])) x.append(Counter) if row: Counter += 1 for i in y: # Number of impacts over set threshold if i > threshold: threshCounter += 1 continue for i in y: # Number of impacts over ZERO if i > impactThreshold: impactCounter += 1 continue for i in x: # Number of impacts totalCount += 1 continue second = totalCount / 250 #sec = np.unique(0,(int(second))) threshCalc = threshCounter / Counter threshTot = 1 - threshCalc print("Total Above: ", threshCounter) print("Total Impacts: ", impactCounter) print("Total Points: ", Counter) print("Threshold %: ", threshCalc) print("Total Thresh %: ", threshTot) print("Impact Counter: ", impactCounter) print("Total Count: ", totalCount) print("Seconds total: ", second) vals = np.array([[10., 10.], [threshCounter, threshCounter]]) # Setting pie chart % vals2 = np.array([[50., 50.], [10., 10.]]) # sizesB = [threshCalc, threshTot] # Setting pie chart labels labelsB = 'Above %', 'Total %' sizesC = [7, 93] labelsC = 'Above %', 'Total %' # ********************************************************************** def setFunc(): plt.ion() threshold = simpledialog.askinteger( "Theshold Value ", "Enter new value: ") # FINALLY !!! a.plot([0., Counter], [threshold, threshold], "k--") print(threshold) # ****************************************************************** def clear(): #plt.ion() #threshold = 0 newVal = simpledialog.askstring("Theshold Value ", "Enter new value: ") print(newVal) l1 = Label(window, text="Threshold Exceeded: ", font="bold") l2 = Label(window, borderwidth=10, width=20, bg="mint cream", relief="flat", text="Patient ID - Name") l3 = Label(window, borderwidth=10, width=20, bg="mint cream", relief="flat", text="Data Set - Primary") l4 = Label(window, borderwidth=10, width=20, bg="mint cream", relief="flat", text="Data Set - Secondary") l5 = Label(window, text="Total Activity: ", font="bold") R2 = Label(window, text="Analysis Tools", font="bold") checkbutton = Checkbutton(window, text="Autoscale") R3 = Label(window, borderwidth=10, width=20, relief="flat", bg="mint cream", text=threshCounter) """ R4 = tk.Button(window, borderwidth = 2, width = 20, text = "Clear", bg = "mint cream", command = clear) """ R5 = Label(window, borderwidth=10, width=20, relief="flat", bg="mint cream", text=impactCounter) setThreshold = tk.Button(window, text="Set Threshold", bg="mint cream", command=setFunc) l1.grid(row=2, column=4, pady=5) l2.grid(row=2, column=0, pady=5) l3.grid(row=3, column=0, pady=5) l4.grid(row=4, column=0, pady=5) l5.grid(row=3, column=4, pady=5) #R2.grid(row = 1, column = 6, pady = 5) R3.grid(row=2, column=5, pady=5) #R4.grid(row = 4, column = 6, pady = 5) R5.grid(row=3, column=5, pady=5) #checkbutton.grid(row = 2, column = 6, pady = 5) setThreshold.grid(row=4, column=5, pady=5) fig1 = plt.figure( figsize=(6, 6), dpi=95) # Instances of individual figures for alignment fig2 = plt.figure(figsize=(4, 3), dpi=95) fig3 = plt.figure(figsize=(4, 3), dpi=95) #plt.ion() a = fig1.add_subplot(1, 1, 1) #a.subplots_adjust(bottom=0.1, right=0.8, top=0.9) a.plot(x, y, label='Loaded from file!') a.plot([0., Counter], [threshold, threshold], "k--") a.set_xlabel('Time(seconds)') a.set_ylabel('Force in Newtons') #a.set_xticks(['0','10','20','30','40','50','60','70','80']) a.set_xticklabels( ['0', '10', '20', '30', '40', '50', '60', '70', '80']) a.set_yticks([0, 250, 500, 750, 1000, 1250, 1500, 1750, 2000]) #a.xticks(x,values) b = fig2.add_subplot(1, 1, 1) # Pie chart setup b.set_title("High Activity Peaks", fontsize=12) b.pie(sizesB, labels=labelsB, autopct='%1.1f%%', colors=outer_colors, radius=1.2, shadow=True, startangle=180, wedgeprops=dict(width=size, edgecolor='w'), textprops={'fontsize': 7}) c = fig3.add_subplot(1, 1, 1) c.set_title("Total Recorded Impacts", fontsize=12) c.pie(sizesC, labels=labelsC, autopct='%1.1f%%', colors=outer_colors, radius=1.2, shadow=True, startangle=180, wedgeprops=dict(width=size, edgecolor='w'), textprops={'fontsize': 7}) canvas1 = FigureCanvasTkAgg(fig1, master=window) canvas1.draw() canvas1.get_tk_widget().grid(row=1, column=3, rowspan=4, padx=10, pady=150) # 1,2,4,50,5 canvas2 = FigureCanvasTkAgg(fig2, master=window) canvas2.draw() canvas2.get_tk_widget().grid(row=0, column=2, rowspan=4, padx=10, pady=150) canvas3 = FigureCanvasTkAgg(fig3, master=window) canvas3.draw() canvas3.get_tk_widget().grid(row=3, column=2, rowspan=4, padx=10, pady=150) # navigation toolbar toolbarFrame = Frame(master=window) toolbarFrame.grid(row=4, column=3) toolbar = NavigationToolbar2Tk(canvas1, toolbarFrame) window.cursor = Cursor(a, useblit=True, color='red', linewidth=2) #window. used for cursor
def cursor(self): #%% self.cursor = Cursor(self.ax, useblit=True, color='red', linewidth=2)
y = totalPortfolioPayoffPlot z = totalPortfolioExpPayoffPlot a = getSTKPayoff(df) b = totalTheoCallOptPayoffPlot c = totalTheoPutOptPayoffPlot d = np.array(totalCallOptExpPlot) + np.array(totalPutOptExpPlot) ax.plot(x, y, 'g', label='Theoretical Price') ax.plot(x, z, 'blue', label='At Expiry') leg = ax.legend() horiz_line_data = np.array([0 for i in range(len(x))]) ax.plot(x, horiz_line_data, 'r--') Cursor = Cursor(ax, useblit=True, color='red', linewidth=1) plt.show() '''plt.figure() plt.xlabel('Market Price') plt.ylabel('Profit/Loss') x = simulatedPrice y = totalPortfolioPayoffPlot plt.plot(x,y, linewidth =2.0) horiz_line_data = np.array([0 for i in xrange(len(x))]) plt.plot(x,horiz_line_data, 'r--') plt.show()'''
color='red', linewidth=3, marker='o', markerfacecolor='yellow', markersize=10) if (SeeMtr3 == True): plt.plot(TimeList_mtr_3, SpeedList_mtr_3, label="Motor 3", color='black', linewidth=3, marker='o', markerfacecolor='orange', markersize=10) cursor = Cursor(ax, horizOn=True, vertOn=True, color="green", linewidth=2.0) # naming the x axis plt.xlabel('Time - axis') # naming the y axis plt.ylabel('Speed - axis') # giving a title to my graph plt.title('Time v Speed') plt.legend() # for i,j in zip(TimeList_mtr_1,SpeedList_mtr_1): # ax.annotate(str(j), xy=(i,j), xytext=(0,15), textcoords='offset points') # for k,p in zip(TimeList_mtr_2,SpeedList_mtr_2): # ax.annotate(str(p), xy=(k,p), xytext=(0,15), textcoords='offset points')