def __init__(self, xv, yv, mask, **kwargs): assert xv.shape == yv.shape, 'xv and yv must have the same shape' for dx, dq in zip(xv.shape, mask.shape): assert dx==dq+1, \ '''xv and yv must be cell verticies (i.e., one cell bigger in each dimension)''' self.xv = xv self.yv = yv self.mask = mask land_color = kwargs.pop('land_color', (0.6, 1.0, 0.6)) sea_color = kwargs.pop('sea_color', (0.6, 0.6, 1.0)) cm = plt.matplotlib.colors.ListedColormap([land_color, sea_color], name='land/sea') self._pc = plt.pcolor(xv, yv, mask, cmap=cm, vmin=0, vmax=1, **kwargs) self._xc = 0.25*(xv[1:,1:]+xv[1:,:-1]+xv[:-1,1:]+xv[:-1,:-1]) self._yc = 0.25*(yv[1:,1:]+yv[1:,:-1]+yv[:-1,1:]+yv[:-1,:-1]) if isinstance(self.xv, np.ma.MaskedArray): self._mask = mask[~self._xc.mask] else: self._mask = mask.flatten() plt.connect('button_press_event', self._on_click) plt.connect('key_press_event', self._on_key) self._clicking = False plt.title('Editing %s -- click "e" to toggle' % self._clicking) plt.draw()
def analisis_grafica(carpeta, nombre): fig = plt.figure() ax = plt.subplot(111) # prueba=cm.comtrade(carpeta, nombre) # prueba.config() # prueba.extraerDatos() # A=prueba.oscilografia[:,11] # B=prueba.oscilografia[:,10] # C=prueba.oscilografia[:,9] plt.plot(A, "g", label="A") plt.plot(B, "r", label="B") plt.plot(C, "y", label="C") plt.suptitle(u"Seleccione el ciclo prefalla") # Ponemos un titulo superior plt.legend() # Creamos la caja con la leyenda binding_id = plt.connect("motion_notify_event", on_move) plt.connect("button_press_event", on_click) """if "test_disconnect" in sys.argv: print("disconnecting console coordinate printout...") plt.disconnect(binding_id)""" # plt.ion() # Ponemos el modo interactivo # plt.axvspan(-0.5,0.5, alpha = 0.25) plt.show()
def ROI_define(): im=mpimg.imread(image) height=im.shape[0] / nrow width=im.shape[1] / ncol # Axis adjustable in function of views during acquisition fig=plt.figure(figsize=(10, 10 * height / width)) plt.imshow(im) plt.grid(True) plt.xticks([width * i for i in range(1, ncol)]) plt.yticks([height * i for i in range(1, nrow)]) # Add mouse click event to set area of interest ax2=fig.add_subplot(111) ax2.patch.set_alpha(0.5) cnv=Canvas(ax2) plt.connect('button_press_event', cnv.update_path) plt.connect('motion_notify_event', cnv.set_location) plt.show() # Deal with polygon poly=cnv.extract_poly() poly, scaleX, scaleY=coordinate_conversion( poly, im.shape[1], im.shape[0]) return poly, scaleX, scaleY
def twoDplots(self, ind1, ind2): """ Provides a plot of a two-dimensional slice of eigenvector space. """ afs = [] fig = plt.figure() s1 = fig.add_subplot(111) s1.scatter(self.eigvecs[:, ind1], self.eigvecs[:, ind2], c="w") afs.append( AnnoteModule.AnnoteFinder(self.eigvecs[:, ind1], self.eigvecs[:, ind2], self.resnames, xtol=5, ytol=5) ) plt.connect("button_press_event", afs[-1]) s1.set_xlabel("$|" + str(ind1) + ">$") s1.set_ylabel("$|" + str(ind2) + ">$") # fig.suptitle('Eigenvector projections') try: for sec in self.listofsecs: s1.scatter( self.eigvecs[sec.members, ind1], self.eigvecs[sec.members, ind2], c=sec.weights, cmap=sec.seccolor, norm=matplotlib.colors.Normalize(vmin=0, vmax=0.3), ) except AttributeError: print "No sectors have been defined for this matrix yet. Call twoDxcc to get them if desired." return fig
def plot(self, multiview=False): """ Plotten der Oberflaeche: plot(multiview=False) multiview: True: Two plotfields side by side; False: One single plotfield - Space-bar: show next surface. - '[1-9]': show every 2nd surface - '0': show last surface - 'r': show first surface - 'a': switch plot aspect 1:1 <==> auto - 'c': switch between two modi, single plot, multiple plot for surfaces - 'f': save plot as (png-)file with the name of the xxx.srf file - 'b': switch between fixed axis and auto axis of new surface - 'q': Quit. """ help(plot.plot) if not multiview: self.multi = False self.ax1 = plt.subplot(1, 1, 1) else: self.multi = True self.ax1 = plt.subplot(1, 2, 1) self.ax2 = plt.subplot(1, 2, 2) self.event_handler(None) plt.connect("key_press_event", self.event_handler) plt.show()
def imrect(image): """ Best python hack of MATLAB's imrect that I could come up with :param image: a numpy array :return: returns the bounds of the selected roi """ print('Click and drag to select ROI. Press "Enter" to proceed.') fig = plt.figure('ROI selection') plt.imshow(image) ax = plt.axes() def nothing(eclick, erelease): pass bounds = None def on_enter(event): if event.key == 'enter' and selector._rect_bbox != (0., 0., 0., 1.): nonlocal bounds bounds = [int(i) for i in selector._rect_bbox] plt.close(fig) selector = widgets.RectangleSelector(ax, nothing, drawtype='box', interactive=True) plt.connect('key_press_event', on_enter) plt.show() # blocks execution until on_enter() completes return bounds
def plot_vi_breakdown_panel(px, h, title, xlab, ylab, hlines, scatter_size, **kwargs): """Plot a single panel (over or undersegmentation) of VI breakdown plot. Parameters ---------- px : np.ndarray of float, shape (N,) The probability (size) of each segment. h : np.ndarray of float, shape (N,) The conditional entropy of that segment. title, xlab, ylab : string Parameters for `matplotlib.plt.plot`. hlines : iterable of float Plot hyperbolic lines of same VI contribution. For each value `v` in `hlines`, draw the line `h = v/px`. scatter_size : int, optional **kwargs : dict Additional keyword arguments for `matplotlib.pyplot.plot`. Returns ------- None """ x = np.arange(max(min(px),1e-10), max(px), (max(px)-min(px))/100.0) for val in hlines: plt.plot(x, val/x, color='gray', ls=':', **kwargs) plt.scatter(px, h, label=title, s=scatter_size, **kwargs) # Make points clickable to identify ID. This section needs work. af = AnnotationFinder(px, h, [str(i) for i in range(len(px))]) plt.connect('button_press_event', af) plt.xlim(xmin=-0.05*max(px), xmax=1.05*max(px)) plt.ylim(ymin=-0.05*max(h), ymax=1.05*max(h)) plt.xlabel(xlab) plt.ylabel(ylab) plt.title(title)
def analisis_grafica(self): #prueba=cm.comtrade(carpeta, nombre) #prueba.config() #prueba.extraerDatos() #A=prueba.oscilografia[:,11] #B=prueba.oscilografia[:,10] #C=prueba.oscilografia[:,9] alt.plot(self.A,'g',label='A') alt.plot(self.B,'r',label='B') alt.plot(self.C,'y',label='C') alt.suptitle(u'Seleccione el ciclo prefalla') # Ponemos un titulo superior alt.legend() # Creamos la caja con la leyenda binding_id = alt.connect('motion_notify_event', on_move) alt.connect('button_press_event', on_click) '''if "test_disconnect" in sys.argv: print("disconnecting console coordinate printout...") plt.disconnect(binding_id)''' #plt.ion() # Ponemos el modo interactivo #plt.axvspan(-0.5,0.5, alpha = 0.25) alt.show()
def turnon(self, event, current_ax): self.Fiddle = True toggle_selector.RS = RectangleSelector(current_ax, self.line_select_callback, drawtype='box', useblit=True, button=[3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels') plt.connect('key_press_event', toggle_selector)
def view(self,comparer=None,grayScale=False): self.grayScale= grayScale self.comparer = comparer self.fig = plt.figure("Image Viewer") self.ax = plt.subplot(111) self._event_fct(None) # initial setup plt.connect('key_press_event', self._event_fct) plt.show()
def __init__(self, environment): self.signal = False self.environment = environment plt.ion() plt.axis([0,environment.width,0,environment.height]) plt.connect('key_press_event', self.event) plt.show() self.draw() plt.pause(100)
def configureFigure(self): #http://stackoverflow.com/questions/12439588/how-to-maximize-a-plt-show-window-using-python mng = plt.get_current_fig_manager() #mng.resize(*mng.window.maxsize()) mng.window.wm_geometry("+0+0") #http://stackoverflow.com/questions/6541123/improve-subplot-size-spacing-with-many-subplots-in-matplotlib plt.subplots_adjust(left=0.09, right=0.95, bottom=0.05, top=0.95, wspace=0.2, hspace=0.5) #http://matplotlib.org/examples/event_handling/keypress_demo.html plt.connect('key_press_event', pressHandler)
def point(x,y,annotation,r,p,c,cmap,ytol): a=[x] b=[y] n=[annotation] s=[r*r] color=matplotlib.colors.colorConverter.to_rgb(cmap(1.+log10(c))) #sctpt=ax.scatter(a,b,s=s,color=color,cmap=cmap,edgecolors='black') sctpt=pylab.gca().scatter(a,b,s=s,color=color,cmap=cmap,alpha=1.,picker=5) af1 = AnnoteFinder(a,b,n,xtol=r,ytol=ytol,pos=p) P.connect('button_press_event',af1) return sctpt
def plotEvents(catalog, client=None, **kwargs): """ Plot events on map. When client is given it shows the waveform when the event is clicked. IPython may not be started in pylab mode for this feature working. """ def onpress(event): if not event.inaxes or event.key != "shift": return lon, lat = map(event.xdata, event.ydata, inverse=True) dlon = 0.05 dlat = 0.05 filter = "%f < latitude < %f and %f < longitude < %f" % (lat - dlat, lat + dlat, lon - dlon, lon + dlon) ev = catalog.filter2(filter) if len(ev) == 0: print "No event picked" return from sito import Stream st = Stream() print "Selcet", ev for arrival in ev[0].origins[0].arrivals: arrival.pick_id.convertIDToQuakeMLURI() pick = arrival.pick_id.getReferredObject() if not pick: print "FAIL" return time = pick.time seed_id = pick.waveform_id.getSEEDString() try: st1 = Stream(client.getWaveform(*(seed_id.split(".") + [time - 50, time + 250]))) except Exception as ex: print "%s for %s" % (ex, seed_id) continue st1.merge() print "load %s %s %.1f" % (seed_id, pick.phase_hint, time - ev[0].origins[0].time) st1[0].stats["label"] = "%s %s %.1f" % (seed_id, pick.phase_hint, time - ev[0].origins[0].time) st += st1 st.setHI("filter", "") st.filter2(2, None) # st.plot(automerge=False, method='fast', type='relative') im = st.plot_() plt.show() if client is None: catalog.plot(**kwargs) else: map, ax = catalog.plot(handle=True, **kwargs) plt.connect("button_press_event", onpress) plt.show()
def signalPlot(time, data, names): plt.figure(1) colors =['r', '#FCBDB1', 'g', '#B6FAC4', 'b', '#CAB6FA', 'c'] ax = plt.subplot(111) for x in range(len(data)): ax.plot(time, data[x], c=colors[x], label=names[x]) plt.legend() selector.keyPressed.RS = RectangleSelector(ax, selector.onselect, drawtype='box', rectprops=dict(facecolor='red', edgecolor = 'black', alpha=0.5, fill=True)) plt.connect('key_press_event', selector.keyPressed) plt.show() plt.show()
def plot(fname,multiview=False): ''' Plotten der Oberflaeche: plot(fname,multiview=False) fname is the file name e.g. trench.srf multiview: True: Two plotfields side by side; False: One single plotfield - Space-bar: show next surface. - '[1-9]': show every 2nd surface - '0': show last surface - 'r': show first surface - 'a': switch plot aspect 1:1 <==> auto - 'c': switch between two modi, single plot, multiple plot for surfaces - 'f': save plot as (png-)file with the name of the xxx.srf file - 'b': switch between fixed axis and auto axis of new surface - 'q': Quit. ''' help(plot) global abs_filepath global number_of_surfaces global ax1 global ax2 global filename global multi filename = fname multi = multiview abs_filepath = get_filepath(fname) count_surfaces() number_of_surfaces = count_surfaces() number = 1 while get_surfacedata(number) != None: # get data from surfaces to plot them x_Vals_tmp, y_Vals_tmp = get_surfacedata(number) x_Vals.append(x_Vals_tmp) y_Vals.append(y_Vals_tmp) number = number + 1 if number > number_of_surfaces: break if multi: f, (ax1, ax2) = plt.subplots(1, 2, sharey=True) else: ax1 = plt.subplot(111) event_handler(None) plt.connect('key_press_event', event_handler) plt.show()
def __init__(self, ax, x, y, rescale, shift, offsets=(-20, 20)): self.x = np.asarray(x, dtype='float') y = np.asarray(y, dtype='float') self._points = np.column_stack((x, y)) self.rescale = rescale self.shift = shift self.tree = spatial.cKDTree(self._points) self.ax = ax self.fig = ax.figure self.dot = ax.scatter([0], [y.min()], s=130, color='green', alpha=0.7,animated=True) self.annotation = self.ax.annotate('', xy=(0, 0), ha = 'right', xytext = offsets, textcoords = 'offset points', va = 'bottom', bbox = dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.75,animated=True), arrowprops = dict(arrowstyle='->', connectionstyle='arc3,rad=0',animated=True),animated=True) self.background = None plt.connect('motion_notify_event', self)
def main(): global rgb, hsv, fig, window args = parse_arguments() image = cv2.imread(args.image) if args.blur > 0: image = cv2.GaussianBlur(image, (args.blur, args.blur), 0) window = args.window rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) fig = plt.figure() plot(fig, rgb, hsv, (window, window), no_labels=args.no_labels) plt.connect('pick_event', onpick) plt.show()
def selectable_plot(*args, **kwargs): fig, current_ax = plt.subplots() # make a new plotingrange plt.plot(*args, **kwargs) # plot something # drawtype is 'box' or 'line' or 'none' toggle_selector.RS = RectangleSelector(current_ax, line_select_callback, drawtype='box', useblit=True, button=[1,3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels') plt.connect('key_press_event', toggle_selector) plt.show()
def plot_matrix(A, title=None, labels=None, vocab=None, fig=None): # cmap = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0.25, 0.75, 0], [0.25, 0, 0.75], [0, 0.5, 0.5], [0.75, 0.25, 0], [0.75, 0, 0.25], [0, 0.75, 0.25], [0, 0.25, 0.75]] cmap = [ [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [0, 1, 1], ] # , [1, 0, 1], [1, 0.5, 0], [0.5, 0, 1], [0.5, 1, 0], [0.98, 0.39, 0]] cl = len(cmap) markers = ["o", "d", ">", (5, 1)] ml = len(markers) if not vocab: vocab = range(A.shape[0]) res = np.array([x for x in bh_tsne(A, verbose=True)]) if not fig: plt.figure() else: plt.figure(fig) if title: plt.title(title) # if all(labels) != None: # plt.scatter(res[:, 0], res[:, 1], s=20, c=labels, alpha=0.5) # else: # plt.scatter(res[:, 0], res[:, 1], s=20, alpha=0.5) for col in xrange(A.shape[1]): top_word = np.argmax(A[:, col]) mk = (col // cl) % ml colors = np.zeros((A.shape[0], 4)) colors[:, 0] = cmap[col % cl][0] colors[:, 1] = cmap[col % cl][1] colors[:, 2] = cmap[col % cl][2] colors[:, -1] = A[:, col] / A[top_word, col] plt.scatter(res[:, 0], res[:, 1], c=colors, marker=markers[mk], s=30, edgecolor="none") plt.scatter( res[top_word, 0], res[top_word, 1], c=cmap[col % cl], marker=markers[mk], s=30, edgecolor="none", label=u"тема #" + str(col), ) if all(vocab) != None: af = AnnoteFinder(res[:, 0], res[:, 1], vocab, xtol=0.1, ytol=0.1) plt.connect("button_press_event", af) plt.legend(scatterpoints=1, loc="best", ncol=3, fontsize=9) plt.draw() return res
def plot_click(data=None): """Plot dummy data and handle user clicks.""" # Generate data if data is None: data = np.arange(10000).reshape(100, 100) # Show data plt.imshow(data) # Register click events plt.connect('button_press_event', _on_click) # Show plot plt.show()
def __init__(self, ax, index, x, y, tolerance, formatter, offsets=(-20, 20)): self._points = numpy.column_stack((x, y)) self._index = index self.offsets = offsets self.scale = x.ptp() self.scale = y.ptp() / self.scale if self.scale else 1 self.tree = spatial.cKDTree(self.scaled(self._points)) self.formatter = formatter self.tolerance = tolerance self.ax = ax self.fig = ax.figure self.dot = ax.scatter( [x.min()], [y.min()], s=130, color='green', alpha=0.7) self.annotation = self.setup_annotation() pyplot.connect('button_press_event', self)
def test_surface(): dir_path = os.path.dirname(os.path.abspath(__file__)) par.init() par.read(os.path.join(dir_path, 'test_surface.cfg')) surface = Surface() print('PRESS ANY KEY TO EXIT THE PLOT') for t in arange(1, par.TOTAL_TIME + par.TIME_STEP, par.TIME_STEP): surface.process(par.TIME_STEP) plt.title('Test Surface{0}'.format(t)) plt.plot(surface.xvals, surface.yvals, '.r-') plt.xlabel('x') plt.ylabel('y') plt.connect('key_press_event', event) plt.show()
def get_initparams_from_mouse( halfwidth=5.0 ): """ Assuming you've already plotted the data you want to fit, this function makes a list of initparams from your mouse clicks on the peaks you want to fit. """ print 'Picking peaks only (not peaks and widths; see code)' peaks_or_peakswidths='p' #peaks_or_peakswidths = raw_input('Pick only peaks (p) or peaks and widths (pw)') if peaks_or_peakswidths=='p': if True: # explitly use "connect" to get points peaks = [] # this will be a list of dictionaries of xloc and height of each peak def click(event): print 'you clicked', event.xdata peaks.append({'xloc':event.xdata, 'ymax':event.ydata}) cid = plt.connect('button_press_event', click) raw_input('Click on the peaks you want to fit, then press Enter to continue.\n') plt.disconnect(cid) else: # use ginput print ('Click on the peaks you want to fit, then press Enter to continue.\n') points = plt.ginput(-1) peaks = [{'xloc':p[0], 'ymax':p[1]} for p in points] elif peaks_or_peakswidths=='pw': print 'This function is not yet implemented' peaks = [] else: print 'Incorrect input.' peaks = [] initparams=[0.0] # this is the initial guess at yoffset for peak in peaks: initparams.append(peak['ymax']) initparams.append( halfwidth ) initparams.append(peak['xloc']) return initparams
def plot_vorbereiten(range): # Plotbereiche vorbereiten f, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(22, 10)) # Plot-Bereich 1 ax1.axis(range) ax1.set_xlabel("x") ax1.set_ylabel("p") ax1.set_title("Phasenraubahn des Teilchens") # Plot-Bereich 2 ax2.axis(range) ax2.set_xlabel("x") ax2.set_ylabel("p") ax2.set_title("Stroboskop-Darstellung der Phasenraubahn") # Verbindung mit Maus herstellen plt.connect("button_press_event", maus_klick) return ax1, ax2
def __init__(self, ax, img, threshold): self.ax = ax self.img = img self.threshold = threshold self.cid = plt.connect('button_press_event', self)
def plot(fname): ''' Plotten der Oberflaeche: plot(fname) fname is the file name e.g. trench.srf - Space-bar: show next surface. - '[1-9]': show every 2nth surface - '0': show last surface - 'r': show first surface - 'a': switch plot aspect 1:1 <==> auto - 'c': switch between two modi, single plot, multiple plot for surfaces - 'f': save plot as (png-)file with the name of the xxx.srf file - 'b': switch between fixed axis and auto axis of new surface - 'q': Quite. ''' help(plot) global abs_filepath global number_of_surfaces global ax global filename filename = fname abs_filepath = get_filepath(fname) count_surfaces() number_of_surfaces = count_surfaces() number = 1 while get_surfacedata(number) != None: # get data from surfaces to plot them x_Vals_tmp, y_Vals_tmp = get_surfacedata(number) x_Vals.append(x_Vals_tmp) y_Vals.append(y_Vals_tmp) number = number + 1 if number > number_of_surfaces: break ax = plt.subplot(111) event_handler(None) plt.connect('key_press_event', event_handler) plt.show()
def scatter_annotate(x, y, labels, xtol=None, ytol=None, ax=None,*args, **kwargs): if ax is None: axi = plt else: axi = ax if len(labels) != len(x): threedhst.showMessage('`x`, `y`, and `labels` inputs must be same size', warn=True) return False if not isinstance(labels, list): labels = list(labels) plt.scatter(x, y, *args, **kwargs) af = AnnoteFinder(x, y, labels, xtol=xtol, ytol=ytol, axis=ax) plt.connect('button_press_event', af) return af
def getClickData(): def onclick(event): global data, plt sys.stdout.write("\t\tAdded 50 points with a mean of ("+`event.xdata`+", "+`event.ydata`+")\n") data = data + genDataPoints(event.xdata, 14, event.ydata, 10, 50) x, y = getX_Y(data) plt.plot(x, y, 'ro') return event.xdata, event.ydata plt.ion() plt.figure() plt.plot(0, 0, 'ro') plt.plot(200, 200, 'ro') plt.title('Click to add data') plt.connect('button_press_event', onclick) raw_input("\tPress enter when complete:\n\n ") plt.close() return np.matrix(data)
def __init__(self, ax, *args, selfunc=None, parent=None, verbose=False, **kwargs): # ====================================== # Store things to class # ====================================== self._parent = parent self._selfunc = selfunc self._ax = ax self.verbose = verbose self._selfunc_results = None self._x0 = 0 self._x1 = 1 self._y0 = 0 self._y1 = 1 # ====================================== # Add rectangle selector # ====================================== self._RectangleSelector = _mw.RectangleSelector(ax, self._onselect, *args, **kwargs) _plt.connect('key_press_event', self._toggle)
def line_select_callback(eclick, erelease): 'eclick and erelease are the press and release events' x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata print("(%3.2f, %3.2f) --> (%3.2f, %3.2f)" % (x1, y1, x2, y2)) print(" The button you used were: %s %s" % (eclick.button, erelease.button)) def toggle_selector(event): print(' Key pressed.') if event.key in ['Q', 'q'] and toggle_selector.RS.active: print(' RectangleSelector deactivated.') toggle_selector.RS.set_active(False) if event.key in ['A', 'a'] and not toggle_selector.RS.active: print(' RectangleSelector activated.') toggle_selector.RS.set_active(True) # drawtype is 'box' or 'line' or 'none' toggle_selector.RS = RectangleSelector( plt.gca(), line_select_callback, drawtype='box', useblit=True, button=[1, 3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels', interactive=True) plt.connect('key_press_event', toggle_selector) plt.show()
def _plot_timeseries(ax, ch_idx, tmin, tmax, vmin, vmax, ylim, data, color, times, vline=None, x_label=None, y_label=None, colorbar=False, hline=None, hvline_color='w', labels=None): """Show time series on topo split across multiple axes.""" import matplotlib.pyplot as plt from matplotlib.colors import colorConverter picker_flag = False for data_, color_ in zip(data, color): if not picker_flag: # use large tol for picker so we can click anywhere in the axes ax.plot(times, data_[ch_idx], color=color_, picker=1e9) picker_flag = True else: ax.plot(times, data_[ch_idx], color=color_) if x_label is not None: ax.set(xlabel=x_label) if y_label is not None: if isinstance(y_label, list): ax.set_ylabel(y_label[ch_idx]) else: ax.set_ylabel(y_label) def _format_coord(x, y, labels, ax): """Create status string based on cursor coordinates.""" idx = np.abs(times - x).argmin() ylabel = ax.get_ylabel() unit = (ylabel[ylabel.find('(') + 1:ylabel.find(')')] if '(' in ylabel and ')' in ylabel else '') labels = [''] * len(data) if labels is None else labels # try to estimate whether to truncate condition labels slen = 10 + sum([12 + len(unit) + len(label) for label in labels]) bar_width = (ax.figure.get_size_inches() * ax.figure.dpi)[0] / 5.5 trunc_labels = bar_width < slen s = '%6.3f s: ' % times[idx] for data_, label in zip(data, labels): s += '%7.2f %s' % (data_[ch_idx, idx], unit) if trunc_labels: label = (label if len(label) <= 10 else '%s..%s' % (label[:6], label[-2:])) s += ' [%s] ' % label if label else ' ' return s ax.format_coord = lambda x, y: _format_coord(x, y, labels=labels, ax=ax) def _cursor_vline(event): """Draw cursor (vertical line).""" ax = event.inaxes if not ax: return if ax._cursorline is not None: ax._cursorline.remove() ax._cursorline = ax.axvline(event.xdata, color=ax._cursorcolor) ax.figure.canvas.draw() def _rm_cursor(event): ax = event.inaxes if ax._cursorline is not None: ax._cursorline.remove() ax._cursorline = None ax.figure.canvas.draw() ax._cursorline = None # choose cursor color based on perceived brightness of background try: facecol = colorConverter.to_rgb(ax.get_facecolor()) except AttributeError: # older MPL facecol = colorConverter.to_rgb(ax.get_axis_bgcolor()) face_brightness = np.dot(facecol, np.array([299, 587, 114])) ax._cursorcolor = 'white' if face_brightness < 150 else 'black' plt.connect('motion_notify_event', _cursor_vline) plt.connect('axes_leave_event', _rm_cursor) _setup_ax_spines(ax, vline, tmin, tmax) ax.figure.set_facecolor('k' if hvline_color is 'w' else 'w') ax.spines['bottom'].set_color(hvline_color) ax.spines['left'].set_color(hvline_color) ax.tick_params(axis='x', colors=hvline_color, which='both') ax.tick_params(axis='y', colors=hvline_color, which='both') ax.title.set_color(hvline_color) ax.xaxis.label.set_color(hvline_color) ax.yaxis.label.set_color(hvline_color) if vline: plt.axvline(vline, color=hvline_color, linewidth=1.0, linestyle='--') if hline: plt.axhline(hline, color=hvline_color, linewidth=1.0, zorder=10) if colorbar: plt.colorbar()
"ro-") # sum axis 2 ax0.axis("scaled") ax1.axis("scaled") ax2.axis("scaled") ax3.axis("auto") ax0.set_title("horizontal=X vertical=Y") ax1.set_title("horizontal=X vertical=rocking curve") ax2.set_title("horizontal=Y vertical=rocking curve") ax3.set_xlabel("q (1/A)") ax3.set_ylabel("PRTF") res_text = fig_prtf.text(0.55, 0.25, "", size=10) fig_prtf.text(0.55, 0.15, "click to read the resolution", size=10) fig_prtf.text(0.01, 0.8, "click to select\nthe endpoint", size=10) fig_prtf.text(0.01, 0.7, "q to quit\ns to save", size=10) plt.tight_layout() plt.connect("key_press_event", press_key) plt.connect("button_press_event", on_click) fig_prtf.set_facecolor(background_plot) plt.show() ################################# # average over spherical shells # ################################# print(f"\nDistance max: {distances_q.max():.2f}(1/A) at:" f" {np.unravel_index(abs(distances_q).argmax(), distances_q.shape)}") nb_bins = numz // 3 prtf_avg = np.zeros(nb_bins) dq = distances_q.max() / nb_bins # in 1/A q_axis = np.linspace(0, distances_q.max(), endpoint=True, num=nb_bins + 1) # in 1/A
def showMatrix(matrix, x_array=None, y_array=None, **kwargs): """Show a matrix using :meth:`~matplotlib.axes.Axes.imshow`. Curves on x- and y-axis can be added. :arg matrix: matrix to be displayed :type matrix: :class:`~numpy.ndarray` :arg x_array: data to be plotted above the matrix :type x_array: :class:`~numpy.ndarray` :arg y_array: data to be plotted on the left side of the matrix :type y_array: :class:`~numpy.ndarray` :arg percentile: a percentile threshold to remove outliers, i.e. only showing data within *p*-th to *100-p*-th percentile :type percentile: float :arg interactive: turn on or off the interactive options :type interactive: bool """ from matplotlib import ticker from matplotlib.gridspec import GridSpec from matplotlib.collections import LineCollection from matplotlib.pyplot import gca, sca, sci, colorbar, subplot p = kwargs.pop('percentile', None) vmin = vmax = None if p is not None: vmin = np.percentile(matrix, p) vmax = np.percentile(matrix, 100 - p) vmin = kwargs.pop('vmin', vmin) vmax = kwargs.pop('vmax', vmax) lw = kwargs.pop('linewidth', 1) W = H = kwargs.pop('ratio', 6) ticklabels = kwargs.pop('ticklabels', None) xticklabels = kwargs.pop('xticklabels', ticklabels) yticklabels = kwargs.pop('yticklabels', ticklabels) show_colorbar = kwargs.pop('colorbar', True) allticks = kwargs.pop( 'allticks', False ) # this argument is temporary and will be replaced by better implementation interactive = kwargs.pop('interactive', True) cmap = kwargs.pop('cmap', 'jet') origin = kwargs.pop('origin', 'lower') tree_mode = False try: from Bio import Phylo except ImportError: raise ImportError('Phylo module could not be imported. ' 'Reinstall ProDy or install Biopython ' 'to solve the problem.') tree_mode = isinstance(y_array, Phylo.BaseTree.Tree) if x_array is not None and y_array is not None: nrow = 2 ncol = 2 i = 1 j = 1 width_ratios = [1, W] height_ratios = [1, H] aspect = 'auto' elif x_array is not None and y_array is None: nrow = 2 ncol = 1 i = 1 j = 0 width_ratios = [W] height_ratios = [1, H] aspect = 'auto' elif x_array is None and y_array is not None: nrow = 1 ncol = 2 i = 0 j = 1 width_ratios = [1, W] height_ratios = [H] aspect = 'auto' else: nrow = 1 ncol = 1 i = 0 j = 0 width_ratios = [W] height_ratios = [H] aspect = kwargs.pop('aspect', None) main_index = (i, j) upper_index = (i - 1, j) left_index = (i, j - 1) complex_layout = nrow > 1 or ncol > 1 ax1 = ax2 = ax3 = None if complex_layout: gs = GridSpec(nrow, ncol, width_ratios=width_ratios, height_ratios=height_ratios, hspace=0., wspace=0.) lines = [] if nrow > 1: ax1 = subplot(gs[upper_index]) if not tree_mode: ax1.set_xticklabels([]) y = x_array xp, yp = interpY(y) points = np.array([xp, yp]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lcy = LineCollection(segments, array=yp, linewidths=lw, cmap=cmap) lines.append(lcy) ax1.add_collection(lcy) ax1.set_xlim(xp.min(), xp.max()) ax1.set_ylim(yp.min(), yp.max()) ax1.axis('off') if ncol > 1: ax2 = subplot(gs[left_index]) if tree_mode: Phylo.draw(y_array, do_show=False, axes=ax2) else: ax2.set_xticklabels([]) y = y_array xp, yp = interpY(y) points = np.array([yp, xp]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lcx = LineCollection(segments, array=yp, linewidths=lw, cmap=cmap) lines.append(lcx) ax2.add_collection(lcx) ax2.set_xlim(yp.min(), yp.max()) ax2.set_ylim(xp.min(), xp.max()) ax2.invert_xaxis() ax2.axis('off') if complex_layout: ax3 = subplot(gs[main_index]) else: ax3 = gca() im = ax3.imshow(matrix, aspect=aspect, vmin=vmin, vmax=vmax, cmap=cmap, origin=origin, **kwargs) #ax3.set_xlim([-0.5, matrix.shape[0]+0.5]) #ax3.set_ylim([-0.5, matrix.shape[1]+0.5]) if xticklabels is not None: ax3.xaxis.set_major_formatter(ticker.IndexFormatter(xticklabels)) if yticklabels is not None and ncol == 1: ax3.yaxis.set_major_formatter(ticker.IndexFormatter(yticklabels)) if allticks: ax3.xaxis.set_major_locator(ticker.IndexLocator(offset=0.5, base=1.)) ax3.yaxis.set_major_locator(ticker.IndexLocator(offset=0.5, base=1.)) else: locator = ticker.AutoLocator() locator.set_params(integer=True) minor_locator = ticker.AutoMinorLocator() ax3.xaxis.set_major_locator(locator) ax3.xaxis.set_minor_locator(minor_locator) locator = ticker.AutoLocator() locator.set_params(integer=True) minor_locator = ticker.AutoMinorLocator() ax3.yaxis.set_major_locator(locator) ax3.yaxis.set_minor_locator(minor_locator) if ncol > 1: ax3.yaxis.set_major_formatter(ticker.NullFormatter()) cb = None if show_colorbar: if nrow > 1: axes = [ax1, ax2, ax3] while None in axes: axes.remove(None) s = H / (H + 1.) cb = colorbar(mappable=im, ax=axes, anchor=(0, 0), shrink=s) else: cb = colorbar(mappable=im) sca(ax3) sci(im) if interactive: from prody.utilities import ImageCursor from matplotlib.pyplot import connect cursor = ImageCursor(ax3, im) connect('button_press_event', cursor.onClick) return im, lines, cb
def connect(self): plt.connect('motion_notify_event', self.mouse_move) plt.connect('button_press_event', self.button_press) plt.connect('button_release_event', self.button_release)
nz, ny, nx = np.shape(data) width = 5 max_colorbar = 5 flag_aliens = True # in XY dim = 0 fig_mask = plt.figure() idx = starting_frame[0] original_data = np.copy(data) plt.imshow(data[idx, :, :], vmin=0, vmax=max_colorbar) plt.title( "Frame " + str(idx + 1) + "/" + str(nz) + "\n" "m mask ; b unmask ; q quit ; u next frame ; d previous frame\n" "up larger ; down smaller ; right darker ; left brighter") plt.connect('key_press_event', press_key) fig_mask.set_facecolor(background_plot) plt.show() del dim, fig_mask # in XZ dim = 1 fig_mask = plt.figure() idx = starting_frame[1] plt.imshow(data[:, idx, :], vmin=0, vmax=max_colorbar) plt.title( "Frame " + str(idx + 1) + "/" + str(ny) + "\n" "m mask ; b unmask ; q quit ; u next frame ; d previous frame\n" "up larger ; down smaller ; right darker ; left brighter") plt.connect('key_press_event', press_key) fig_mask.set_facecolor(background_plot)
def _plot_timeseries(ax, ch_idx, tmin, tmax, vmin, vmax, ylim, data, color, times, vline=None, x_label=None, y_label=None, colorbar=False, hline=None, hvline_color='w', labels=None): """Show time series on topo split across multiple axes.""" import matplotlib.pyplot as plt from matplotlib.colors import colorConverter picker_flag = False for data_, color_, times_ in zip(data, color, times): if not picker_flag: # use large tol for picker so we can click anywhere in the axes line = ax.plot(times_, data_[ch_idx], color=color_, picker=True)[0] line.set_pickradius(1e9) picker_flag = True else: ax.plot(times_, data_[ch_idx], color=color_) def _format_coord(x, y, labels, ax): """Create status string based on cursor coordinates.""" # find indices for datasets near cursor (if any) tdiffs = [np.abs(tvec - x).min() for tvec in times] nearby = [ k for k, tdiff in enumerate(tdiffs) if tdiff < (tmax - tmin) / 100 ] xlabel = ax.get_xlabel() xunit = (xlabel[xlabel.find('(') + 1:xlabel.find(')')] if '(' in xlabel and ')' in xlabel else 's') timestr = '%6.3f %s: ' % (x, xunit) if not nearby: return '%s Nothing here' % timestr labels = [''] * len(nearby) if labels is None else labels nearby_data = [(data[n], labels[n], times[n]) for n in nearby] ylabel = ax.get_ylabel() yunit = (ylabel[ylabel.find('(') + 1:ylabel.find(')')] if '(' in ylabel and ')' in ylabel else '') # try to estimate whether to truncate condition labels slen = 9 + len(xunit) + sum( [12 + len(yunit) + len(label) for label in labels]) bar_width = (ax.figure.get_size_inches() * ax.figure.dpi)[0] / 5.5 # show labels and y values for datasets near cursor trunc_labels = bar_width < slen s = timestr for data_, label, tvec in nearby_data: idx = np.abs(tvec - x).argmin() s += '%7.2f %s' % (data_[ch_idx, idx], yunit) if trunc_labels: label = (label if len(label) <= 10 else '%s..%s' % (label[:6], label[-2:])) s += ' [%s] ' % label if label else ' ' return s ax.format_coord = lambda x, y: _format_coord(x, y, labels=labels, ax=ax) def _cursor_vline(event): """Draw cursor (vertical line).""" ax = event.inaxes if not ax: return if ax._cursorline is not None: ax._cursorline.remove() ax._cursorline = ax.axvline(event.xdata, color=ax._cursorcolor) ax.figure.canvas.draw() def _rm_cursor(event): ax = event.inaxes if ax._cursorline is not None: ax._cursorline.remove() ax._cursorline = None ax.figure.canvas.draw() ax._cursorline = None # choose cursor color based on perceived brightness of background try: facecol = colorConverter.to_rgb(ax.get_facecolor()) except AttributeError: # older MPL facecol = colorConverter.to_rgb(ax.get_axis_bgcolor()) face_brightness = np.dot(facecol, np.array([299, 587, 114])) ax._cursorcolor = 'white' if face_brightness < 150 else 'black' plt.connect('motion_notify_event', _cursor_vline) plt.connect('axes_leave_event', _rm_cursor) ymin, ymax = ax.get_ylim() # don't pass vline or hline here (this fxn doesn't do hvline_color): _setup_ax_spines(ax, [], tmin, tmax, ymin, ymax, hline=False) ax.figure.set_facecolor('k' if hvline_color == 'w' else 'w') ax.spines['bottom'].set_color(hvline_color) ax.spines['left'].set_color(hvline_color) ax.tick_params(axis='x', colors=hvline_color, which='both') ax.tick_params(axis='y', colors=hvline_color, which='both') ax.title.set_color(hvline_color) ax.xaxis.label.set_color(hvline_color) ax.yaxis.label.set_color(hvline_color) if x_label is not None: ax.set_xlabel(x_label) if y_label is not None: if isinstance(y_label, list): ax.set_ylabel(y_label[ch_idx]) else: ax.set_ylabel(y_label) if vline: plt.axvline(vline, color=hvline_color, linewidth=1.0, linestyle='--') if hline: plt.axhline(hline, color=hvline_color, linewidth=1.0, zorder=10) if colorbar: plt.colorbar()
lowerLimit = 40 axs[0].plot(dataFrame['Date'], [upperLimit] * dataFrame.shape[0], 'r--', dataFrame['Date'], [lowerLimit] * dataFrame.shape[0], 'g--', dataFrame['Date'], dataFrame['RSI'], dataFrame['Date'], dataFrame['RSIavg'], 'k--') axs[0].legend(['Sell', 'Buy', 'RSI', 'RSI average'], loc='upper left') axs[0].grid(True, linestyle='--') axs[1].plot(dataFrame['Date'], dataFrame['Close'], dataFrame['Date'], dataFrame['UpperBand'], 'r--', dataFrame['Date'], dataFrame['LowerBand'], 'g--') axs[1].plot(dataFrame['Date'], dataFrame['Anomaly'], 'ro') axs[1].legend(['Close', 'Upper Bollinger band', 'Lower Bollinger band']) axs[1].set_ylim([dataFrame['Close'].min(), dataFrame['UpperBand'].max()]) axs[1].grid(True, linestyle='--') cursor = SnaptoCursor(axs[1], dataFrame) cid = plt.connect('motion_notify_event', cursor.mouse_move) axs[2].plot(dataFrame['Date'], dataFrame['MACD'], 'b', dataFrame['Date'], dataFrame['MACDsignal'], 'r--', dataFrame['Date'], [0] * dataFrame.shape[0], 'k') axs[2].legend(['MACD', 'Signal']) axs[2].bar(dataFrame['Date'], dataFrame['MACDsignalDiff'], color='green') axs[2].grid(True, linestyle='--') plt.xlim(dataFrame.at[0, 'Date'], dataFrame.at[dataFrame.shape[0] - 1, 'Date']) plt.tight_layout() plt.show()
"p plot mask ; r reset current points", size=10) fig_mask.text( 0.60, 0.18, "m square mask ; b unmask ; right darker ; left brighter", size=10, ) fig_mask.text(0.60, 0.15, "up larger masking box ; down smaller masking box", size=10) fig_mask.text(0.60, 0.12, "a restart ; q quit", size=10) info_text = fig_mask.text(0.60, 0.05, "masking enabled", size=16) plt.tight_layout() plt.connect("key_press_event", press_key) plt.connect("button_press_event", on_click) fig_mask.set_facecolor(background_plot) plt.show() mask[np.nonzero(updated_mask)] = 1 data = original_data detector_plane = False del fig_mask, original_data, updated_mask gc.collect() if use_rawdata: q_values = [] binning_comment = ( f"_{detector.preprocessing_binning[0]*detector.binning[0]}" f"_{detector.preprocessing_binning[1]*detector.binning[1]}"
im = plt.imshow(im_ca, animated=True) plt.title('Step: 0') def updatefig(*args): global idx_anim, im_ca idx_anim += 1 exp.run_step(feed_dict={input_ca: np.ones((input_size, 1))}) if idx_anim < height_fig: im_ca[idx_anim] = exp.get_group_cells_state("g_ca", "g_ca_bin")[:, 0] im.set_array(im_ca) else: im_ca = np.vstack( (im_ca[1:], exp.get_group_cells_state("g_ca", "g_ca_bin")[:, 0])) im.set_array(im_ca) plt.title('Step: ' + str(idx_anim + 1)) return im, # ttl ani = animation.FuncAnimation(fig, updatefig, frames=timesteps-2,\ interval=100, blit=False, repeat=False) plt.show() plt.connect('close_event', exp.close())
else: ## cumulative displacement time_selected = tslider.val tslider.set_val(time_selected) if lastevent: ## Time series plot printcoords(lastevent) RS = RectangleSelector(axv, line_select_callback, drawtype='box', useblit=True, button=[3], spancoords='pixels', interactive=False) plt.connect('key_press_event', RS) #%% Check box for mask ON/OFF if maskflag: axbox = pv.add_axes([0.01, 0.25, 0.1, 0.08]) visibility = True check = CheckButtons(axbox, [ 'mask', ], [ visibility, ]) def func(label): global mask, visibility if visibility: mask = mask_base
get_func_of_switch_ashi("m01")(event) elif event.key in jsn2["keyconfig"]["m15"]: get_func_of_switch_ashi("m15")(event) elif event.key in jsn2["keyconfig"]["h01"]: get_func_of_switch_ashi("h01")(event) elif event.key in jsn2["keyconfig"]["h04"]: get_func_of_switch_ashi("h04")(event) elif event.key in jsn2["keyconfig"]["d01"]: get_func_of_switch_ashi("d01")(event) else: pass else: pass except: raise Exception("please make ytest_config.json") plt.connect('key_press_event', keycon) ashi = "m05" fig.add_axes(mac_axs[ashi]) fig.add_axes(candle_axs[ashi]) ashi = watching_ashi fig.add_axes(mac_axs[ashi]) fig.add_axes(candle_axs[ashi]) for ashi in ashis: create_ax(ashi) btns[watching_ashi].color = "lightseagreen" plt.show()
ax2.imshow(np.log10(abs(data).sum(axis=2)), vmin=0, vmax=max_colorbar, cmap=my_cmap) ax0.axis('scaled') ax1.axis('scaled') ax2.axis('scaled') ax0.set_title("XY") ax1.set_title("XZ") ax2.set_title("YZ") fig_mask.text(0.60, 0.27, "click to select the vertices of a polygon mask", size=10) fig_mask.text(0.60, 0.24, "x to pause/resume polygon masking for pan/zoom", size=10) fig_mask.text(0.60, 0.21, "p plot mask ; r reset current points", size=10) fig_mask.text(0.60, 0.18, "m square mask ; b unmask ; right darker ; left brighter", size=10) fig_mask.text(0.60, 0.15, "up larger masking box ; down smaller masking box", size=10) fig_mask.text(0.60, 0.12, "a restart ; q quit", size=10) info_text = fig_mask.text(0.60, 0.05, "masking enabled", size=16) plt.tight_layout() plt.connect('key_press_event', press_key) plt.connect('button_press_event', on_click) fig_mask.set_facecolor(background_plot) plt.show() mask[np.nonzero(updated_mask)] = 1 data = original_data detector_plane = False del fig_mask, original_data, updated_mask gc.collect() if use_rawdata: q_values = [] binning_comment = (f'_{detector.preprocessing_binning[0]*detector.binning[0]}' f'_{detector.preprocessing_binning[1]*detector.binning[1]}' f'_{detector.preprocessing_binning[2]*detector.binning[2]}')
def interactive_editor(mask_path: str) -> None: with gdal_open(mask_path) as f: mask = f.ReadAsArray() selection = () previous_values = None previous_selection = () fig, ax = plt.subplots() im = plt.imshow(mask) plt.text(0, 1.1, (f"Press '{KEY_FILL_0}' or '{KEY_FILL_2}' to fill zeros, " f"'{KEY_FILL_1}' to fill ones, " f"'{KEY_UNDO}' to undo the last fill and " f"'{KEY_SAVE}' to save the mask "), transform=ax.transAxes) saved_text = plt.text(0.5, 1, "saved", transform=ax.transAxes) def selector_handler(eclick, erelease) -> None: nonlocal selection x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata selection = (x1, y1, x2, y2) def key_pressed(event) -> None: nonlocal previous_values nonlocal previous_selection if not selection: return # Keys that don't care about the selection data if event.key == KEY_SAVE: write_mask_to_file(f, mask_path, mask) saved_text.set_visible(True) fig.canvas.draw() return elif event.key == KEY_UNDO: if previous_values is not None: x1, y1, x2, y2 = previous_selection mask[y1:y2, x1:x2] = previous_values im.set_data(mask) fig.canvas.draw() return saved_text.set_visible(False) x1, y1, x2, y2 = list(map(int, selection)) previous_values = np.array(mask[y1:y2, x1:x2]) previous_selection = (x1, y1, x2, y2) if event.key == KEY_FILL_0: mask[y1:y2, x1:x2] = 0 elif event.key == KEY_FILL_2: mask[y1:y2, x1:x2] = 0 elif event.key == KEY_FILL_1: mask[y1:y2, x1:x2] = 1 im.set_data(mask) fig.canvas.draw() selector = RectangleSelector(ax, selector_handler, drawtype='box', interactive=True) plt.connect('key_press_event', key_pressed) plt.show()
def plot_ax(ax=None, img_path='', baselines_list=None, surr_polys=None, bcolors=None, region_dict_poly=None, rcolors=None, word_polys=None, plot_legend=False, fill_regions=False, height=None, width=None): if rcolors is None: rcolors = {} if region_dict_poly is None: region_dict_poly = {} if bcolors is None: bcolors = [] if surr_polys is None: surr_polys = [] if baselines_list is None: baselines_list = [] if word_polys is None: word_polys = [] if ax is None: fig, ax = plt.subplots(figsize=(16, 9)) # type: # (plt.Figure, plt.Axes) fig.canvas.set_window_title(img_path) views = collections.defaultdict(list) # # Maximize plotting window # mng = plt.get_current_fig_manager() # mng.resize(*mng.window.maxsize()) # # mng.full_screen_toggle() try: img_plot = add_image(ax, img_path, height=height, width=width) views.update({"image": img_plot}) except IOError as err: print(f"Can't display image given by path: {img_path} - {err}") if len(bcolors): assert len(bcolors) >= len(baselines_list), f"There should be at least {len(baselines_list)}" \ f" colors but just got {len(bcolors)}" else: bcolors = [DEFAULT_COLOR] * len(baselines_list) if baselines_list: article_collection = [] for i, blines in enumerate(baselines_list): baseline_collection = add_polygons(ax, blines, bcolors[i], closed=False) article_collection.append(baseline_collection) if bcolors[i] == DEFAULT_COLOR: baseline_collection.set_label("None") else: baseline_collection.set_label("a-id " + str(i + 1)) views['baselines'].append(baseline_collection) if plot_legend: # Add article ids to the legend # TODO: Sometimes there are too many articles to display -> possibility to scroll?! # article_collection = [coll for coll in ax.collections if coll.get_label().startswith("a-id")] ax.legend(article_collection, [coll.get_label() for coll in article_collection], bbox_to_anchor=[1.0, 1.0], loc="upper left") if surr_polys: surr_poly_collection = add_polygons(ax, surr_polys, DEFAULT_COLOR, closed=True) surr_poly_collection.set_visible(False) views['surr_polys'] = [surr_poly_collection] if word_polys: word_poly_collection = add_polygons(ax, word_polys, DEFAULT_COLOR, closed=True) word_poly_collection.set_visible(False) views['word_polys'] = [word_poly_collection] if region_dict_poly: for region_name, regions in region_dict_poly.items(): region_collection = add_polygons(ax, regions, rcolors[region_name], closed=True, filled=fill_regions) region_collection.set_visible(False) views[region_name] = [region_collection] views['regions'].append(region_collection) # Toggle baselines with "b", image with "i", surrounding polygons with "p" plt.connect('key_press_event', lambda event: toggle_view(event, views))
time -= time_frame if (time >= (duration - time_frame)): time = 0 print("Reached end of file!") if key == "q": return print(time) frame = source.get_frame(time) line_image, cropped_image, mask_image = pipeline() # img1.set_data(line_image) # img2.set_data(mask_image) # img3.set_data(cropped_image) # plt.draw() #------------------------------- plt.connect('key_press_event', toggle_images) img1 = ax1.imshow(line_image) img2 = ax2.imshow(mask_image) img3 = ax3.imshow(cropped_image) mng = plt.get_current_fig_manager() mng.full_screen_toggle() plt.show()
#%% 单变量高斯分布 mu = 0 sigma2 = 4 L = 1000 x_points = np.linspace(-10, 10, L) f_points = gaussian_distribution(x_points, mu, sigma2) # print(np.log(f_points[:100])) # print(gaussian_distribution_log(x_points, mu, sigma2)[:100]) # f_points = gaussian_multi_distribution( # np.expand_dims(x_points, axis=1), # np.array([0]).reshape(1, 1), # np.array([4]).reshape(1, 1)) # 单维也属于用多维高斯分布 print("面积: ", np.abs(np.sum((x_points[:-1] - x_points[1:]) * f_points[:-1]))) plt.figure('Gaussian single variable') plt.connect('key_press_event', on_key) plt.axes((0.1, 0.1, 0.8, 0.8)) plt.plot(x_points, f_points) plt.show() #%% 多变量高斯分布 mu = np.array([0, 0]), Sigma = np.array([[1.0, 0.3], [0.2, 1.0]], dtype=np.float) L = 1000 r = np.linspace(-3, 3, L, dtype=np.float) mesh = np.meshgrid(r, r) x_points = np.empty((L * L, 2), dtype=np.float) x_points[:, 0] = mesh[0].ravel() x_points[:, 1] = mesh[1].ravel() f_points = gaussian_multi_distribution(x_points, mu, Sigma) f_points = f_points.reshape((L, L))
def main(values, is_animation=False): """Main function to show the plot which could be played with animation.""" def on_clicked(event): """Direct the program when a key is pressed.""" if event.key == "x": # Use this os._exit(0) to close whole window, even when playing os._exit(0) if event.key == "s": # Get time to define image's name now = datetime.now() current_time = now.strftime("%H-%M-%S") plot_name = "Plot" + "-" + current_time # Remove left title, then save image pyplot.title("", loc="left", pad=20) fig.savefig( "%s%s%s" % ( CONS["OUTPUT_PHOTO_DIRECTORY"], plot_name, CONS["PHOTO_TYPE"], ), transparent=False, dpi=300, ) # Use this exit(0) to prevent exiting when playing the plot # but allow closing when plotting finishes exit(0) def draw(values): """Plot the grid, the line graphs and the titles.""" # Turn on grid with dashed style subplot.yaxis.grid(True, linestyle="dashed") # Get list of new higher values new_values = get_new_values(values) # Plot 2 lines subplot.plot(range(len(values)), values) subplot.plot(range(len(new_values)), new_values, linewidth=2) # Print left plot title pyplot.title( "Press X to exit\nPress S to save", loc="left", fontsize=14, color="#1F76B4", style="italic", pad=20, ) # Print right plot title pyplot.title( f"{'Max objective:':>25}{max(values):>10.2E}\n" f"{'Generation:':>25}{values.index(max(values)):>10}", loc="right", fontfamily="Lucida Sans Typewriter", fontsize=12, color="#FF7E0E", pad=20, ) # The following code configures some elements of the plot window # Disable toolbar maplot.rcParams["toolbar"] = "None" # Set font maplot.rcParams["font.family"] = "Candara" maplot.rcParams["font.size"] = 12 maplot.rcParams["font.weight"] = 500 # Set window title fig = pyplot.figure(figsize=(10, 5)) fig.canvas.set_window_title("Prosthetic Foot Design by Genetic Algorithm") # Set icon manager = pyplot.get_current_fig_manager() manager.window.wm_iconbitmap(CONS["ICON_FILE"]) # Disable some borders subplot = fig.add_subplot(111, frameon=True) subplot.spines["right"].set_visible(False) subplot.spines["left"].set_visible(False) subplot.spines["top"].set_visible(False) # Push verticle axis to the right subplot.yaxis.tick_right() # Padding axis label from plot area, maybe unnecessary subplot.tick_params(axis="y", which="major", pad=5) subplot.tick_params(axis="x", which="major", pad=5) # Adjust subplot size based on window size pyplot.subplots_adjust(left=0.03, right=0.94, top=0.82, bottom=0.1) # Reconize key pressed pyplot.connect("key_press_event", on_clicked) if is_animation: for index in range(1, len(values) + 1): subplot.clear() draw(values[:index]) pyplot.pause(0.0001) else: draw(values) # Hold window pyplot.show()
#button 1 is left mouse button minspanx=5, minspany=5, # don't accept a box of fewer than 5 pixels spancoords='pixels') # units for above #set axis limits ax.set_ylim(-30, 30) ax.set_xlim(-30, 30) # Add axis labels plt.xlabel('x (kpc)', fontsize=22) plt.ylabel('y (kpc)', fontsize=22) # ADDED THIS # to detect the 'R' key press to reset the image plt.connect("key_press_event", onKeyPressed) plt.show() # # Part C Connecting Morphology to Kinematics # # # Make a two panel plot. # Left Panel: Density # Right Panel: Phase Diagram # # Relect a section of the density plot and see where the particles are on the phase diagram # In[ ]: # Let's store the circular velocity of the MW like we did in Lab 7
if event.key in ['7'] and len(scan.selectorlist) > 6: print('ROI7 activated') scan.selectorlist[6].ROI.set_active(True) axnext = plt.axes([0.95, 0.025, 0.05, 0.04]) buttonnext = Button(axnext, 'Next', color=(0, 0.5, 0.9)) axprev = plt.axes([0.9, 0.025, 0.05, 0.04]) buttonprev = Button(axprev, 'Prev', color=(0, 0.5, 0.9)) def buttonnextfun(event): img_slider.set_val(img_slider.val + 1) update(img_slider.val) ROI1.updatedata() ROI1.storedata() ROIlineupdate(ROI1) buttonnext.on_clicked(buttonnextfun) def buttonprevfun(event): img_slider.set_val(img_slider.val - 1) update(img_slider.val) buttonprev.on_clicked(buttonprevfun) plt.connect('key_press_event', keyboard_selector) plt.show()
plt.ylim(-10, 10) plt.ion() plt.show() # Plot inital tracker old_point, = plt.plot(x_t, y_t, 'rx') # Handler to get mouse coordinates def mouse_move(event): global x_m, y_m if event.xdata: # Check Null (outside axes) x_m, y_m = event.xdata, event.ydata plt.connect('motion_notify_event', mouse_move) # Handler to get keyboard inputs def key_pressed(event): if event.key == 'q': # quit exit() plt.connect('key_press_event', key_pressed) # Main loop for tracking while True: old_point.remove() # Global angle from the current location to target
rax = plt.axes([0.05, 0.1, 0.15, 0.15]) radios = RadioButtons(rax, ["sine", "square", "tri"]) ax = axs[0] ax.set_xlim(0, max(ts)) ax.set_ylim(-2, 2) axdiff = axs[1] curs = Cursor(ax, horizOn=False, vertOn=True, c="orange") axdiff.set_ylim(-2, 2) tang = DiffTangentDraw(ax, axdiff, ts) # setup_sine_wave(tang) # setup_square_wave(tang) def choose_wave(name): if name == "sine": setup_sine_wave(tang, ax, axdiff) elif name == "square": setup_square_wave(tang, ax, axdiff) elif name == "tri": setup_tri_wave(tang, ax, axdiff) setup_sine_wave(tang, ax, axdiff) radios.on_clicked(choose_wave) plt.connect("motion_notify_event", tang.move_event) plt.show(block=True)
def plotlc(): global aid, bid, cid, did, eid, fid, mask # load button plt.clf() plt.axes([0.06, 0.02, 0.22, 0.1]) plt.text(0.5, 0.5, 'LOAD', fontsize=24, weight='heavy', horizontalalignment='center', verticalalignment='center') plt.setp(plt.gca(), xticklabels=[], xticks=[], yticklabels=[], yticks=[]) plt.fill([0.0, 1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 1.0, 0.0], '#ffffee') plt.xlim(0.0, 1.0) plt.ylim(0.0, 1.0) aid = plt.connect('button_press_event', clicker1) # save button plt.axes([0.2933, 0.02, 0.22, 0.1]) plt.text(0.5, 0.5, 'SAVE', fontsize=24, weight='heavy', horizontalalignment='center', verticalalignment='center') plt.setp(plt.gca(), xticklabels=[], xticks=[], yticklabels=[], yticks=[]) plt.fill([0.0, 1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 1.0, 0.0], '#ffffee') plt.xlim(0.0, 1.0) plt.ylim(0.0, 1.0) bid = plt.connect('button_press_event', clicker2) # clear button plt.axes([0.5266, 0.02, 0.22, 0.1]) plt.text(0.5, 0.5, 'CLEAR', fontsize=24, weight='heavy', horizontalalignment='center', verticalalignment='center') plt.setp(plt.gca(), xticklabels=[], xticks=[], yticklabels=[], yticks=[]) plt.fill([0.0, 1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 1.0, 0.0], '#ffffee') plt.xlim(0.0, 1.0) plt.ylim(0.0, 1.0) cid = plt.connect('button_press_event', clicker3) # print button plt.axes([0.76, 0.02, 0.22, 0.1]) plt.text(0.5, 0.5, 'PRINT', fontsize=24, weight='heavy', horizontalalignment='center', verticalalignment='center') plt.setp(plt.gca(), xticklabels=[], xticks=[], yticklabels=[], yticks=[]) plt.fill([0.0, 1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 1.0, 0.0], '#ffffee') plt.xlim(0.0, 1.0) plt.ylim(0.0, 1.0) did = plt.connect('button_press_event', clicker4) # light curve plt.axes([0.06, 0.213, 0.92, 0.77]) plt.gca().xaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False)) plt.gca().yaxis.set_major_formatter(plt.ScalarFormatter(useOffset=False)) ltime = [] ldata = [] work1 = instr[1].data.field(0) + bjdref work2 = instr[1].data.field(col) / cade for i in range(len(work1)): if np.isfinite(work1[i]) or np.isfinite(work2[i]): ltime.append(work1[i]) ldata.append(work2[i]) else: ltime = np.array(ltime, dtype=np.float64) - barytime0 ldata = np.array(ldata, dtype=np.float64) / 10**nrm plt.plot(ltime, ldata, color='#0000ff', linestyle='-', linewidth=1.0) ltime = [] ldata = [] ltime = np.array(ltime, dtype=np.float64) - barytime0 ldata = np.array(ldata, dtype=np.float64) / 10**nrm plt.plot(ltime, ldata, color='#0000ff', linestyle='-', linewidth=1.0) plt.fill(barytime, flux, fc='#ffff00', linewidth=0.0, alpha=0.2) plt.xlabel(xlab, {'color': 'k'}) plt.ylabel(ylab, {'color': 'k'}) plt.grid() # plt.plot masks for i in range(len(mask)): t = float(mask[i]) plt.plot([t, t], [ymin, ymax], color='g', linestyle='-', linewidth=0.5) nt = 0 for i in range(int(len(mask) / 2)): t1 = float(mask[nt]) t2 = float(mask[nt + 1]) nt += 2 plt.fill([t1, t1, t2, t2, t1], [ymin, ymax, ymax, ymin, ymin], fc='g', linewidth=0.0, alpha=0.5) # plot ranges plt.xlim(xmin - xr * 0.01, xmax + xr * 0.01) if ymin - yr * 0.01 <= 0.0: plt.ylim(1.0e-10, ymax + yr * 0.01) else: plt.ylim(ymin - yr * 0.01, ymax + yr * 0.01) # ranges eid = plt.connect('button_press_event', clicker6) # render plot plt.show()
def crop_clone_preview(image): """Interactive viewer to quickly get crop and clone parameters. Parameters ---------- image : numpy.ndarray Image array, typically from cv2.imread(). Returns ------- tuple Format is (crop, clone_to, clone_directs). The crop_tuple variable can be fed directly into process_jpgs(). Then, use "generate_clone_tuples(clone_to, directs[0])" to get the clone parameter, or any other direction in the directs list (all have been checked for bounds, unlike generate_clone_tuples). """ mem = Mem() mem.crop_tuple = False mem.clone_tuple = False mem.clone_directs = False def update(event): if crop_RS.active: crop_RS.update() if clone_RS.active: clone_RS.update() def safe_corners(geometry): min_y = max(0, min(geometry[0, :])) max_y = min(H, max(geometry[0, :])) min_x = max(0, min(geometry[1, :])) max_x = min(W, max(geometry[1, :])) ignore = (min_y > H or max_y < 0 or min_x > W or max_x < 0) return tuple(map( lambda x: int(round(x)), (min_y, max_y, min_x, max_x))), ignore def RS_event(eclick, erelease): x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata cr_corn, cr_ig = safe_corners(crop_RS.geometry) cl_corn, cl_ig = safe_corners(clone_RS.geometry) mod = image.copy() if not cl_ig: mem.clone_tuple = cl_corn trials = [] for direct in ("A", "B", "R", "L"): tups = generate_clone_tuples(cl_corn, direct) a, b, c, d = tups[1] if not (a < 0 or b > H or c < 0 or d > W): trials.append((tups, direct)) choose = [] for (tups, direct) in trials: test = image.copy() (a, b, c, d), (e, f, g, h) = tups test[a:b, c:d] = test[e:f, g:h] diff = cv2.absdiff(test, image) choose.append((sum(cv2.sumElems(diff)), direct, test)) choose.sort() if choose: _, directs, imgs = list(zip(*choose)) mem.clone_directs = directs mod = imgs[0] del choose else: mem.clone_tuple = False mem.clone_directs = False if cr_ig: cr_corn = (0, H, 0, W) mem.crop_tuple = False else: mem.crop_tuple = cr_corn y1, y2, x1, x2 = cr_corn mod = mod[y1:y2, x1:x2] mod = cv2.cvtColor(mod, cv2.COLOR_BGR2RGB) ax_mod.imshow(mod) fig.canvas.draw_idle() rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) H, W, *_ = image.shape scale = 10 lo_W, hi_W = (0 - W // scale), (W + W // scale) lo_H, hi_H = (0 - H // scale), (H + H // scale) gs = gridspec.GridSpec(2, 2, height_ratios=[1, 1.25]) fig = plt.figure() fig.canvas.set_window_title("Crop and Clone Preview") ax_crop = fig.add_subplot(gs[0, 0]) ax_clone = fig.add_subplot(gs[0, 1]) ax_mod = fig.add_subplot(gs[1, :]) crop_RS = RectangleSelector( ax_crop, RS_event, **RS_PARAMS) clone_RS = RectangleSelector( ax_clone, RS_event, **RS_PARAMS) ax_crop.set_title("Crop") ax_clone.set_title("Clone") ax_mod.set_title("Result") for axe in (ax_crop, ax_clone): axe.set_xticklabels([]) axe.set_yticklabels([]) axe.set_xlim(lo_W, hi_W) axe.set_ylim(hi_H, lo_H) ax_crop.imshow(rgb) ax_clone.imshow(rgb) ax_mod.imshow(rgb) plt.connect("draw_event", update) plt.show() return mem.crop_tuple, mem.clone_tuple, mem.clone_directs
plt.close() def toggle_selector(event): toggle_selector.RS.set_active(True) if __name__ == '__main__': for n, image_file in enumerate(os.scandir(image_folder)): img = image_file print(img) fig, ax = plt.subplots(1) mngr = plt.get_current_fig_manager() #mngr.window.setGeometry(250, 120, 1280, 1024) image = cv2.imread(image_file.path) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) ax.imshow(image) toggle_selector.RS = RectangleSelector(ax, line_select_callback, drawtype='box', useblit=True, button=[1], minspanx=5, minspany=5, spancoords='pixels', interactive=True) bbox = plt.connect('key_press_event', toggle_selector) key = plt.connect('key_press_event', onkeypress) plt.show()
EonImageDark = sp.zeros((Ny,Nx),dtype=sp.float64) + 3.14 for nx in range(Nx): for ny in range(Ny): for nt in range(Nt-(trim1+trim2)): if sweepReversed == 'y': n = -1*(nt+1) else: n = nt if photoCube[ny,nx,n]>iThreshold: EonImagePhoto[ny,nx] = xData[n] break for nt in range(Nt-(trim1+trim2)): if sweepReversed == 'y': n = -1*(nt+1) else: n = nt if darkCube[ny,nx,n]>iThreshold: EonImageDark[ny,nx] = xData[n] break photoPath = imgsPath + baseName + '_Eon_ImagePhoto.txt' sp.savetxt(photoPath,EonImagePhoto,delimiter='\t') darkPath = imgsPath + baseName + '_Eon_ImageDark.txt' sp.savetxt(darkPath,EonImageDark,delimiter='\t') #This just plots the image for a final time and binds the GUI functions to the figure. fig, current_ax = plt.subplots() totalCurr = sp.average(dataCube,axis=2) totCurrPlot = plt.imshow(totalCurr,interpolation='none',origin='lower') plt.connect('button_press_event', onclick) plt.show()
def draw(df, title="", colorup='g', colordown='r'): # 畫出價量曲線 # 檢查實際讀到的日期 if not 'Date' in df.columns: df['Date'] = df.index.date startdate = df.index.date[0] enddate = df.index.date[-1] def format_coord1(x, y): "用來顯示股價相關資訊" try: index = int(x + 0.5) if index < 0 or index >= len(df.Date): return "" else: return 'x=%s, y=%1.1f, price=%1.1f' % ( df.Date[int(x + 0.5)], y, df.Close[int(x + 0.5)]) except Exception as e: print(e.args) return '' def format_coord2(x, y): "用來顯示 Volume 的相關資訊" try: index = int(x + 0.5) if index < 0 or index >= len(df.Date): return "" else: return 'x=%s, y=%1.1fM, volume=%1.1fM' % (df.Date[int( x + 0.5)], y * 1e-6, df.Volume[int(x + 0.5)] * 1e-6) except Exception as e: print(e.args) return '' # 如果沒有讀到任何股價,就跳出程式 if df.empty: raise SystemExit tickdates = getListOfDates(startdate, enddate) tickindex = getDateIndex(df.Date, tickdates) ticknames = getMonthNames(df.Date, tickindex) millionformatter = FuncFormatter(millions) thousandformatter = FuncFormatter(thousands) fig = plt.figure(figsize=(16, 12)) fig.subplots_adjust(bottom=0.1) fig.subplots_adjust(hspace=0) gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1]) ax0 = plt.subplot(gs[0]) candles = candlestick(ax0, df.Open, df.High, df.Low, df.Close, width=1, colorup=colorup, colordown=colordown) last_price = "Date:{}, Open:{}, High:{}, Low:{}, Close:{}, Volume:{}".format( df.Date[-1], df.Open[-1], df.High[-1], df.Low[-1], df.Close[-1], df.Volume[-1]) ax0.text(0.99, 0.97, last_price, horizontalalignment='right', verticalalignment='bottom', transform=ax0.transAxes) draw_price_ta(ax0, df) ax0.set_xticks(tickindex) ax0.set_xticklabels(ticknames) ax0.format_coord = format_coord1 ax0.legend(loc='upper left', shadow=True, fancybox=True) ax0.set_ylabel('Price($)', fontsize=16) if has_chinese_font: ax0.set_title(title, fontsize=24, fontweight='bold', fontproperties=font) else: ax0.set_title(title, fontsize=24, fontweight='bold') ax0.grid(True) ax1 = plt.subplot(gs[1], sharex=ax0) vc = volume_overlay(ax1, df.Open, df.Close, df.Volume, colorup=colorup, colordown=colordown, width=1) ax1.set_xticks(tickindex) ax1.set_xticklabels(ticknames) ax1.format_coord = format_coord2 ax1.tick_params(axis='x', direction='out', length=5) ax1.yaxis.set_major_formatter(millionformatter) ax1.yaxis.tick_right() ax1.yaxis.set_label_position("right") ax1.set_ylabel('Volume', fontsize=16) ax1.grid(True) plt.setp(ax0.get_xticklabels(), visible=False) cursor0 = Cursor(ax0) cursor1 = Cursor(ax1) plt.connect('motion_notify_event', cursor0.mouse_move) plt.connect('motion_notify_event', cursor1.mouse_move) # 使用 cursor 的時候,如果沒有設定上下限,圖形的上下限會跑掉 yh = df.High.max() yl = df.Low.min() ax0.set_ylim(yl - (yh - yl) / 20.0, yh + (yh - yl) / 20.0) ax0.set_xlim(0, len(df.Date) - 1) plt.show()
def main(): list_float = [ 1901155, 1901298, 1901324, 1901341, 1901604, 1901685, 1901689 ] #create empty dataframe to store user inputs df_main = pd.DataFrame(columns=[ 'Feature', 'Float', 'Profile', 'Colour', 'x1', 'x2', 'y1', 'y2', 'lat', 'long' ]) # will create a data set print('-----------------------------------------------') user = input("Enter name: ") #print("Welcome "+ user) feat = input("Feature interested: ") gen = input("Number of samples: ") print('--------- Graph Info ---------') print( " White dot represents the current location \n press 'g' to label data as good \n press 'r' to label data poor" ) for i in range(int(gen)): #select random float float argo = random.choice(list_float) #access the random float from database argo_float = pd.read_csv("/Users/vagifaliyev/Desktop/argo_database/" + str(argo) + '.csv') list_prof = list(dict.fromkeys(argo_float['CYCLE_NUMBER'])) #randomly select a profile prof = random.choice(list_prof) df = argo_float.loc[argo_float['CYCLE_NUMBER'] == prof] # allocate the columns to specific variable names for easier access pres = df['PRES'] psal = df['PSAL'] temp = df['TEMP'] lat = df['LATITUDE'].values[0] lon = df['LONGITUDE'].values[0] # plotting salinity graph fig = plt.figure(figsize=(8, 4)) gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1]) ax = plt.subplot(gs[0]) # adding a low transperency line to follow the patern more easily plt.plot(psal, temp, alpha=0.2) # main fature is the scatter plot sc = plt.scatter(psal, temp, c=pres, cmap='hsv') # add colour graded bar cbar = plt.colorbar(sc) cbar.set_label('Pressure', labelpad=-40, y=1.05, rotation=0) plt.title(str(argo) + '_' + str(prof)) plt.xlabel('Salinity') plt.ylabel('Temp') # enabling use of selector # drawtype is 'box' or 'line' or 'none' toggle_selector.RS = RectangleSelector( ax, line_select_callback, drawtype='box', useblit=True, button=[1, 3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels', interactive=True) plt.connect('key_press_event', toggle_selector) # basemap mapping ax = plt.subplot(gs[1]) map = Basemap(projection='cass', lon_0=lon, lat_0=lat, width=10000000, height=10000000) map.bluemarble() map.drawcountries() map.drawcoastlines() map.drawrivers(color='#0000ff') #plot the current float point lons, lats = map(lon, lat) map.scatter(lons, lats, marker='o', color='w', zorder=5) #plot the previous points lons, lats = map(df_main['long'].values, df_main['lat'].values) map.scatter(lons, lats, marker='o', color=df_main['Colour'], zorder=5) ax.set_title("Lat: " + str(lat) + '\n Long: ' + str(lon)) plt.tight_layout() plt.show() # at the end of one loop, save all the data to main dataframe df_main = df_main.append( { 'Feature': feat, 'Float': argo, 'Profile': prof, 'Colour': colour, 'x1': x1, 'x2': x2, 'y1': y1, 'y2': y2, 'lat': lat, 'long': lon }, ignore_index=True) print( '----------------------DATA COLLECTION FINISHED-------------------------' ) #print dataframe to check print(df_main) #request filename filename = input(user + ", insert file name: ") #save the data frame as csv # if file does not exist write header # else it exists so append without writing the header with open(user + '_' + filename + '.csv', 'a') as f: df_main.to_csv(f, header=f.tell() == 0, index=False) print('-----------------------CSV FILE SAVED------------------------')
ax.autoscale(True) d.set_ydata(y0) ax.relim() ax.autoscale_view() ax.autoscale(False) dy0.remove() dy1.remove() dy2.remove() dy3.remove() update(0) # register objects using weighting_type_update rad_weighting_type.on_clicked(weighting_type_update) def on_move(event): if event.inaxes: new_plot_size = fig.get_size_inches()*fig.dpi global plot_size if (not np.array_equal(new_plot_size, plot_size)): for item in t_labels.keys(): t_labels[item].update({'fontsize':10.0/1600*new_plot_size[0]}) plot_size = new_plot_size fig.canvas.draw_idle() plt.connect('motion_notify_event', on_move) plt.show() del kp
button.connect('clicked', clicked) toolitem = gtk.ToolItem() toolitem.show() toolitem.set_tooltip(toolbar.tooltips, 'Click me for fun and profit') toolitem.add(button) toolbar.insert(toolitem, next) next += 1 # now let's add a widget to the vbox label = gtk.Label() label.set_markup('Drag mouse over axes for position') label.show() vbox = manager.vbox vbox.pack_start(label, False, False) vbox.reorder_child(manager.toolbar, -1) def update(event): if event.xdata is None: label.set_markup('Drag mouse over axes for position') else: label.set_markup('<span color="#ef0000">x,y=(%f, %f)</span>' % (event.xdata, event.ydata)) plt.connect('motion_notify_event', update) plt.show()