def test_twin_axes_empty_and_removed(): # Purely cosmetic font changes (avoid overlap) matplotlib.rcParams.update({"font.size": 8}) matplotlib.rcParams.update({"xtick.labelsize": 8}) matplotlib.rcParams.update({"ytick.labelsize": 8}) generators = [ "twinx", "twiny", "twin" ] modifiers = [ "", "host invisible", "twin removed", "twin invisible", "twin removed\nhost invisible" ] # Unmodified host subplot at the beginning for reference h = host_subplot(len(modifiers)+1, len(generators), 2) h.text(0.5, 0.5, "host_subplot", horizontalalignment="center", verticalalignment="center") # Host subplots with various modifications (twin*, visibility) applied for i, (mod, gen) in enumerate(product(modifiers, generators), len(generators)+1): h = host_subplot(len(modifiers)+1, len(generators), i) t = getattr(h, gen)() if "twin invisible" in mod: t.axis[:].set_visible(False) if "twin removed" in mod: t.remove() if "host invisible" in mod: h.axis[:].set_visible(False) h.text(0.5, 0.5, gen + ("\n" + mod if mod else ""), horizontalalignment="center", verticalalignment="center") plt.subplots_adjust(wspace=0.5, hspace=1)
def init_axis_gs (gs, twin=False, sharex=False): if not sharex: ax = host_subplot(gs, axes_class=AA.Axes) else: ax = host_subplot(gs, axes_class=AA.Axes, sharex=sharex) if twin: return ax, ax.twin() else: return ax
def plot_classification_confidence_histograms(config, task, model, scaler, X_test, classes, targets_test, excludes_test): best_confidence_hist = [0 for i in range(101)] true_confidence_hist = [0 for i in range(101)] if scaler != None: X_test = scaler.transform(X_test) probabs = model.predict(X_test, verbose=0) for i in range(0, probabs.shape[0]): classes_sorted = probabs[i].argsort()[::-1] adjusted_classes_and_probabs_sorted = [] for j in range(0,classes_sorted.shape[0]): classname = classes[classes_sorted[j]] probab = probabs[i][classes_sorted[j]] if classname not in excludes_test[i]: adjusted_classes_and_probabs_sorted.append((classname, probab)) probab = adjusted_classes_and_probabs_sorted[0][1] try: best_confidence_hist[int(round(100*probab))] += 1 except ValueError: return best = 0 while best < len(adjusted_classes_and_probabs_sorted): if adjusted_classes_and_probabs_sorted[best][0] == targets_test[i]: probab = adjusted_classes_and_probabs_sorted[best][1] try: true_confidence_hist[int(round(100*probab))] += 1 except ValueError: return break else: best += 1 host = host_subplot(111) host.set_xlabel('Confidence') host.set_ylabel("Probability") divisor = sum(true_confidence_hist) host.plot(np.array(range(101)), np.array([x/divisor for x in true_confidence_hist]), label='Probability') plt.title('True Confidence Hist') plt.savefig(config['base_folder'] + 'classification/true_confidence_hist_' + task + '.png') plt.close() print("Saving true confidence histogram to " + config['base_folder'] + 'classification/true_confidence_hist_' + task + '.png') host = host_subplot(111) host.set_xlabel('Confidence') host.set_ylabel("Probability") divisor = sum(best_confidence_hist) host.plot(np.array(range(101)), np.array([x/divisor for x in best_confidence_hist]), label='Probability') plt.title('Best Confidence Hist') plt.savefig(config['base_folder'] + 'classification/best_confidence_hist_' + task + '.png') print("Saving true confidence histogram to " + config['base_folder'] + 'classification/best_confidence_hist_' + task + '.png')
def render_plot(urls, tstartstr, tendstr): tstart = ParseDate(tstartstr) tend = ParseDate(tendstr) log = DataLog() log.Open(readOnly=True) colors = 'rgb' urlsSplit = urls.split(',') ax = [] pos = [] if len(urlsSplit) > 0: host = host_subplot(111, axes_class=AA.Axes) ax.append(host) pos.append('left') if len(urlsSplit) > 1: par1 = host.twinx() ax.append(par1) pos.append('right') if len(urlsSplit) > 2: par2 = host.twinx() plt.subplots_adjust(right=0.75) offset = 60 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0)) ax.append(par2) pos.append('right') for i in range(len(ax)): try: url = urlsSplit[i] dbkey, unit = log.SignalGet(url.split('.')[2]) label = url + " (" + unit + ")" times, n, values = log.Query(url, tstart, tend) sumn, minp50, maxp50 = log.QueryAccumulates(url) ax[i].set_xlim(UtcToLocalTime([tstart, tend])) ax[i].set_ylim([ np.floor(minp50), np.ceil(maxp50) ]) ax[i].set_ylabel(label) ax[i].tick_params(axis='y', colors=colors[i], which='both') ax[i].axis[pos[i]].label.set_color(colors[i]) ax[i].axis[pos[i]].major_ticklabels.set_color(colors[i]) DoPlot(times, values[:,2], ax[i], '-' + colors[i]) if i > 0: ax[i].axis['bottom'].toggle(all=False) except Exception as e: ax[i].text(0.5, (1 + i) / (len(ax) + 1.0), str(e), horizontalalignment='center', verticalalignment='center', \ transform = ax[i].transAxes, color=colors[i]) placeName = url.split('.')[0] wgs84long, wgs84lat, heightMeters = log.PlaceDetailsGet(placeName) PlotDayNight(ax[0], tstart, tend, wgs84long, wgs84lat) ax[0].axis["bottom"].major_ticklabels.set_rotation(30) ax[0].axis["bottom"].major_ticklabels.set_ha("right") ax[0].grid() log.Close() img = StringIO.StringIO() plt.savefig(img, dpi=150) plt.close() img.seek(0) return flask.send_file(img, mimetype='image/png')
def create_plot(self, parent): """Create plot area""" plotframe = QtGui.QFrame(parent) sizepol = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed) sizepol.setHorizontalStretch(0) sizepol.setVerticalStretch(0) sizepol.setHeightForWidth(plotframe.sizePolicy().hasHeightForWidth()) plotframe.setSizePolicy(sizepol) plotframe.setMinimumSize(QtCore.QSize(0, 200)) plotframe.setMaximumSize(QtCore.QSize(1980, 200)) # plotframe.setFrameShape(QtGui.QFrame.StyledPanel) # plotframe.setFrameShadow(QtGui.QFrame.Raised) plotframe.setObjectName("plotframe") plotlayout = QtGui.QVBoxLayout(plotframe) plotlayout.setMargin(0) plotlayout.setObjectName("plotlayout") fig = plt.figure(dpi=100)#, frameon=False figsize=(20, 4), fig.patch.set_facecolor('white') rcParams['axes.color_cycle'] = ['k', 'b', 'g', 'r'] self.canvas = FigureCanvas(fig) self.axes.append(host_subplot(111, axes_class=aa.Axes)) self.axes[0].set_xlabel("Time") self.axes[0].set_ylabel(DATA_LABELS[9]) self.axes[0].set_aspect('auto', 'datalim') self.plots.append(self.axes[0].plot(aprs_daemon.LIVE_DATA['timestamps'], aprs_daemon.LIVE_DATA['altitudes'])[0]) fig.add_axes(self.axes[0]) self.axes[0].axis["left"].label.set_color(self.plots[0].get_color()) self.axes[0].tick_params(axis='y', color=self.plots[0].get_color()) for row in range(5, len(DATA_LABELS)/2): if row % 2 == 0: side = "left" offset = -1 else: side = "right" offset = 1 self.axes.append(self.axes[0].twinx()) self.axes[row-4].axis["right"].set_visible(False) new_fixed_axis = self.axes[row-4].get_grid_helper().new_fixed_axis self.axes[row-4].axis[side] = new_fixed_axis(loc=side, axes=self.axes[row-4], offset=(offset*(60*((row-5)%2+(row-5)/2)), 0)) self.axes[row-4].axis[side].label.set_visible(True) self.axes[row-4].axis[side].major_ticklabels.set_ha(side) self.axes[row-4].axis[side].set_label(DATA_LABELS[2*row+1]) self.plots.append(self.axes[row-4].plot(aprs_daemon.LIVE_DATA['timestamps'], aprs_daemon.LIVE_DATA[DATA_LABELS[2*row]])[0]) self.axes[row-4].axis[side].label.set_color(self.plots[row-4].get_color()) self.axes[row-4].set_aspect('auto', 'datalim') self.axes[row-4].tick_params(axis='y', colors=self.plots[row-4].get_color()) plt.subplots_adjust(bottom=0.3, left=0.20, right=0.8, top=0.85) fig.tight_layout() self.canvas.setParent(plotframe) self.canvas.setStyleSheet("background-color: rgb(255, 0, 255);") self.canvas.draw() plotlayout.addWidget(self.canvas) return plotframe
def __init__(self, data, labels, colors=None): self.data = data host = host_subplot(111, axes_class=AA.Axes) #plt.subplots_adjust(right=0.75) plt.gca().set_frame_on(False) host.set_frame_on(False) xticks = np.arange(data.shape[1]) host.set_xticks(xticks) host.set_xticklabels(labels) host.yaxis.set_visible(False) host.tick_params(axis='x', length=0) host.axis['top'].set_visible(False) host.axis['right'].set_visible(False) host.set_ylim(np.min(data[:, 0]) - 0.1, np.max(data[:, 0]) + 0.1) axes = [host] for i in range(1, data.shape[1]): ax = host.twinx() ax.set_ylim(np.min(data[:, i]), np.max(data[:, i])) ax.axis["right"] = ax.new_floating_axis(1, value=i) ax.axis["right"].set_axis_direction("left") axes.append(ax) else: ax.axis["right"].set_axis_direction("right") self.axes = axes self.colors = colors
def plot_cummulative_distance(self, i, j, fixed): # i,j is grid id # fixed is table of (theta, starting position) delta_d_alpha = [] for elem in self.all_data: if elem.info["angle"] == fixed["angle"]: if elem.info["starting_point"] == fixed["starting_point"]: delta_d_alpha.append([elem.grid[i][j][2], elem.info["distance"], elem.get_apical_angle(i,j)]) delta_d_alpha.sort(key=lambda x:x[1]) splitted = zip(*delta_d_alpha) host = host_subplot(111, axes_class=AA.Axes) plt.subplots_adjust(right=0.75) par1 = host.twinx() host.set_xlabel("Distance") host.set_ylabel("Delta") par1.set_ylabel("Apical Angle") p1, = host.plot(splitted[1], splitted[0], label="Delta") p2, = par1.plot(splitted[1], splitted[2], label="Distance") host.legend() host.axis["left"].label.set_color(p1.get_color()) par1.axis["right"].label.set_color(p2.get_color()) plt.draw() plt.show()
def show_ppt(self): ''' show the peeling and pasting trajectory in a figure ''' ax = host_subplot(111) ax.set_xlabel("peeling and pasting trajectory") par = ax.twinx() par.set_ylabel("nr. restricted dimensions") ax.plot(self.mean, label="mean") ax.plot(self.mass, label="mass") ax.plot(self.coverage, label="coverage") ax.plot(self.density, label="density") par.plot(self.res_dim, label="restricted_dim") ax.grid(True, which='both') ax.set_ylim(ymin=0,ymax=1) fig = plt.gcf() make_legend(['mean', 'mass', 'coverage', 'density', 'restricted_dim'], fig, ncol=5) return fig
def line_plot_overlapping_peak_intensity(dict_of_bins): from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA import matplotlib.pyplot as plt if 1: host = host_subplot(111, axes_class=AA.Axes) plt.subplots_adjust(right=0.75) par1 = host.twinx() par2 = host.twinx() #par3 = host.twinx() offset = 40 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0)) #new_fixed_axis = par3.get_grid_helper().new_fixed_axis #par3.axis["right"] = new_fixed_axis(loc="right", # axes=par3, # offset=(2 * offset, 0)) par2.axis["right"].toggle(all=True) #par3.axis["right"].toggle(all=True) List = dict_of_bins.values() names = dict_of_bins.keys() x_range = range(0, len(List[0])) host.set_xlim(0, len(List[0])) host.set_ylim(0, int(max(List[1])) + 10) host.set_xlabel("Clustered peaks") host.set_ylabel(names[1]) par1.set_ylabel(names[2]) par2.set_ylabel(names[3]) #par3.set_ylabel(names[3]) p1, = host.plot(x_range, List[1], label=names[1], marker='o') p2, = par1.plot(x_range, List[2], label=names[2], marker='o') p3, = par2.plot(x_range, List[3], label=names[3], marker='o') #p4, = par3.plot(x_range, List[3], label=names[3], marker='o') par1.set_ylim(0, int(max(List[2])) + 10) par2.set_ylim(0, int(max(List[3])) + 10) #par3.set_ylim(0, int(max(List[3])) + 10) host.legend(loc='upper left') host.axis["left"].label.set_color(p1.get_color()) par1.axis["right"].label.set_color(p2.get_color()) par2.axis["right"].label.set_color(p3.get_color()) #par3.axis["right"].label.set_color(p4.get_color()) plt.draw() # plt.show() plt.savefig( '/ps/imt/e/20141009_AG_Bauer_peeyush_re_analysis/further_analysis/overlap/overlapping_peak_intensity_'+names[0]+names[1]+'.png') plt.clf()
def plot_distribution(val): theta = np.pi/2*val sense = ta.lha_sensor() sigma = sense.get_sigma(100, theta) s = sense.sample_from(100, theta, 1000) x=None layers=160 for n in range(-layers,layers): y=np.arange((2*n-1)*np.pi/2,(2*n+1)*np.pi/2,np.pi/256)[0:256] if verbose: stderr.write("layer %d: shape: %r\n" % (n,y.shape)) if x==None: x = y else: if n != 0: y = y[::-1] x = np.vstack((x,y)) ax=x[layers,:] f=gauss(x,theta,sigma) host = host_subplot(111) n=0 plt.plot(ax,f[n+layers,:],linewidth=1, color='r', label='Gaussian assumption') #plt.plot(ax,f[1,:],linewidth=1, color='r') plt.plot(ax,f.sum(axis=0),linewidth=1, color='b', linestyle='--', label='effective') #ax.set_ticks([0., .5*np.pi, np.pi, 1.5*np.pi, 2*np.pi]) plt.axvline(-np.pi/2, color='grey', linestyle='--') plt.axvline(np.pi/2, color='grey', linestyle='--') plt.axhline(1/np.pi, color='grey', linestyle=':', label='Uniform') plt.legend(loc=10) return plt
def plot(self): host = host_subplot(111, axes_class=AA.Axes) plt.subplots_adjust(right=0.75) par1 = host.twinx() par2 = host.twinx() offset = 60 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0)) par2.axis["right"].toggle(all=True) host.set_xlim(0, 40000) host.set_ylim(-180, 400) host.set_xlabel("altitude [feet]") host.set_ylabel("direction [deg]") par1.set_ylabel("velocity [kts]") par2.set_ylabel("temperature [F]") p1, = host.plot(self.alt_markers, self.i_direction, label="Direction", color="black") p2, = host.plot(self.alt_markers, self.i_speed, label="Velocity", color="blue") p3, = host.plot(self.alt_markers, self.i_temperature, label="Temperature", color="red") par1.set_ylim(-180, 400) par2.set_ylim(-180, 400) host.legend() host.axis["left"].label.set_color(p1.get_color()) par1.axis["right"].label.set_color(p2.get_color()) par2.axis["right"].label.set_color(p3.get_color()) plt.draw() plt.show()
def mass_plot(self): sources = self.sources host = host_subplot(111, axes_class = AA.Axes) plt.subplots_adjust(right = 0.75) host.set_yscale("log") hist = sources.data["top"] bin_edges = sources.data["edges"] host.set_xlabel(sources.data["x_unit"], fontsize = 25) y_unit = sources.data["y_unit"] host.set_ylabel(y_unit, fontsize = 25) host.bar(bin_edges[:-1], hist, width = 1) host.set_xlim(min(bin_edges), max(bin_edges)) plt.xticks(fontsize = 16) plt.yticks(fontsize = 16) plt.show() """
def DrawLines(xlists, ylists, ylabels): line_count = len(ylists) ymin = min([min(ylist) for ylist in ylists]) ymax = max([max(ylist) for ylist in ylists]) diff = ymax-ymin ymin = ymin - 0.1*diff ymax = ymax + 0.1*diff clf() host = host_subplot(111, axes_class=AA.Axes) pyplot.subplots_adjust(right=(0.9-0.05*line_count)) host.set_xlabel('time') host.set_ylabel(ylabels[0]) host.set_ylim(ymin, ymax) p1, = host.plot(xlists[0], ylists[0], label=ylabels[0]) host.axis['left'].label.set_color(p1.get_color()) for i in range(1, line_count): offset = 60*i par = host.twinx() new_fixed_axis = par.get_grid_helper().new_fixed_axis par.axis["right"] = new_fixed_axis(loc="right", axes=par, offset=(offset, 0)) par.axis['right'].toggle(all=True) par.set_ylabel(ylabels[i]) p, = par.plot(xlists[i], ylists[i], label = ylabels[i]) par.set_ylim(ymin, ymax) par.axis['right'].label.set_color(p.get_color()) host.legend() pyplot.draw() pyplot.show()
def MakePlot(ncanvas,ndata,title,FigName,xlab,ylab,invert,x1,y1,x2,y2,x3,y3,show): if os.path.exists(FigName) == False : plt.figure(ncanvas) host = host_subplot(111) host.set_xlabel(xlab) host.set_ylabel(ylab) if invert == True : plt.gca().invert_xaxis() if ndata == 1 or ndata == 2 or ndata == 3 : plt.scatter(x1,y1,marker = 'o', color = 'g') if ndata == 2 or ndata == 3 : plt.scatter(x2,y2,marker = 'o', color = 'r') if ndata == 3 : plt.scatter(x3,y3,marker = 'o', color = 'b') plt.title(title) grid(False) savefig(FigName) plt.legend( loc='lower left') print(FigName+" has been created "+"\n") if show : plt.show() else : print(FigName + " already exists"+"\n")
def on_epoch_end(self, epoch, logs={}): self.val_losses.append(logs.get('val_loss')) self.val_accs.append(logs.get(self.additional_metric_name)) self.epochs.append(epoch) host = host_subplot(111) par = host.twinx() host.set_xlabel('epochs') host.set_ylabel("Accuracy") par.set_ylabel("Loss") p1, = host.plot(self.epochs, self.val_accs, label=self.additional_metric_name) p2, = par.plot(self.epochs, self.val_losses, label="Validation Loss") leg = plt.legend(loc='lower left') host.yaxis.get_label().set_color(p1.get_color()) leg.texts[0].set_color(p1.get_color()) par.yaxis.get_label().set_color(p2.get_color()) leg.texts[1].set_color(p2.get_color()) plt.title('Metrics by epoch') plt.savefig(self.filename) plt.close() # Do also flush STDOUT sys.stdout.flush()
def density_plot(rbin1, mTbin1, rhobin1, partAge1, rbin2, mTbin2, rhobin2, partAge2): if partAge1 < 0.0: particle_1_label = str(int(abs(partAge1))) + ' yr prior to formation' else: particle_1_label = str(int(partAge1)) + ' yr after formation' if partAge2 < 0.0: particle_2_label = str(int(abs(partAge2))) + ' yr prior to formation' else: particle_2_label = str(int(partAge2)) + ' yr after formation' pl.clf() pl.rc('text', usetex=True) pl.rc('font', family='serif') host = host_subplot(111, axes_class=AA.Axes) par1 = host.twinx() Ndensity_Y_min = 1e1 Ndensity_Y_max = 1e8 host.set_xlim(3e-3, 5e0) host.set_ylim(Ndensity_Y_min, Ndensity_Y_max) Mdensity_Y_min = Ndensity_Y_min * 2. * mp Mdensity_Y_max = Ndensity_Y_max * 2. * mp par1.set_ylim(Mdensity_Y_min, Mdensity_Y_max) par1.set_yscale('log') pl.gcf().subplots_adjust(bottom=0.15) host.set_ylabel('$n$ $({\\rm cm}^{-3})$', fontsize = 28) host.set_xlabel('$r$ $({\\rm pc})$', fontsize = 28) par1.set_ylabel('$\\rho$ $({\\rm g\\, cm}^{-3})$', fontsize = 28) host.axis["left"].label.set_fontsize(25) host.axis["bottom"].label.set_fontsize(25) par1.axis["right"].label.set_fontsize(25) host.loglog(rbin1, rhobin1/mp, 'b.--', label = particle_1_label) host.loglog(rbin2, rhobin2/mp, 'g-', label = particle_2_label) pl.legend(loc=0, fontsize='20', frameon=False) pl.rc('text', usetex=False)
def plot_gef_load_Z01_raw(): X, y, D = fear_load_mat('../data/gef_load_full_Xy.mat', 1) host = host_subplot(111, axes_class=AA.Axes) plt.subplots_adjust(right=0.85) par1 = host.twinx() # host.set_xlim(0, 2) # host.set_ylim(0, 2) host.set_xlabel("Time") host.set_ylabel("Load (Z01)") par1.set_ylabel("Temperature (T09)") p1, = host.plot(X[0:499,0], y[0:499]) p2, = par1.plot(X[0:499,0], X[0:499,9]) # par1.set_ylim(0, 4) host.legend() host.axis["left"].label.set_color(p1.get_color()) par1.axis["right"].label.set_color(p2.get_color()) plt.draw() plt.show()
def _init_ctrls(self, parent): wx.Panel.__init__(self, parent, -1) self.parent = parent #init Plot # matplotlib.figure.Figure self.figure = plt.figure() # matplotlib.axes.AxesSubplot self.timeSeries = host_subplot( 111, axes_class=AA.Axes) self.setTimeSeriesTitle("No Data to Plot") # matplotlib.backends.backend_wxagg.FigureCanvasWxAgg self.canvas = FigCanvas(self, -1, self.figure) self.canvas.SetFont(wx.Font(20, wx.SWISS, wx.NORMAL, wx.NORMAL, False, u'Tahoma')) self.isShowLegendEnabled = False # Create the navigation toolbar, tied to the canvas self.toolbar = NavigationToolbar(self.canvas, allowselect=True) self.canvas.mpl_connect('figure_leave_event', self.toolbar._onFigureLeave) Publisher.subscribe(self.updateCursor, "updateCursor") self.toolbar.Realize() self.seriesPlotInfo = None #set properties self.fontP = FontProperties() self.fontP.set_size('x-small') self.format = '-o' self.alpha=1 self._setColor("WHITE") left = 0.125 # the left side of the subplots of the figure plt.subplots_adjust( left=left#, bottom=bottom, right=right, top=top, wspace=wspace, hspace=hspace ) plt.tight_layout() #init lists #self.lines = {} self.lines = [] self.axislist = {} self.curveindex = -1 self.editseriesID = -1 self.editCurve = None self.editPoint =None # self.hoverAction = None self.selplot= None self.cursors = [] self.canvas.draw() self._init_sizers()
def plot_significance(X_test, y_test, est_decisions, min_BDT = 0.5, max_BDT = 1.0, bins_BDT = 10, luminosity = 30, s_fid_b = 0, s_fid_s =0) : BDT_bkg = est_decisions[y_test < 0.5] BDT_sig = est_decisions[y_test > 0.5] X_test_bkg = X_test[y_test < 0.5] X_test_sig = X_test[y_test > 0.5] bkg_weight = luminosity*s_fid_b / sum(np.ones(np.shape(X_test_bkg[:,0]))) * np.ones(np.shape(X_test_bkg[:,0])) sig_weight = luminosity*s_fid_s / sum(np.ones(np.shape(X_test_sig[:,0]))) * np.ones(np.shape(X_test_sig[:,0])) n, _, _ = plt.hist([BDT_bkg, BDT_sig], bins=bins_BDT, range=(min_BDT, max_BDT) , weights = [bkg_weight, sig_weight] , lw=1, alpha=0.5, color = ['red', 'orange'], label=['background', 'signal'], stacked = True) N_b = n[0] N_s = n[1] - n[0] # second histo is stack! weight = np.log(1 + N_s / N_b) second_term = (N_s + N_b)* weight middle = (max_BDT - min_BDT) / bins_BDT / 2 print 'sigma: ', get_ln_significance(N_s, N_b) host = host_subplot(111, axes_class=AA.Axes) plt.subplots_adjust(right=0.75) par1 = host.twinx() par2 = host.twinx() offset = 60 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0)) par2.axis["right"].toggle(all=True) host.set_xlim(min_BDT, max_BDT) host.set_ylim(0, 2.5) host.set_xlabel("BDT score (probability)") host.set_ylabel(r'Events at 30 fb$^{-1}$') par1.set_ylabel(r'$log(1 + N_s^i / N_b^i)$') par2.set_ylabel(r'$(N_s^i + N_b^i) * log(1 + N_s^i / N_b^i)$') p1 = host.hist([BDT_bkg, BDT_sig], bins=bins_BDT, range=(min_BDT, max_BDT) , weights = [bkg_weight, sig_weight] , lw=1, alpha=0.5, color = ['red', 'orange'], label=['background', 'signal'], stacked = True) host.legend(loc="best") p2, = par1.plot(np.linspace(min_BDT + middle, max_BDT + middle , bins_BDT, endpoint=False), weight , '-ro') p3, = par2.plot(np.linspace(min_BDT + middle, max_BDT + middle , bins_BDT, endpoint=False), second_term , '-bo') par1.axis["right"].label.set_color(p2.get_color()) par2.axis["right"].label.set_color(p3.get_color())
def plot_box_debit(folder): ticklabels = [] r_debit_tcp = [] r_debit_udp = [] files_r = [] fig_size = plt.rcParams["figure.figsize"] fig_size[0] = 14 # width fig_size[1] = 8 # heigth plt.rcParams["figure.figsize"] = fig_size host = host_subplot(111) host.set_ylabel("Mbit/s") files_r = parse_files(folder) for filename in files_r: if extention == ".flent": f = open(filename,"rb") else: f = gzip.open( filename,"rb") data = json.load(f) f.close() d = ([f for f in data['results']['TCP download'] if f is not None]) d = d[10:-10] p = ([f for f in data['results']['Ping (ms) ICMP'] if f is not None]) filename = filename.replace(folder,"").replace(extention,"") if filename.split("-")[-3] == "tcp": r_debit_tcp.append(d) label = "bw: " + filename.split("-")[-2].split("_")[0] + "mbit/s rtt: " + str(int(filename.split("-")[-1].split("_")[0])*2) + "ms" ticklabels.append("link 1 " + label + "\n" + "link 2 " + label) else: r_debit_udp.append(d) # draw boxplot and set colors bp1 = host.boxplot(r_debit_tcp, positions=np.array(xrange(len(r_debit_tcp)))*2 - 0.2, sym='', widths=0.3) bp2 = host.boxplot(r_debit_udp, positions=np.array(xrange(len(r_debit_udp)))*2 + 0.2, sym='', widths=0.3) color1 = '#60AAAA' color2 = 'y' color3 = 'green' plt.axhline(y=62,xmin=0.690,xmax=0.74,c=color3,linewidth=1,zorder=0) plt.axhline(y=16,xmin=0.410,xmax=0.450,c=color3,linewidth=1,zorder=0) set_box_color(bp1, color1) set_box_color(bp2, color2) # draw temporary red and blue lines and use them to create a legend plt.plot([], c=color1, label='TCP') plt.plot([], c=color2, label='UDP') plt.plot([], c=color3, label='MPTCP max theoretical throughput') plt.legend() best_m= 0 for i in r_debit_udp: if max(i) > best_m: best_m = max(i) plt.yticks(xrange(0, int(best_m), 10)) plt.xticks(xrange(0, len(ticklabels)*2 , 2 ), ticklabels, rotation=45) plt.xlim(-1, len(ticklabels)*2) plt.ylim(-1) plt.grid() plt.tight_layout() plt.savefig(file_ouput, format='PDF')
def init_axis(rows, cols, i, twin=False): # this creates axes with the axes artist loaded ax = host_subplot(rows, cols, i) # ,axes_class=AA.Axes) if twin: # the twin axis will create a second X and Y axis on the top and the left! return ax, ax.twin() else: return ax
def draw_CloudSat_1Dvar_pha(lon, lat, time, z, var_name, title_name): """ ====================================================================== Plot the CloudSat 1D var with orbit info. !!! Warnning sometimes not works very well ---------------------------------------------------------------------- draw_CloudSat_1Dvar(lon, lat, time, z, var_name, title_name, fig_name): ---------------------------------------------------------------------- Input: lon, lat, time: comes from cloudsat_tool.get_geo, time is the datetime object; z: 1-D var to plot; var_name: the name of the variable shows on the figure; title_name: title of the figure; Output: figure instance ====================================================================== """ from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA # fig fig=plt.figure(figsize=(10, 5)) host = host_subplot(111, axes_class=AA.Axes) fig.subplots_adjust(bottom=0.25) # divide axis par2 = host.twiny() par3 = host.twiny() offset = -25 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["top"] = new_fixed_axis(loc="bottom", axes=par2, offset=(0, offset)) offset = -62.5 new_fixed_axis = par3.get_grid_helper().new_fixed_axis par3.axis["top"] = new_fixed_axis(loc="bottom", axes=par3, offset=(0, offset)) # label axis host.set_ylabel(var_name) host.set_xlabel('\n\nGeolocation (longitude/latitude)') par3.set_xlabel('Orbit time') # set axis lim par2.set_xlim(lat.min(), lat.max()) par3.set_xlim(0, 1) host.set_xlim(lon.min(), lon.max()) host.set_ylim(z.min()-0.1*(z.max()-z.min()), z.max()+0.1*(z.max()-z.min())) # plot host.plot(lon, z, linewidth=1.5, linestyle='-', color='k') # labelling ticks host.set_yticks(np.linspace(z.min(), z.max(), 5)) host.set_xticks(np.linspace(lon.min(), lon.max(), 6)) par2.set_xticks(np.linspace(lat.min(), lat.max(), 6)) par2.invert_xaxis() count=0; labels_str=[0] * 6 for time_id in np.linspace(0, len(time)-1, 6).astype(int): labels_str[count]=time[time_id].strftime('%H:%M UCT') count+=1 par3.set_xticklabels(labels_str) # grid on host.grid() # title host.set_title(title_name, fontsize=14, fontweight='bold') return fig
def on_epoch_end(self, epoch, logs={}): self.val_losses.append(logs.get('val_loss')) self.epochs.append(epoch) if self.calc_training_acc: probabs_train = self.model.predict(self.X_train, verbose=0) probabs_val = self.model.predict(self.X_val, verbose=0) for out_layer in self.output_names: acc_val = self.accuracy(probabs_val, self.y_val[out_layer], out_layer) self.val_accs[out_layer].append(acc_val) if self.calc_training_acc: acc_train = self.accuracy(probabs_train, self.y_train[out_layer] , out_layer) print('train_acc: ' + str(acc_train) + ', val_acc: ' + str(acc_val)) self.train_accs[out_layer].append(acc_train) else: print('val_acc: ' + str(acc_val)) host = host_subplot(111) par = host.twinx() host.set_xlabel('epochs') host.set_ylabel("accuracy for layer " + out_layer) par.set_ylabel("overall loss") p1, = host.plot(self.epochs, self.val_accs[out_layer], label='Validation accuracy') if self.calc_training_acc: p2, = host.plot(self.epochs, self.train_accs[out_layer], label='Training accuracy') p3, = par.plot(self.epochs, self.val_losses, label="Validation loss") leg = plt.legend(loc='lower left') host.yaxis.get_label().set_color(p1.get_color()) leg.texts[0].set_color(p1.get_color()) if self.calc_training_acc: leg.texts[1].set_color(p2.get_color()) par.yaxis.get_label().set_color(p3.get_color()) leg.texts[2 if self.calc_training_acc else 1].set_color(p3.get_color()) plt.title('Accuracy by epoch on validation set for layer ' + out_layer) plt.savefig(self.base_folder + self.task_name + '_epochs_' + out_layer + '.png') plt.close() # early stopping if acc_val > self.max_val_acc: self.max_val_acc = acc_val self.max_epoch = epoch elif epoch - self.max_epoch > self.patience: print('Epoch %05d: early stopping' % (epoch)) self.model.stop_training = True # Do also flush STDOUT sys.stdout.flush()
def plot_thresh(directory,savepoint,parameter): #preamp directory1=directory directory=directory+'/*_threshold.h5' directory=glob(directory) vthin1Dac_array=() power_status_array=() Threshold_array=() PrmpVbpDac_array=() Threshold_sigma_array=() for files in directory: with tb.open_file(files, 'r') as in_file_h5: vthin1Dac= yaml.load(in_file_h5.root.meta_data.attrs.dac_status) power_status = yaml.load(in_file_h5.root.meta_data.attrs.power_status) Threshold= in_file_h5.root.Thresh_results.Threshold_pure.attrs.fitdata_thresh vthin1Dac_array = np.append(vthin1Dac_array,vthin1Dac['vthin1Dac']) power_status_array = np.append(power_status_array,power_status['VDDA[mA]']) Threshold_array = np.append(Threshold_array,Threshold['mu']) Threshold_sigma_array = np.append(Threshold_sigma_array, Threshold['sigma']) PrmpVbpDac_array = np.append(PrmpVbpDac_array,vthin1Dac[parameter]) host = host_subplot(111, axes_class=AA.Axes) plt.subplots_adjust(right=0.75) par1 = host.twinx() par2 = host.twinx() offset = 60 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["right"] = new_fixed_axis(loc="right", axes=(par2), offset=(offset, 0)) par2.axis["right"].toggle(all=True) host.set_xlabel(parameter) host.set_ylabel("VDDA [mA] ") host.set_ylim([18, 38]) par1.set_ylabel("Threshold [e-]") par1.set_ylim([0,1100]) par2.set_ylabel("vthin1Dac") par2.set_ylim([0, 100]) p1, = host.plot(PrmpVbpDac_array, power_status_array,'ro') host.errorbar(PrmpVbpDac_array, power_status_array, fmt='ro', yerr=0.05) p2, = par1.plot(PrmpVbpDac_array, Threshold_array * 1000*analysis.cap_fac(),'bv') par1.errorbar(PrmpVbpDac_array, Threshold_array*1000*analysis.cap_fac(), fmt='bv', yerr=(Threshold_sigma_array*1000*analysis.cap_fac()))#7.6 p3, = par2.plot(PrmpVbpDac_array, vthin1Dac_array,'gs') host.legend() host.axis["left"].label.set_color(p1.get_color()) par1.axis["right"].label.set_color(p2.get_color()) par2.axis["right"].label.set_color(p3.get_color()) plt.draw() a = directory1.rfind("/") plt.savefig(savepoint) plt.close()
def plot_box_debit(folder): ticklabels = [] r_debit = [] r_debit_3setup = [] files_r = [] fig_size = plt.rcParams["figure.figsize"] fig_size[0] = 14 # width fig_size[1] = 8 # heigth plt.rcParams["figure.figsize"] = fig_size host = host_subplot(111) host.set_ylabel("Mbit/s") files_r = parse_files(folder) for filename in files_r: filec = open(filename, "rb") f = csv.reader(filec, delimiter=",") d = [] # parse csv row and select only the value we want for row in f: d.append(float(row[0])) d = d[0:-1] if "3setup" in filename: print(filename) r_debit_3setup.append(d) else: r_debit.append(d) ticklabels.append(filename.replace(folder, "").replace(extention, "").replace("_3setup", "")) filec.close() # draw boxplot and set colors bp1 = host.boxplot(r_debit, positions=np.array(xrange(len(r_debit))) * 2.0, sym="", widths=0.4) bp2 = host.boxplot(r_debit_3setup, positions=np.array(xrange(len(r_debit))) * 2.0, sym="", widths=0.4) color1 = "#60AAAA" color2 = "#B0AAAA" set_box_color(bp1, color1) set_box_color(bp2, color2) # draw temporary red and blue lines and use them to create a legend plt.plot([], c=color1, label="bandwith link 1 : 32mbit/s rtt: 2ms \nbandwith link 2 : 8mbit/s rtt: 2ms") plt.plot([], c=color2, label="bandwith link 1 : 32mbit/s rtt: 400ms \nbandwith link 2 : 8mbit/s rtt: 2ms") plt.legend(loc=5) best_m = 0 for i in r_debit: if max(i) > best_m: best_m = max(i) plt.yticks(xrange(0, int(best_m), 5)) plt.xticks(xrange(0, len(ticklabels) * 2, 2), ticklabels, rotation=45) plt.xlim(-1, len(ticklabels) * 2) plt.ylim(-1) plt.grid() plt.tight_layout() plt.title("Congestion algorithms comparison") plt.savefig(file_ouput, format="PDF")
def plotPrediction(np_price_data, np_sentiment_data): # # plot the prices # fig, ax = plot.subplots() # plot.plot_date(np_price_data[-3000:-1000,1],np_price_data[-3000:-1000,0],'-') # # plot.plot_date(np_price_data[:,1],np_price_data[:,0],'-') # plot.plot_date(np_sentiment_data[:,1],np_sentiment_data[:,0],'-') # ax.autoscale_view() # ax.grid(True) # fig.autofmt_xdate() # plot.show() # fig, ax = plot.subplots() host = host_subplot(111) par = host.twinx() host.set_xlabel("Time") host.set_ylabel("Pair Price") par.set_ylabel("Sentiment") # p1, = host.plot_date(np_price_data[-3000:-1000,1],np_price_data[-3000:-1000,0],'-',label='Pair Price') p1, = host.plot_date(np_price_data[:,1],np_price_data[:,0],'-',label='Pair Price') from scipy.interpolate import interp1d x = np_sentiment_data[:,1] y = np_sentiment_data[:,0] f2 = interp1d(x, y, kind='cubic') xnew = np.linspace(np_sentiment_data[:,1].min(),np_sentiment_data[:,1].max(),500) p2, = par.plot_date(xnew,f2(xnew),'-',label='Sentiment') print 'done111' host.autoscale_view() host.grid(True) # par.set_ylim([-2000,500]) # fig.autofmt_xdate() # matplotlib.pyplot.autofmt_xdate() plot.xticks(rotation=40) leg = plot.legend(loc='lower right') host.yaxis.get_label().set_color(p1.get_color()) leg.texts[0].set_color(p1.get_color()) par.yaxis.get_label().set_color(p2.get_color()) leg.texts[1].set_color(p2.get_color()) # plot.show() fig = plot.gcf() fig.set_size_inches(18.5,10.5) plot.savefig('testFeb1.png',dpi=100)
def test_parasite(self): from mpl_toolkits.axes_grid1 import host_subplot host = host_subplot(111) par = host.twinx() p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density") p2, = par.plot([0, 1, 2], [0, 3, 2], label="Temperature") with mock.patch('matplotlib.legend.Legend') as Legend: plt.legend() Legend.assert_called_with(host, [p1, p2], ['Density', 'Temperature'])
def __init__(self,xlim,ylim,ylim2): plt.ion() self.fig = plt.figure() self.host = host_subplot(111, axes_class=AA.Axes) self.par1 = self.host.twinx() #self.ax = self.fig.add_subplot(111) self.lines=[None,None] self.host.set_xlim(xlim) self.host.set_ylim(ylim) self.par1.set_ylim(ylim2)
def plot_timewalk(folder,savefile,parameter): #precomp folder = glob(folder+'/*_threshold_timewalk.h5') threshold_all=() responds_all=() thresherror_all=() Preamp=() for files in folder: with tb.open_file(files, 'r') as in_file_h5: dac_status = yaml.load(in_file_h5.root.meta_data.attrs.dac_status) thresh= timewalk_reevaluated(files) #Threshold2=in_file_h5.root.td_threshold[:] #print "filename: ", files #print "Threshold1: ", thresh #print "Threshold2: ", Threshold2 #responds=0 #thresh=() #x=0 #for i in Threshold: #x=x+1 #if i[1]>0: #responds=responds+1 #thresh=np.append(thresh,i[1]) threshmean=np.mean(thresh) thresherror=np.std(thresh) responds_all=np.append(responds_all,len(thresh)) Preamp = np.append(Preamp, dac_status[parameter]) threshold_all=np.append(threshold_all,threshmean) thresherror_all = np.append(thresherror_all, thresherror) x=np.max(responds_all) x=int(x) plt.subplots_adjust(right=0.75) host = host_subplot(111, axes_class=AA.Axes) plt.subplots_adjust(right=0.75) par1 = host.twinx() host.set_xlabel(parameter) host.set_ylabel("In-time-threshold [e-]") par1.set_ylabel("Responding pixels max: " + str(x)) host.set_ylim([300,1400]) par1.set_ylim([0,70]) p1, = host.plot(Preamp, threshold_all, 'ro') host.errorbar(Preamp, threshold_all, fmt='ro', yerr=(thresherror_all)) if parameter=="PrmpVbpDac": width=2 else: width=4 par1.bar(Preamp,responds_all,width=width, color='b') host.legend() host.axis["left"].label.set_color(p1.get_color()) par1.axis["right"].label.set_color('b') plt.savefig(savefile) plt.close()
def test_picking_callbacks_overlap(big_on_axes, small_on_axes, click_on): """Test pick events on normal, host or parasite axes.""" # Two rectangles are drawn and "clicked on", a small one and a big one # enclosing the small one. The axis on which they are drawn as well as the # rectangle that is clicked on are varied. # In each case we expect that both rectangles are picked if we click on the # small one and only the big one is picked if we click on the big one. # Also tests picking on normal axes ("gca") as a control. big = plt.Rectangle((0.25, 0.25), 0.5, 0.5, picker=5) small = plt.Rectangle((0.4, 0.4), 0.2, 0.2, facecolor="r", picker=5) # Machinery for "receiving" events received_events = [] def on_pick(event): received_events.append(event) plt.gcf().canvas.mpl_connect('pick_event', on_pick) # Shortcut rectangles_on_axes = (big_on_axes, small_on_axes) # Axes setup axes = {"gca": None, "host": None, "parasite": None} if "gca" in rectangles_on_axes: axes["gca"] = plt.gca() if "host" in rectangles_on_axes or "parasite" in rectangles_on_axes: axes["host"] = host_subplot(111) axes["parasite"] = axes["host"].twin() # Add rectangles to axes axes[big_on_axes].add_patch(big) axes[small_on_axes].add_patch(small) # Simulate picking with click mouse event if click_on == "big": click_axes = axes[big_on_axes] axes_coords = (0.3, 0.3) else: click_axes = axes[small_on_axes] axes_coords = (0.5, 0.5) # In reality mouse events never happen on parasite axes, only host axes if click_axes is axes["parasite"]: click_axes = axes["host"] (x, y) = click_axes.transAxes.transform(axes_coords) m = MouseEvent("button_press_event", click_axes.figure.canvas, x, y, button=1) click_axes.pick(m) # Checks expected_n_events = 2 if click_on == "small" else 1 assert len(received_events) == expected_n_events event_rects = [event.artist for event in received_events] assert big in event_rects if click_on == "small": assert small in event_rects
def main(args): data = {} files = args.file_names.split(',') n = 0 for f in files: with open(f, newline='') as f: reader = csv.reader(f, delimiter=' ', quotechar='|') for row in reader: data[n] = ', '.join(row) if args.mode.startswith('rlkit'): directory = ('./rlkit/data/' + args.session_name) if args.session_name != '' else './' data['rewards'] = {} data['tower_heights'] = {} data['collisions'] = {} variant, params = doc.load_rklit_file(args.session_name) random_play_offset = args.start_offset + int( variant['algorithm_kwargs']['min_num_steps_before_training']) end_offset = args.end_offset rew = [] tow = [] col = [] collisions = [] which_buf = "_eval" if args.mode == 'rlkit_eval' else ( '_expl' if not args.mode == 'rlkit' else '') for i in range( random_play_offset, int(params['replay_buffer' + which_buf + '/size'] - end_offset)): step_rew = params['replay_buffer' + which_buf + '/rewards'][i].tolist()[0] rew.append(step_rew) tow.append( max(params['replay_buffer' + which_buf + '/observations'][i].tolist())) col.append(0 if step_rew > 0 else 1) r = partition_list(rew, 21) t = partition_list(tow, 21) c = partition_list(col, 21) collisions = [] towers = [] for i in range(len(r)): data['rewards'][str(i)] = r[i] data['tower_heights'][str(i)] = max(t[i]) data['collisions'][str(i)] = sum(c[i]) collisions.append(sum(c[i])) towers.append(max(t[i])) num_plays = len(data['rewards']) returns = [None] * num_plays for i in data['rewards']: returns[int(i)] = sum(data['rewards'][i]) if args.mode == 'sac': plt.plot(range(num_plays), returns, linewidth=0.3, color='#C9DBFF') plt.plot(range(num_plays), smooth(returns, args.smoothing), linewidth=0.6) plt.xlabel('plays') plt.ylabel('returns') plt.title('Total reward') plt.savefig(directory + '/returns.png', dpi=300, figsize=(19.20 * 2, 10.80 * 2)) if args.show == 'True': plt.show() sac_plot(args, data, directory, num_plays) elif args.mode.startswith('rlkit'): ''' plt.plot(range(num_plays), returns, linewidth=0.3, color='#C9DBFF') plt.plot(range(num_plays), smooth(returns, args.smoothing), linewidth=0.6) plt.xlabel('plays') plt.ylabel('returns') plt.title(args.title) plt.savefig(directory+'/rlkit_'+args.title+'.png', dpi=300, figsize=(19.20*2,10.80*2)) ''' host = host_subplot(111, axes_class=AA.Axes) plt.subplots_adjust(right=0.75) par1 = host.twinx() par2 = host.twinx() offset = 50 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0)) par1.axis["right"].toggle(all=True) host.set_xlim(0, num_plays) host.set_ylim(-3.0, 12.0) host.set_xlabel("Plays") host.set_ylabel("Return") par1.set_ylabel("Nr. of Collisions") par2.set_ylabel("Tower Height [mm]") #returns = returns[args.start_offset:num_plays] #collisions = collisions[args.start_offset:num_plays] #towers = towers[args.start_offset:num_plays] #rng = range(0,num_plays - args.start_offset) rng = range(num_plays) p1, = host.plot(rng, returns, linewidth=0.15, alpha=0.4, color='#FF0000') p1a, = host.plot(rng, smooth(returns, args.smooth_window, args.smooth_deg), label="Returns", linewidth=0.7, color='#FF0000') p2, = par1.plot(rng, collisions, linewidth=0.15, alpha=0.4, color='#0000FF') p2a, = par1.plot(rng, smooth(collisions, args.smooth_window, args.smooth_deg), label="Collisions", linewidth=0.7, color='#0000FF') p3, = par2.plot(rng, towers, linewidth=0.15, alpha=0.4, color='#00FF00') p3a, = par2.plot(rng, smooth(towers, args.smooth_window, args.smooth_deg), label="Tower Height", linewidth=0.7, color='#00FF00') par1.set_ylim(0, 23) par2.set_ylim(0.0, 1300.0) host.legend() host.axis["left"].label.set_color(p1a.get_color()) par1.axis["right"].label.set_color(p2a.get_color()) par2.axis["right"].label.set_color(p3a.get_color()) plt.title(args.title) #plt.draw() if args.show == 'True': plt.show() plt.savefig(directory + '/rlkit_' + args.title + '.png', dpi=300, figsize=(19.20 * 2, 10.80 * 2))
def plotterX(inp,fname): plot_x_min, plot_x_max, plot_y_min, plot_y_max = smartscale(inp) host = host_subplot(111, axes_class=AA.Axes) host.set_xlabel("Elution volume (ml)") host.set_ylabel("Absorbance (mAu)") host.set_xlim(plot_x_min, plot_x_max) host.set_ylim(plot_y_min, plot_y_max) for i in inp.keys(): if i.startswith('UV') and not i.endswith('_0nm'): plot_this_data = True if args.wavelength: plot_this_data = any([w in i for w in args.wavelength]) if plot_this_data: x_dat, y_dat = xy_data(inp[i]['data']) print("Plotting: " + inp[i]['data_name']) stl = styles[i[:4]] p0, = host.plot(x_dat, y_dat, label=inp[i]['data_name'], color=stl['color'], ls=stl['ls'], lw=stl['lw'],alpha=stl['alpha']) if args.par1 == 'None': args.par1 = None if args.par1: try: par1_inp = args.par1 par1 = host.twinx() par1_data = inp[par1_inp] stl = styles[par1_inp[:4]] par1.set_ylabel(par1_data['data_name'] + " (" + par1_data['unit'] + ")", color=stl['color']) x_dat_p1, y_dat_p1 = xy_data(par1_data['data']) p1_ymin, p1_ymax = expander(min(y_dat_p1), max(y_dat_p1), 0.085) par1.set_ylim(p1_ymin, p1_ymax) print("Plotting: " + par1_data['data_name']) p1, = par1.plot(x_dat_p1, y_dat_p1, label=par1_data['data_name'], color=stl['color'], ls=stl['ls'], lw=stl['lw'], alpha=stl['alpha']) except: KeyError if par1_inp != None: print("Warning: Data block chosen for par1 does not exist!") if args.par2: try: par2_inp = args.par2 par2 = host.twinx() offset = 60 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0)) par2.axis["right"].toggle(all=True) par2_data = inp[par2_inp] stl = styles[par2_inp[:4]] par2.set_ylabel(par2_data['data_name'] + " (" + par2_data['unit'] + ")", color=stl['color']) x_dat_p2, y_dat_p2 = xy_data(par2_data['data']) p2_ymin, p2_ymax = expander(min(y_dat_p2), max(y_dat_p2), 0.075) par2.set_ylim(p2_ymin, p2_ymax) print("Plotting: " + par2_data['data_name']) p2, = par2.plot(x_dat_p2, y_dat_p2, label=par2_data['data_name'], color=stl['color'],ls=stl['ls'], lw=stl['lw'], alpha=stl['alpha']) except: KeyError if par2_inp != None: print("Warning: Data block chosen for par2 does not exist!") if not args.no_fractions: try: frac_data = inp['Fractions']['data'] frac_x, frac_y = xy_data(frac_data) frac_delta = [abs(a - b) for a, b in zip(frac_x, frac_x[1:])] frac_delta.append(frac_delta[-1]) frac_y_pos = mapper(host.get_ylim()[0], host.get_ylim()[1], 0.015) for i in frac_data: host.axvline(x=i[0], ymin=0.065, ymax=0.0, color='r', linewidth=0.85) host.annotate(str(i[1]), xy=(i[0] + frac_delta[frac_data.index(i)] * 0.55, frac_y_pos), horizontalalignment='center', verticalalignment='bottom', size=8, rotation=90) except: KeyError if inp.inject_vol != 0.0: injections = inp.injection_points host.axvline(x=0, ymin=0.10, ymax=0.0, color='#FF3292', ls ='-', marker='v', markevery=2, linewidth=1.5, alpha=0.85, label='Inject') host.set_xlim(plot_x_min, plot_x_max) if not args.no_legend: host.legend(fontsize=8, fancybox=True, labelspacing=0.4, loc='upper right', numpoints=1) host.xaxis.set_minor_locator(AutoMinorLocator()) host.yaxis.set_minor_locator(AutoMinorLocator()) if not args.no_title: plt.title(fname, loc='left', size=9) plot_file = fname[:-4] + "_" + inp.run_name + "_plot." + args.format plt.savefig(plot_file, bbox_inches='tight', dpi=args.dpi) print("Plot saved to: " + plot_file) plt.clf()
from mpl_toolkits import axisartist import matplotlib.pyplot as plt import pandas as pd import numpy as np #initialize paramenter here plt.rcParams["figure.figsize"] = (12,10) plt.rcParams["axes.labelsize"] = 16 plt.rcParams['ytick.labelsize'] = 12 plt.rcParams['legend.fontsize'] = 12 mal_frac = str(("%.6f" % (2**-1))) hell_evpr_multi = str(100) filename = "AntSimData_SIM_STEPS-50000_SIM_ITERS-1_mal_frac-"+mal_frac+"_mal_delay-100_mal_ants_focus-1_ant_tracing-1_ctr_pherm-1_hell_phermn_intens-1.000000_hell_phermn_evpr-"+hell_evpr_multi+".000000_iter-0.csv" foldername = "./data/" data = pd.read_csv(foldername+filename,header=None).T data = np.array(data) host = host_subplot(111, axes_class=axisartist.Axes) plt.subplots_adjust(right=0.75) par1 = host.twinx() par1.axis["right"].toggle(all=True) #define which one will get plot l1,l2 = host.plot(data[0:2].T) #this is the left axis data l3,l4 = par1.plot(100*data[2:4].T) #this is the right axis data, multiply by 100 to make it percentage. #change the style of line here plt.setp(l2,linestyle='--', linewidth=2) plt.setp(l3, linestyle=':', linewidth=2) plt.setp(l4, linestyle='-.', linewidth=2) par1.set_ylim(0, 100) #set y range for fraction to be between 0 - 100 plt.xlabel('Iterations') #x axis plt.ylabel('Food bits per ants', fontsize=20) #left axis par1.set_ylabel("Percentage of cooperators", fontsize=20) #right axis par1.legend()
def viz_opt_curves(df, opt_df, method, chromnames, expected_mts=60000, mts=1000, resolution=5000, stage='3-4h'): """ Function to vizualize curves of coverage value, mean tad size and number of tads depend on gamma values in our grid. :param df: for modularity and armatus -- dataframe with all segmentations based on all gamma values from our grid. for insulation -- dictionary with statistics. :param opt_df: dataframe with segmentation for optimal gamma / window values :param method: TAD or TAD boundaries calling method (insulation, armatus or modularity). :param chromnames: list of chromosomes of interest. :param expected_mts: expected mean size of TADs :param mts: maximum TAD size. :param resolution: resolution of Hi-C maps :param stage: stage of development by which TAD or TAD boundaries calling was performed :return: -- """ # expected_mts /= resolution for ch in chromnames: if method == 'insulation': od = collections.OrderedDict(sorted(df[ch].items())) gr_mean = [od[i][0] for i in od] # gr_cov = [od[i][1] for i in od] # gr_count = [od[i][2] for i in od] gr_ins = [od[i][3] for i in od] gr_bsc = [od[i][4] for i in od] w_range = [i for i in od] else: gr_mean = df.query('ch=="{}"'.format(ch)).groupby(['gamma', 'ch']).mean().reset_index().sort_values(['ch', 'gamma']) gr_count = df.query('ch=="{}"'.format(ch)).groupby(['gamma', 'ch']).count().reset_index().sort_values( ['ch', 'gamma']) gr_cov = df.query('ch=="{}"'.format(ch)).groupby(['gamma', 'ch']).sum().reset_index().sort_values(['ch', 'gamma']) plt.figure(figsize=[10, 5]) host = host_subplot(111, axes_class=AA.Axes) par1 = host.twinx() par2 = host.twinx() offset = 70 new_fixed_axis = par1.get_grid_helper().new_fixed_axis par1.axis["left"] = new_fixed_axis(loc="left", axes=par1, offset=(-offset, 0)) offset = 120 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["left"] = new_fixed_axis(loc="left", axes=par2, offset=(-offset, 0)) if method == 'insulation': host.set_xlabel("Window") host.set_ylabel("Mean TAD size") par1.set_ylabel("Mean Insulation score") par2.set_ylabel("Mean B-score") else: host.set_xlabel("Gamma") host.set_ylabel("Mean TAD size") par1.set_ylabel("Coverage") par2.set_ylabel("TADs count") if method == 'insulation': p1, = host.plot(w_range, [x * resolution for x in gr_mean], label="{} mean TAD size".format(ch)) p1, = host.plot([min(w_range), max(w_range)], [expected_mts, expected_mts], color=p1.get_color()) p1, = host.plot( [list(set(opt_df[opt_df.ch == ch]['window']))[0], list(set(opt_df[opt_df.ch == ch]['window']))[0]], [0, expected_mts], color=p1.get_color(), linestyle='dashed') p2, = par1.plot(w_range, gr_ins, label="{} mean insulation score".format(ch)) p3, = par2.plot(w_range, gr_bsc, label="{} mean B-score".format(ch)) else: p1, = host.plot(gr_mean.gamma, gr_mean.length, label="{} mean TAD size".format(ch)) p1, = host.plot([min(df[df['ch'] == ch]['gamma']), max(df[df['ch'] == ch]['gamma'])], [expected_mts, expected_mts], color=p1.get_color()) p2, = par1.plot(gr_cov.gamma, gr_cov.length, label="{} coverage".format(ch)) p3, = par2.plot(gr_count.gamma, gr_count.length, label="{} count".format(ch)) host.set_ylim([0, max(gr_mean.length)]) host.axis["left"].label.set_color(p1.get_color()) par1.axis["left"].label.set_color(p2.get_color()) par2.axis["left"].label.set_color(p3.get_color()) if method == 'insulation': plt.title('Stage {}, Chr {}, Method: {}, expected TAD size: {} Kb, optimal window: {}'.format(stage, ch, method, str(expected_mts), list(set(opt_df[opt_df.ch == ch]['window']))[0] // resolution)) else: plt.title('Stage {}, Chr {}, Method: {}, expected TAD size: {} Kb, optimal gamma: {}'.format(stage, ch, method, str(expected_mts), list(set(opt_df[opt_df.ch == ch]['gamma']))[0] // resolution)) plt.draw() plt.show()
plt.xlim(xlim_start,xlim_end) plt.ylim(0,1.01) plt.ylabel('coherence') plt.xlabel('frequency (Hz)') plt.title('coherence x/y with repeated ts: '+str(tile_no)) ## PLOT 9 rad2time = ph/(2*np.pi*f) mtcl2time = phif/(2*np.pi*f) neg_time= np.where(rad2time<0) dur_cycl = (1/f) rad2time[neg_time] = rad2time[neg_time]+dur_cycl[neg_time] ax = host_subplot(122, axes_class=AA.Axes) p1 = plt.Rectangle((0, 0), 1, 1, fc='c', ec='c') p2, = ax.plot(f, rad2time, color='m', zorder=5, label='Phase') p3, = ax.plot(f, dur_cycl, color='gray', linestyle='-.', zorder=5, label='Period') p4, = ax.plot(f, dur_cycl/2, color='gray', linestyle='--', zorder=5, label='Halve period') ax.fill_between(f,(rad2time+mtcl2time),(rad2time-mtcl2time), where=(((rad2time+mtcl2time)<dur_cycl)), facecolor='c' ,edgecolor='c', lw=0.0 ,interpolate=True, zorder=4) ax.fill_between(f,(rad2time-mtcl2time),dur_cycl, where=(((rad2time+mtcl2time)>dur_cycl)), facecolor='c' ,edgecolor='c', lw=0.0 ,interpolate=True, zorder=4) ax.fill_between(f,(rad2time+mtcl2time)-dur_cycl, where=(((rad2time+mtcl2time)>0)), facecolor='c' ,edgecolor='c', lw=0.0 ,interpolate=True, zorder=4) ax.fill_between(f,((rad2time-mtcl2time)+dur_cycl),dur_cycl, where=((rad2time-mtcl2time)<0), facecolor='c' ,edgecolor='c', lw=0.0 ,interpolate=True, zorder=4)
def makeSomePlots(forcing, pwp_out, time_vec=None, save_plots=False, suffix=''): """ TODO: add doc file Function to make plots of the results once the model iterations are complete. """ if len(suffix) > 0 and suffix[0] != '_': suffix = '_%s' % suffix #plot summary of ML evolution fig, axes = plt.subplots(3, 1, sharex=True, figsize=(7.5, 9)) if time_vec is None: tvec = pwp_out['time'] else: tvec = time_vec axes = axes.flatten() ##plot surface heat flux axes[0].plot(tvec, forcing['lw'], label='$Q_{lw}$') axes[0].plot(tvec, forcing['qlat'], label='$Q_{lat}$') axes[0].plot(tvec, forcing['qsens'], label='$Q_{sens}$') axes[0].plot(tvec, forcing['sw'], label='$Q_{sw}$') axes[0].hlines(0, tvec[0], pwp_out['time'][-1], linestyle='-', color='0.3') axes[0].plot(tvec, forcing['q_in'] - forcing['q_out'], ls='-', lw=2, color='k', label='$Q_{net}$') axes[0].set_ylabel('Heat flux (W/m2)') axes[0].set_title('Heat flux into ocean') axes[0].grid(True) #axes[0].set_ylim(-500,300) axes[0].legend(loc=0, ncol=2, fontsize='smaller') ##plot wind stress axes[1].plot(tvec, forcing['tx'], label=r'$\tau_x$') axes[1].plot(tvec, forcing['ty'], label=r'$\tau_y$') axes[1].hlines(0, tvec[0], pwp_out['time'][-1], linestyle='--', color='0.3') axes[1].set_ylabel('Wind stress (N/m2)') axes[1].set_title('Wind stress') axes[1].grid(True) axes[1].legend(loc=0, fontsize='medium') ## plot freshwater forcing # emp_mmpd = forcing['emp']*1000*3600*24 #convert to mm per day # axes[2].plot(tvec, emp_mmpd, label='E-P') # axes[2].hlines(0, tvec[0], pwp_out['time'][-1], linestyle='--', color='0.3') # axes[2].set_ylabel('Freshwater forcing (mm/day)') # axes[2].set_title('Freshwater forcing') # axes[2].grid(True) # axes[2].legend(loc=0, fontsize='medium') # axes[2].set_xlabel('Time (days)') emp_mmpd = forcing['emp'] * 1000 * 3600 * 24 #convert to mm per day evap_mmpd = forcing['evap'] * 1000 * 3600 * 24 #convert to mm per day precip_mmpd = forcing['precip'] * 1000 * 3600 * 24 #convert to mm per day axes[2].plot(tvec, precip_mmpd, label='$P$', lw=1, color='b') axes[2].plot(tvec, evap_mmpd, label='$-E$', lw=1, color='r') axes[2].plot(tvec, emp_mmpd, label='$|E| - P$', lw=2, color='k') axes[2].hlines(0, tvec[0], tvec[-1], linestyle='--', color='0.3') axes[2].set_ylabel('Freshwater forcing (mm/day)') axes[2].set_title('Freshwater forcing') axes[2].grid(True) axes[2].legend(loc=1, fontsize=8, ncol=2) axes[2].set_xlabel('Time (days)') if save_plots: plt.savefig('plots/surface_forcing%s.png' % suffix, bbox_inches='tight') ##plot temp and sal change over time fig, axes = plt.subplots(2, 1, sharex=True) vble = ['temp', 'sal'] units = ['$^{\circ}$C', 'PSU'] #cmap = custom_div_cmap(numcolors=17) cmap = plt.cm.rainbow for i in range(2): ax = axes[i] im = ax.contourf(pwp_out['time'], pwp_out['z'], pwp_out[vble[i]], 15, cmap=cmap, extend='both') ax.set_ylabel('Depth (m)') ax.set_title('Evolution of ocean %s (%s)' % (vble[i], units[i])) ax.invert_yaxis() cb = plt.colorbar(im, ax=ax, format='%.1f') ax.set_xlabel('Days') ## plot initial and final T-S profiles from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA plt.figure() host = host_subplot(111, axes_class=AA.Axes) host.invert_yaxis() par1 = host.twiny() #par for parasite axis host.set_ylabel("Depth (m)") host.set_xlabel("Temperature ($^{\circ}$C)") par1.set_xlabel("Salinity (PSU)") p1, = host.plot(pwp_out['temp'][:, 0], pwp_out['z'], '--r', label='$T_i$') host.plot(pwp_out['temp'][:, -1], pwp_out['z'], '-r', label='$T_f$') p2, = par1.plot(pwp_out['sal'][:, 0], pwp_out['z'], '--b', label='$S_i$') par1.plot(pwp_out['sal'][:, -1], pwp_out['z'], '-b', label='$S_f$') host.grid(True) host.legend(loc=0, ncol=2) #par1.legend(loc=3) host.axis["bottom"].label.set_color(p1.get_color()) host.axis["bottom"].major_ticklabels.set_color(p1.get_color()) host.axis["bottom"].major_ticks.set_color(p1.get_color()) par1.axis["top"].label.set_color(p2.get_color()) par1.axis["top"].major_ticklabels.set_color(p2.get_color()) par1.axis["top"].major_ticks.set_color(p2.get_color()) if save_plots: plt.savefig('plots/initial_final_TS_profiles%s.png' % suffix, bbox_inches='tight') plt.show()
def render_plot(urls, tstartstr, tendstr): tstart = LocalTimeToUtc(ParseTime(tstartstr)) tend = LocalTimeToUtc(ParseTime(tendstr)) log = DataLog() log.Open(readOnly=True) colors = 'rgb' urlsSplit = urls.split(',') ax = [] pos = [] if len(urlsSplit) > 0: host = host_subplot(111, axes_class=AA.Axes) ax.append(host) pos.append('left') if len(urlsSplit) > 1: par1 = host.twinx() ax.append(par1) pos.append('right') if len(urlsSplit) > 2: par2 = host.twinx() plt.subplots_adjust(right=0.75) offset = 60 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0)) ax.append(par2) pos.append('right') for i in range(len(ax)): try: url = urlsSplit[i] dbkey, unit = log.SignalGet(url.split('.')[2]) label = url + " (" + unit + ")" times, n, values = log.Query(url, tstart, tend) sumn, minp50, maxp50 = log.QueryAccumulates(url) ax[i].set_xlim(UtcToLocalTime([tstart, tend])) ax[i].set_ylim([np.floor(minp50), np.ceil(maxp50)]) ax[i].set_ylabel(label) ax[i].tick_params(axis='y', colors=colors[i], which='both') ax[i].axis[pos[i]].label.set_color(colors[i]) ax[i].axis[pos[i]].major_ticklabels.set_color(colors[i]) DoPlot(times, values[:, 2], ax[i], '-' + colors[i]) if i > 0: ax[i].axis['bottom'].toggle(all=False) except Exception as e: ax[i].text(0.5, (1 + i) / (len(ax) + 1.0), str(e), \ horizontalalignment='center', verticalalignment='center', \ transform = ax[i].transAxes, color=colors[i]) placeName = url.split('.')[0] wgs84long, wgs84lat, heightMeters = log.PlaceDetailsGet(placeName) PlotDayNight(ax[0], tstart, tend, wgs84long, wgs84lat) ax[0].axis["bottom"].major_ticklabels.set_rotation(30) ax[0].axis["bottom"].major_ticklabels.set_ha("right") ax[0].grid() log.Close() img = StringIO.StringIO() mydpi = 150 plt.gcf().set_size_inches(1100 / mydpi, 900 / mydpi, forward=True) plt.savefig(img, dpi=mydpi) plt.close() img.seek(0) return flask.send_file(img, mimetype='image/png')
def plot_selected(self, values, dat): """ Plot data based on selected keys within listboxes. """ fail = 0 self.color_error_flag = 0 self.f.clf() self.plots = [] try: if self.var_bounds.get(): try: self.bounds except AttributeError: self.error_display("No bounds information in history file") fail = 1 # Plot on shared axes if self.var.get() == 0 and not fail: a = self.f.add_subplot(111) # Calculate and plot the delta values if selected if self.var_del.get(): for idx, val in enumerate(values): newdat = [] for i, value in enumerate(dat[val], start=1): newdat.append(abs(value - dat[val][i - 2])) plots = a.plot(range(1, self.num_iter), newdat[1:], "o-", label=val, markeredgecolor='none', clip_on=False) if len(plots) > 1: for i, plot in enumerate(plots): self.plots.append([plot, i]) else: self.plots.append([plots[0], -1]) # Otherwise plot original data else: for i, val in enumerate(values): self.orig_plot(dat, val, values, a, i) if self.color_error_flag and self.var_bounds.get(): self.warning_display( "Line color for bounds may not match data color") # Plot using log scale if selected if self.var_log.get(): a.set_yscale('log') if self.var_legend.get(): a.legend(loc='best') plt.subplots_adjust(right=.95) a.set_xlabel('iteration') a.set_xlim(0, self.num_iter - 1) self.canvas.show() # Plot on individual vertical axes elif self.var.get() == 1 and not fail: # Set window sizing parameters for when additional axes are # added n = len(values) plt.figure(self.f.number) par_list = [[] for i in range(n)] # make into array par_list[0] = host_subplot(111, axes_class=AA.Axes) size_list = [.95, .95, .93, .83, .73, .63, .53, .43, .33] plt.subplots_adjust(right=size_list[n]) for i in range(1, n): par_list[i] = par_list[0].twinx() offset = 60 for i in range(2, n): new_fixed_axis = par_list[i].get_grid_helper( ).new_fixed_axis par_list[i].axis["right"] = new_fixed_axis( loc="right", axes=par_list[i], offset=(offset * i**1.15, 0)) par_list[i].axis["right"].toggle(all=True) p_list = [[] for i in range(n)] # Compute and plot delta values if selected if self.var_del.get(): for i, val in enumerate(values): newdat = [] for idx, value in enumerate(dat[val], start=1): newdat.append(abs(value - dat[val][idx - 2])) p_list[i], = par_list[i].plot(range(1, self.num_iter), newdat[1:], "o-", label=val, markeredgecolor='none', clip_on=False) par_list[i].set_ylabel(val) # Otherwise plot original data else: for i, val in enumerate(values): cc = (matplotlib.rcParams['axes.color_cycle'] * 10) par_list[i].set_color_cycle(cc[i]) p_list[i], = par_list[i].plot(dat[val], "o-", label=val, markeredgecolor='none', clip_on=False) par_list[i].set_ylabel(val) try: if self.var_bounds.get(): self.plot_bounds(val, par_list[i], cc[i]) except (ValueError, UnboundLocalError): if len(values) > 1: pass else: self.error_display("No bounds information") # Plot using log scale if selected if self.var_log.get(): for ax in par_list: ax.set_yscale('log') par_list[0].set_xlim(0, self.num_iter - 1) par_list[0].set_xlabel('iteration') if self.var_legend.get(): par_list[0].legend(loc='best') for i, plot in enumerate(p_list): self.plots.append([plot, i]) self.canvas.show() # Plot on stacked axes with shared x-axis elif self.var.get() == 2 and not fail: n = len(values) # Compute and plot delta values if selected if self.var_del.get(): a = [] for i, val in enumerate(values): newdat = [] for idx, value in enumerate(dat[val], start=1): newdat.append(abs(value - dat[val][idx - 2])) a.append(self.f.add_subplot(n, 1, i + 1)) plots = a[i].plot(range(1, self.num_iter), newdat[1:], "o-", label=val, markeredgecolor='none', clip_on=False) a[i].set_ylabel('delta ' + val) self.plots.append([plots[0], -1]) # Otherwise plot original data else: a = [] for i, val in enumerate(values): a.append(self.f.add_subplot(n, 1, i + 1)) self.orig_plot(dat, val, values, a[i]) # Plot using log scale if selected if self.var_log.get(): for ax in a: ax.set_yscale('log') # Turn off horiztonal axes above the bottom plot a[-1].set_xlabel('iteration') for ax in a: if ax != a[-1]: ax.spines['bottom'].set_visible(False) ax.set_xticklabels([]) ax.xaxis.set_major_locator(plt.NullLocator()) ax.spines['top'].set_visible(False) for tic in ax.xaxis.get_major_ticks(): tic.tick2On = False ax.tick_params(axis='y', which='both', labelleft='off', labelright='on') ax.set_xlim(0, self.num_iter - 1) plt.subplots_adjust(right=.95) self.canvas.show() except ValueError: self.error_display()
""" ================ Simple Axisline4 ================ """ import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA import numpy as np ax = host_subplot(111) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis ax2.set_xticks([0., .5 * np.pi, np.pi, 1.5 * np.pi, 2 * np.pi]) ax2.set_xticklabels( ["$0$", r"$\frac{1}{2}\pi$", r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"]) ax2.axis["right"].major_ticklabels.set_visible(False) ax2.axis["top"].major_ticklabels.set_visible(True) plt.draw() plt.show()
def _plot_training_stats(self, stats, n_explore_episodes, stats_file_path): from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator episodes, epsilons, rewards, max_qs, errors = zip(*stats) if len(stats) <= n_explore_episodes + 1: y_values = np.array(rewards) else: y_values = np.concatenate([ rewards, max_qs[n_explore_episodes + 1:], errors[n_explore_episodes + 1:] ]) y_range = int(np.min(y_values)) - 1, int(np.max(y_values)) + 1 # plt.rcParams["figure.figsize"] = (10, 8) par0 = host_subplot(111, axes_class=AA.Axes) par1 = par0.twinx() par2 = par0.twinx() par3 = par0.twinx() plt.subplots_adjust(right=0.85) new_fixed_axis = par1.get_grid_helper().new_fixed_axis par1.axis["right"] = new_fixed_axis(loc="right", axes=par1, offset=(0, 0)) par1.axis["right"].toggle(all=True) par0.set_xlabel("Episode") par0.set_ylabel("Epsilon") par1.set_ylabel("Reward, Q max, Q error") par0.plot(episodes, epsilons, label="Epsilon") par1.plot(episodes, rewards, label="Reward", marker='o', linewidth=0, markersize=2) par2.plot(episodes, max_qs, label="Q max", marker='.', linewidth=1, markersize=1) par3.plot(episodes, errors, label="Q error", marker='.', linewidth=1, markersize=1) par0.set_ylim([0, 1]) par0.xaxis.set_major_locator(MaxNLocator(integer=True)) par1.set_ylim(y_range) par2.set_ylim(y_range) par3.set_ylim(y_range) par0.legend(loc="upper left") plt.draw() # plt.show(block=False) if stats_file_path: plt.savefig(stats_file_path) else: plt.show() plt.gcf().clear()
def figure_2(): """ Figure 2. Binarizing and skeletonizing the region highlighted in an input photomicrograph [1]. (a) Input photomicrograph. (b) Example highlighted region. (c) Binarizing the example region using the ISODATA algorithm (threshold: 133). (d) Skeletonizing the binary region in (c). Colormap: gray. [1] Image sample1_01.jpg, from the folder `orig_figures`. Available in the Supplementary Material. """ image = imread('orig_figures/dur_grain1apatite01.tif', as_grey=True) img_bin = _processed_image(image) props = regionprops(label(img_bin)) x_min, y_min, x_max, y_max = props[TEST_REGION].bbox img_orig = image[x_min:x_max, y_min:y_max] img_reg = props[TEST_REGION].image img_skel = skeletonize_3d(props[TEST_REGION].image) _, x_px = img_skel.shape x_um = _calibrate_aux(len_px=x_px) # checking if the folder 'figures' exists. if not os.path.isdir('./figures'): os.mkdir('./figures') # Figure 2(a). image_arrow = imread('misc/Fig01a.tif') _, xarr_px, _ = image_arrow.shape xarr_um = _calibrate_aux(len_px=xarr_px) fig = plt.figure(figsize=(12, 10)) host = host_subplot(111, axes_class=mpl_aa.Axes) plt.subplots_adjust(bottom=0.2) host.imshow(image_arrow, cmap='gray') host.axis['bottom', 'left'].toggle(all=False) guest = host.twiny() new_fixed_ax = guest.get_grid_helper().new_fixed_axis guest.axis['bottom'] = new_fixed_ax(loc='bottom', axes=guest, offset=(0, OFFSET)) guest.axis['top'].toggle(all=False) guest.set_xlabel('$\mu m$') guest.set_xlim(0, xarr_um) plt.savefig('figures/Fig_02a' + SAVE_FIG_FORMAT, bbox_inches='tight') plt.close() # Figure 2(b). fig = plt.figure(figsize=(12, 10)) host = host_subplot(111, axes_class=mpl_aa.Axes) plt.subplots_adjust(bottom=0.2) host.imshow(img_orig, cmap='gray') host.axis['bottom', 'left'].toggle(all=False) guest = host.twiny() new_fixed_ax = guest.get_grid_helper().new_fixed_axis guest.axis['bottom'] = new_fixed_ax(loc='bottom', axes=guest, offset=(0, OFFSET)) guest.axis['top'].toggle(all=False) guest.set_xlabel('$\mu m$') guest.set_xlim(0, x_um) plt.savefig('figures/Fig_02b' + SAVE_FIG_FORMAT, bbox_inches='tight') plt.close() # Figure 2(c). fig = plt.figure(figsize=(12, 10)) host = host_subplot(111, axes_class=mpl_aa.Axes) plt.subplots_adjust(bottom=0.2) host.imshow(img_reg, cmap='gray') host.axis['bottom', 'left'].toggle(all=False) guest = host.twiny() new_fixed_ax = guest.get_grid_helper().new_fixed_axis guest.axis['bottom'] = new_fixed_ax(loc='bottom', axes=guest, offset=(0, OFFSET)) guest.axis['top'].toggle(all=False) guest.set_xlabel('$\mu m$') guest.set_xlim(0, x_um) plt.savefig('figures/Fig_02c' + SAVE_FIG_FORMAT, bbox_inches='tight') plt.close() # Figure 2(d). fig = plt.figure(figsize=(12, 10)) host = host_subplot(111, axes_class=mpl_aa.Axes) plt.subplots_adjust(bottom=0.2) host.imshow(img_skel, cmap='gray') host.axis['bottom', 'left'].toggle(all=False) guest = host.twiny() new_fixed_ax = guest.get_grid_helper().new_fixed_axis guest.axis['bottom'] = new_fixed_ax(loc='bottom', axes=guest, offset=(0, OFFSET)) guest.axis['top'].toggle(all=False) guest.set_xlabel('$\mu m$') guest.set_xlim(0, x_um) plt.savefig('figures/Fig_02d' + SAVE_FIG_FORMAT, bbox_inches='tight') plt.close() return None
arr = re.findall(r'ion \b\d+\b,', line) test_iterations.append(int(arr[0].strip(',')[4:])) check_test = True print 'train iterations len: ', len(training_iterations) print 'train loss len: ', len(training_loss) print 'heat loss len: ', len(training_heatmap_loss) print 'fusion loss len: ', len(training_fusion_loss) print 'test loss len: ', len(test_loss) print 'test iterations len: ', len(test_iterations) f.close() # plt.plot(training_iterations, training_loss, '-', linewidth=2) # plt.show() host = host_subplot(111) #, axes_class=AA.Axes) plt.subplots_adjust(right=0.75) par1 = host.twinx() host.set_xlabel("iterations") host.set_ylabel("log loss") p1, = host.plot(training_iterations, training_loss, label="training loss") #p2, = host.plot(training_iterations,training_heatmap_loss,label= "heatmap loss") #p3, = host.plot(training_iterations,training_fusion_loss, label = "fusion loss") #p4, = host.plot(test_iterations, test_loss, label="test loss") host.legend(loc=2) host.axis["left"].label.set_color(p1.get_color())
def kippenhahn_complicated(track_obj): t = track_obj #age1 = 7.9 #age2 = 8.001 age1 = 0.8 age2 = 1 axisNum = 1 info = info_from_track_filename(track_obj.name) try: env = info['ENV'] except KeyError: env = 0.0 age = Tracks.get_stable_col(t, 'AGE') #lage = np.log10(age) lage = age / age.max() lx = Tracks.get_stable_col(t, 'LX') qh1 = Tracks.get_stable_col(t, 'QH1') qh2 = Tracks.get_stable_col(t, 'QH2') ly = Tracks.get_stable_col(t, 'LY') ycen = Tracks.get_stable_col(t, 'YCEN') qhe1 = Tracks.get_stable_col(t, 'QHE1') qhe2 = Tracks.get_stable_col(t, 'QHE2') lc = Tracks.get_stable_col(t, 'LC') qc1 = Tracks.get_stable_col(t, 'QC1') qc2 = Tracks.get_stable_col(t, 'QC2') conv = Tracks.get_stable_col(t, 'CONV') ci1 = np.abs(Tracks.get_stable_col(t, 'CI1')) cf1 = np.abs(Tracks.get_stable_col(t, 'CF1')) ci2 = np.abs(Tracks.get_stable_col(t, 'CI2')) cf2 = np.abs(Tracks.get_stable_col(t, 'CF2')) ci3 = np.abs(Tracks.get_stable_col(t, 'CI3')) cf3 = np.abs(Tracks.get_stable_col(t, 'CF3')) ci4 = np.abs(Tracks.get_stable_col(t, 'CI4')) cf4 = np.abs(Tracks.get_stable_col(t, 'CF4')) ci5 = np.abs(Tracks.get_stable_col(t, 'CI5')) cf5 = np.abs(Tracks.get_stable_col(t, 'CF5')) qdisc = Tracks.get_stable_col(t, 'QDISC') qinte = Tracks.get_stable_col(t, 'QINTE') qhel = Tracks.get_stable_col(t, 'QHEL') logL = Tracks.get_stable_col(t, 'LOG_L') logTe = Tracks.get_stable_col(t, 'LOG_TE') logrhc = Tracks.get_stable_col(t, 'LOG_RHc') logTc = Tracks.get_stable_col(t, 'LOG_Tc') logPc = Tracks.get_stable_col(t, 'LOG_Pc') he = np.nonzero(ly > 0.0)[0] heb = np.nonzero((ly > 0.0) & (ycen > 0.0))[0] heb2 = np.nonzero((ly > 0.0) & (ycen == 0))[0] cfus = np.nonzero(lc > 0.0)[0] pt1 = heb[0] pt2 = closest_match(logL[heb[pt1:]].min(), logL[heb]) pt3 = logTe[heb].argmax() # pt4 = start of He out of core? pt5 = heb2[0] ageBlueLoop = age[pt5] - age[pt1] print ageBlueLoop / age[pt1] strage = str('%.3e' % ageBlueLoop).replace('e+06', ' Myr').replace( 'e+07', '0 Myr').replace('e+08', '00 Myr') num = len(tracks) * 100 + 10 + axisNum host = host_subplot(num, axes_class=AA.Axes) plt.subplots_adjust(right=0.6) par1 = host.twinx() par2 = host.twinx() offset = 60 new_fixed_axis = par2.get_grid_helper().new_fixed_axis par2.axis["right"] = new_fixed_axis(loc="right", axes=par2, offset=(offset, 0)) par2.axis["right"].toggle(all=True) host.set_title('Mass = %.2f Env = %.2f' % (info['M'], env)) host.set_xlim(age1, age2) # age range host.set_ylim(0, 1) # m/M # host.set_xlabel("Log Age (yrs)") host.set_xlabel("per cent total lifetime") host.set_ylabel("M/Mstar") par1.set_ylabel("Log L", color='orange') par2.set_ylabel("Log T", color='purple') p1, = host.plot(lage, qh1, color='blue') p1, = host.plot(lage, qh2, color='blue', label='H fusion') p1, = host.plot(lage, qhe1, color='red') p1, = host.plot(lage, qhe2, color='red', label='He fusion') host.fill_between(lage, qhe1, qhe2, color='red', alpha=0.5) p1, = host.plot(lage, qc1, color='green') p1, = host.plot(lage, qc2, color='green', label='C+O fusion') host.fill_between(lage, qc1, qc2, color='green', alpha=0.5) host.fill_between(lage, qh1, qh2, color='blue', alpha=0.5) p1, = host.plot(lage, conv, color='grey', label='Conv zone') p1, = host.plot(lage, cf1, color='grey') p1, = host.plot(lage, qdisc, '-.', color='black', label='H discont.') p1, = host.plot(lage, qinte, '-', color='black', label='H shell base') p1, = host.plot(lage, qhel, '--', color='black', label='H depleted core') p1, = host.plot(lage, ycen, color='red', label='Y in core') host.fill_between(lage, cf1, ci1, color='grey', alpha=0.5) host.fill_between(lage, cf2, ci2, color='grey', alpha=0.5) host.fill_between(lage, cf3, ci3, color='grey', alpha=0.5) host.fill_between(lage, cf4, ci4, color='grey', alpha=0.5) host.fill_between(lage, cf5, ci5, color='grey', alpha=0.5) p2, = par1.plot(lage, logL, linewidth=3, color='orange', label='Log L') p2, = par1.plot(lage, np.log10(lx * 10**logL), '--', linewidth=3, color='orange', label='Lx') p2, = par1.plot(lage, np.log10(ly * 10**logL), '-.', linewidth=3, color='orange', label='Ly') p3, = par2.plot(lage, logTe, linewidth=3, color='purple', label='Log Te') p3, = par2.plot(lage, logTc, '--', linewidth=3, color='purple', label='Log Tc') par1.set_ylim(logL.min(), logL.max()) par2.set_ylim(logTe.min(), logTc.max()) leg = host.legend(loc=2, bbox_to_anchor=(1.3, 1)) leg._drawFrame = False host.axis["left"].label.set_color('black') par1.axis["right"].label.set_color(p2.get_color()) par2.axis["right"].label.set_color(p3.get_color()) for t in par1.get_yticklabels(): t.set_color('green') for t in par2.get_yticklabels(): t.set_color('red') plt.draw() plt.show()
def plot_4(TEMP, DEPTH, PRES, PSAL, VAR, FLU3, i): fig = plt.figure(figsize=(9, 9), dpi=1200) for x in range(0, STATION): host = host_subplot(111, axes_class=AA.Axes) plt.subplots_adjust(bottom=0.20, top=0.80) #Allow to copy y axis 3 times (this means we will have 4 different parameters on y) par1 = host.twiny( ) # instantiate a second axes that shares the same y-axis par2 = host.twiny( ) # instantiate a third axes that shares the same y-axis par3 = host.twiny( ) # instantiate a fourth axes that shares the same y-axis #Allows you to choose the location of additional axes new_fixed_axis = par2.get_grid_helper().new_fixed_axis new_fixed_axis = par3.get_grid_helper().new_fixed_axis par2.axis["top"] = new_fixed_axis(loc="top", axes=par2, offset=(0, 30)) par3.axis["bottom"] = new_fixed_axis(loc="bottom", axes=par3, offset=(0, -30)) par1.axis["top"].toggle(all=True) par2.axis["top"].toggle(all=True) par3.axis["bottom"].toggle(all=True) # Use the data that we need temp = TEMP[x, :] depth = DEPTH[x, :] pres = PRES[x, :] psal = PSAL[x, :] flu3 = FLU3[x, :] var = VAR[x, :] host.set_ylabel("Pressure, Digiquartz [db]") host.set_xlabel("Temperature [ITS-90, deg C]") par1.set_xlabel("Salinity, Pratical [PSU]") par2.set_xlabel("Fluorescence, WET Labs ECO-EFLD/FL [mg/m^3]") par3.set_xlabel('{} [{}]'.format(VAR.long_name, VAR.units)) p1, = host.plot(temp, pres) p2, = par1.plot(psal, pres) p3, = par2.plot(flu3, pres) p4, = par3.plot(var, pres) host.invert_yaxis() #put a different color for each plot host.axis["bottom"].label.set_color(p1.get_color()) par1.axis["top"].label.set_color(p2.get_color()) par2.axis["top"].label.set_color(p3.get_color()) par3.axis["bottom"].label.set_color(p4.get_color()) fig.text(0.4, 0.9, '{}, dfr300{}'.format(CM, PROFILE[x]), va='center', rotation='horizontal') #plt.title('{}, dfr300{}'.format(CM, PROFILE[x])) figname = 'dfr30{:03d}-{}.png'.format(PROFILE[x], i) dest = os.path.join(path, figname) plt.savefig(dest, format='png', dpi=1200) print('Printing: ', dest) #plt.show() plt.draw() plt.clf() plt.close(fig)
# print('rpn_loss_bbox') continue fp.close() print(len(train_iterations)) print(len(train_loss)) print(len(loss_bbox)) print(len(loss_cls)) print(len(rpn_cls_loss)) print(len(rpn_loss_bbox)) # a = input() fig = plt.figure(figsize=[8, 4]) plt.rcParams['savefig.dpi'] = 300 # plt.rcParams['figure.dpi'] = 100 # host1 = host_subplot(111) plt.subplots_adjust( right=0.8) # ajust the right boundary of the plot window #par1 = host.twinx() # set labels host1.set_xlabel("iterations") host1.set_ylabel("RPN loss") #par1.set_ylabel("validation accuracy") # plot curves p1, = host1.plot(train_iterations, train_loss, label="train RPN loss") host1.legend(loc=1) # set label color host1.axis["left"].label.set_color(p1.get_color()) host1.set_xlim([-1000, max_iter])
def transitVisibilityPlot(allData, markTransit=False, plotLegend=True, showMoonDist=True, print2file=False): """ Plot the visibility of transits. This function can conveniently be used with the output of the transitTimes function. Parameters ---------- allData : dictionary Essentially the output of `transitTimes`. A dictionary mapping consecutive numbers (one per transit) to another dictionary providing the following keys: ============ ==================================================== Key Description ------------ ---------------------------------------------------- Planet name Name of the planet Transit jd (Only if `markTransit is True) Array giving JD of start, mid-time, and end of transit. Obs jd Array specifying the HJD of the start, center and end of the observation. Obs cal Equivalent to 'Obs jd', but in the form of the calendar date. In particular, for each date, a list containing [Year, month, day, fractional hours] is given. Obs coord East longitude [deg], latitude [deg], and altitude [m] of the observatory. Star ra Right ascension of the star [deg]. Star dec Declination of the star [deg]. ============ ==================================================== .. note:: To use the list created by transitTimes, the LONGITUDE and LATITUDE of the observatory location must have been specified. markTransit : boolean, optional If True (default is False), the in-transit times will be clearly indicated in the plot. Note that this would not be the case otherwise, which is particularly important if extra off-transit time before and after the transit has been requested. showMoonDist : boolean, optional If True (default), the Moon distance will be shown. print2file : boolean, optional If True, the plot will be dumped to a png-file named: "transitVis-"[planetName].png. The default is False. """ from PyAstronomy.pyasl import _ic if not _ic.check["matplotlib"]: raise(PE.PyARequiredImport("matplotlib is not installed.", \ where="transitVisibilityPlot", \ solution="Install matplotlib (http://matplotlib.org/)")) import matplotlib import matplotlib.pylab as plt from mpl_toolkits.axes_grid1 import host_subplot from matplotlib.ticker import MultipleLocator from matplotlib.font_manager import FontProperties from matplotlib import rcParams rcParams['xtick.major.pad'] = 12 if len(allData) == 0: raise(PE.PyAValError("Input dictionary is empty", \ where="transitVisibilityPlot", \ solution=["Use `transitTimes` to generate input dictionary", "Did you forget to supply observer's location?", \ "If you used `transitTime`, you might need to change the call argument (e.g., times)"])) # Check whether all relevant data have been specified reqK = [ "Obs jd", "Obs coord", "Star ra", "Star dec", "Obs cal", "Planet name" ] if markTransit: reqK.append("Transit jd") missingK = [] for k in reqK: if not k in allData[1]: missingK.append(k) if len(missingK) > 0: raise(PE.PyAValError("The following keys are missing in the input dictionary: " + ', '.join(missingK), \ where="transitVisibilityPlot", \ solution="Did you specify observer's location in `transitTimes`?")) fig = plt.figure(figsize=(15, 10)) fig.subplots_adjust(left=0.07, right=0.8, bottom=0.15, top=0.88) ax = host_subplot(111) font0 = FontProperties() font1 = font0.copy() font0.set_family('sans-serif') font0.set_weight('light') font1.set_family('sans-serif') font1.set_weight('medium') for n in six.iterkeys(allData): # JD array jdbinsize = 1.0 / 24. / 10. jds = np.arange(allData[n]["Obs jd"][0], allData[n]["Obs jd"][2], jdbinsize) # Get JD floating point jdsub = jds - np.floor(jds[0]) # Get alt/az of object altaz = eq2hor.eq2hor(jds, np.ones(jds.size)*allData[n]["Star ra"], np.ones(jds.size)*allData[n]["Star dec"], \ lon=allData[n]["Obs coord"][0], lat=allData[n]["Obs coord"][1], \ alt=allData[n]["Obs coord"][2]) # Get alt/az of Sun sunpos_altaz = eq2hor.eq2hor(jds, np.ones(jds.size)*allData[n]["Sun ra"], np.ones(jds.size)*allData[n]["Sun dec"], \ lon=allData[n]["Obs coord"][0], lat=allData[n]["Obs coord"][1], \ alt=allData[n]["Obs coord"][2]) # Define plot label plabel = "[%02d] %02d.%02d.%4d" % (n, allData[n]["Obs cal"][0][2], \ allData[n]["Obs cal"][0][1], allData[n]["Obs cal"][0][0]) # Find periods of: day, twilight, and night day = np.where(sunpos_altaz[0] >= 0.)[0] twi = np.where( np.logical_and(sunpos_altaz[0] > -18., sunpos_altaz[0] < 0.))[0] night = np.where(sunpos_altaz[0] <= -18.)[0] if (len(day) == 0) and (len(twi) == 0) and (len(night) == 0): print() print("transitVisibilityPlot - no points to draw for date %2d.%2d.%4d" \ % (allData[n]["Obs cal"][0][2], allData[n]["Obs cal"][0][1], allData[n]["Obs cal"][0][0])) print("Skip transit and continue with next") print() continue mpos = moonpos(jds) mpha = moonphase(jds) mpos_altaz = eq2hor.eq2hor(jds, mpos[0], mpos[1], lon=allData[n]["Obs coord"][0], \ lat=allData[n]["Obs coord"][1], alt=allData[n]["Obs coord"][2]) moonind = np.where(mpos_altaz[0] > 0.)[0] if showMoonDist: mdist = getAngDist(mpos[0], mpos[1], np.ones(jds.size)*allData[n]["Star ra"], \ np.ones(jds.size)*allData[n]["Star dec"]) bindist = int((2.0 / 24.) / jdbinsize) firstbin = np.random.randint(0, bindist) for mp in range(0, int(len(jds) / bindist)): bind = int(firstbin + float(mp) * bindist) ax.text(jdsub[bind], altaz[0][bind]-1., str(int(mdist[bind]))+r"$^\circ$", ha="center", va="top", \ fontsize=8, stretch='ultra-condensed', fontproperties=font0, alpha=1.) if markTransit: # Mark points within transit. These may differ from that pertaining to the # observation if an extra offset was given to provide off-transit time. transit_only_ind = np.where( np.logical_and(jds >= allData[n]["Transit jd"][0], \ jds <= allData[n]["Transit jd"][2]) )[0] ax.plot(jdsub[transit_only_ind], altaz[0][transit_only_ind], 'g', linewidth=6, alpha=.3) if len(twi) > 1: # There are points in twilight linebreak = np.where( (jdsub[twi][1:] - jdsub[twi][:-1]) > 2.0 * jdbinsize)[0] if len(linebreak) > 0: plotrjd = np.insert(jdsub[twi], linebreak + 1, np.nan) plotdat = np.insert(altaz[0][twi], linebreak + 1, np.nan) ax.plot(plotrjd, plotdat, "-", color='#BEBEBE', linewidth=1.5) else: ax.plot(jdsub[twi], altaz[0][twi], "-", color='#BEBEBE', linewidth=1.5) ax.plot(jdsub[night], altaz[0][night], 'k', linewidth=1.5, label=plabel) ax.plot(jdsub[day], altaz[0][day], color='#FDB813', linewidth=1.5) altmax = np.argmax(altaz[0]) ax.text( jdsub[altmax], altaz[0][altmax], str(n), color="b", fontsize=14, \ fontproperties=font1, va="bottom", ha="center") if n == 29: ax.text( 1.1, 1.0-float(n)*0.04, "too many transits", ha="left", va="top", transform=ax.transAxes, \ fontsize=10, fontproperties=font0, color="r") else: ax.text( 1.1, 1.0-float(n)*0.04, plabel, ha="left", va="top", transform=ax.transAxes, \ fontsize=12, fontproperties=font0, color="b") ax.text( 1.1, 1.03, "Start of observation", ha="left", va="top", transform=ax.transAxes, \ fontsize=12, fontproperties=font0, color="b") ax.text( 1.1, 1.0, "[No.] Date", ha="left", va="top", transform=ax.transAxes, \ fontsize=12, fontproperties=font0, color="b") axrange = ax.get_xlim() ax.set_xlabel("UT [hours]") if axrange[1] - axrange[0] <= 1.0: jdhours = np.arange(0, 3, 1.0 / 24.) utchours = (np.arange(0, 72, dtype=int) + 12) % 24 else: jdhours = np.arange(0, 3, 1.0 / 12.) utchours = (np.arange(0, 72, 2, dtype=int) + 12) % 24 ax.set_xticks(jdhours) ax.set_xlim(axrange) ax.set_xticklabels(utchours, fontsize=18) # Make ax2 responsible for "top" axis and "right" axis ax2 = ax.twin() # Set upper x ticks ax2.set_xticks(jdhours) ax2.set_xticklabels(utchours, fontsize=18) ax2.set_xlabel("UT [hours]") # Horizon angle for airmass airmass_ang = np.arange(5., 90., 5.) geo_airmass = airmass.airmassPP(90. - airmass_ang) ax2.set_yticks(airmass_ang) airmassformat = [] for t in range(geo_airmass.size): airmassformat.append("%2.2f" % geo_airmass[t]) ax2.set_yticklabels(airmassformat, rotation=90) ax2.set_ylabel("Relative airmass", labelpad=32) ax2.tick_params(axis="y", pad=10, labelsize=10) plt.text(1.015,-0.04, "Plane-parallel", transform=ax.transAxes, ha='left', \ va='top', fontsize=10, rotation=90) ax22 = ax.twin() ax22.set_xticklabels([]) ax22.set_frame_on(True) ax22.patch.set_visible(False) ax22.yaxis.set_ticks_position('right') ax22.yaxis.set_label_position('right') ax22.spines['right'].set_position(('outward', 25)) ax22.spines['right'].set_color('k') ax22.spines['right'].set_visible(True) airmass2 = np.array([ airmass.airmassSpherical(90. - ang, allData[n]["Obs coord"][2]) for ang in airmass_ang ]) ax22.set_yticks(airmass_ang) airmassformat = [] for t in range(airmass2.size): airmassformat.append("%2.2f" % airmass2[t]) ax22.set_yticklabels(airmassformat, rotation=90) ax22.tick_params(axis="y", pad=10, labelsize=10) plt.text(1.045,-0.04, "Spherical+Alt", transform=ax.transAxes, ha='left', va='top', \ fontsize=10, rotation=90) ax3 = ax.twiny() ax3.set_frame_on(True) ax3.patch.set_visible(False) ax3.xaxis.set_ticks_position('bottom') ax3.xaxis.set_label_position('bottom') ax3.spines['bottom'].set_position(('outward', 50)) ax3.spines['bottom'].set_color('k') ax3.spines['bottom'].set_visible(True) ltime, ldiff = localtime.localTime( utchours, np.repeat(allData[n]["Obs coord"][0], len(utchours))) jdltime = jdhours - ldiff / 24. ax3.set_xticks(jdltime) ax3.set_xticklabels(utchours) ax3.set_xlim([axrange[0], axrange[1]]) ax3.set_xlabel("Local time [hours]") ax.yaxis.set_major_locator(MultipleLocator(15)) ax.yaxis.set_minor_locator(MultipleLocator(5)) yticks = ax.get_yticks() ytickformat = [] for t in range(yticks.size): ytickformat.append(str(int(yticks[t])) + r"$^\circ$") ax.set_yticklabels(ytickformat, fontsize=20) ax.set_ylabel("Altitude", fontsize=18) yticksminor = ax.get_yticks(minor=True) ymind = np.where(yticksminor % 15. != 0.)[0] yticksminor = yticksminor[ymind] ax.set_yticks(yticksminor, minor=True) m_ytickformat = [] for t in range(yticksminor.size): m_ytickformat.append(str(int(yticksminor[t])) + r"$^\circ$") ax.set_yticklabels(m_ytickformat, minor=True) ax.yaxis.grid(color='gray', linestyle='dashed') ax.yaxis.grid(color='gray', which="minor", linestyle='dotted') ax2.xaxis.grid(color='gray', linestyle='dotted') plt.text(0.5,0.95,"Transit visibility of "+allData[n]["Planet name"].decode("utf8"), \ transform=fig.transFigure, ha='center', va='bottom', fontsize=20) if plotLegend: line1 = matplotlib.lines.Line2D((0, 0), (1, 1), color='#FDB813', linestyle="-", linewidth=2) line2 = matplotlib.lines.Line2D((0, 0), (1, 1), color='#BEBEBE', linestyle="-", linewidth=2) line3 = matplotlib.lines.Line2D((0, 0), (1, 1), color='k', linestyle="-", linewidth=2) line4 = matplotlib.lines.Line2D((0, 0), (1, 1), color='g', linestyle="-", linewidth=6, alpha=.3) if markTransit: lgd2 = plt.legend((line1,line2,line3, line4),("day","twilight","night","transit",), \ bbox_to_anchor=(0.88, 0.15), loc=2, borderaxespad=0.,prop={'size':12}, fancybox=True) else: lgd2 = plt.legend((line1,line2,line3),("day","twilight","night",), \ bbox_to_anchor=(0.88, 0.13), loc=2, borderaxespad=0.,prop={'size':12}, fancybox=True) lgd2.get_frame().set_alpha(.5) targetco = r"Target coordinates: (%8.4f$^\circ$, %8.4f$^\circ$)" % \ (allData[n]["Star ra"], allData[n]["Star dec"]) obsco = "Obs coord.: (%8.4f$^\circ$, %8.4f$^\circ$, %4d m)" % \ (allData[n]["Obs coord"][0], allData[n]["Obs coord"][1], allData[n]["Obs coord"][2]) plt.text(0.01, 0.97, targetco, transform=fig.transFigure, ha='left', va='center', fontsize=10) plt.text(0.01, 0.95, obsco, transform=fig.transFigure, ha='left', va='center', fontsize=10) if print2file: outfile = "transVis-" + allData[n]["Planet name"].replace(" ", "") + ".png" plt.savefig(outfile, format="png", dpi=300) else: plt.show()
V2 = dataG1[2:,2] t3 = T*dataG2[2:,0] V3 = dataG2[2:,2] #### #### #### #### # Creo un grafico la dimensione è in pollici fig1 = plt.figure(figsize=(14, 5.5)) # Titolo del grafico fig1.suptitle("Divisore di frequenze", y=0.97, fontsize=15) ###### # GRAFICO 1 #f1 = fig1.add_subplot(1, 3, 1) f1 = host_subplot(311, axes_class=AA.Axes) g1 = f1.errorbar(x=t1-20, y=V1, fmt='-', c='black') g1 = f1.errorbar(x=t1, y=V1, fmt='-', c='black') g1 = f1.errorbar(x=t1+20, y=V1, fmt='-', c='black') f1.grid(True) f1.set_ylim((-0.5, 5.5)) f1.set_xlim((-12.4,12.4)) f1.text(-97, 0, u'd.d.p. [$V$]', size=14, va='center', ha='center',rotation='90') f1.set_xlabel(u'Tempo [$ms$]', labelpad=0, fontsize=14) f1.legend((g1, ), (r'$V_{gen}$', ), 'upper left', prop={'size': 13}) ######
for i in range(0, 100): xd.append(angle_between((0, 1), (-(i/10), 10-(i/10)))) print(np.power(0.25*np.pi, 2), np.power(0.5*np.pi, 2), np.power(0.75*np.pi, 2)) print(np.power(0.5*np.pi, 2) - np.power(0.25*np.pi, 2), np.power(0.75*np.pi, 2) - np.power(0.5*np.pi, 2)) print((np.power(0.5*np.pi, 2) - np.power(0.25*np.pi, 2))/np.power(0.75*np.pi, 2), (np.power(0.75*np.pi, 2) - np.power(0.5*np.pi, 2))/np.power(0.75*np.pi, 2)) print(np.power(2, 0.25*np.pi), np.power(2, 0.5*np.pi), np.power(2, 0.75*np.pi)) print(np.power(2, 0.5*np.pi) - np.power(2, 0.25*np.pi), np.power(2, 0.75*np.pi) - np.power(2, 0.5*np.pi)) print((np.power(2, 0.5*np.pi) - np.power(2, 0.25*np.pi))/np.power(2, 0.75*np.pi), (np.power(2, 0.75*np.pi) - np.power(2, 0.5*np.pi))/np.power(2, 0.75*np.pi)) print(np.power(0.25*np.pi, 0.25*np.pi), np.power(0.5*np.pi, 0.5*np.pi), np.power(0.75*np.pi, 0.75*np.pi)) print(np.power(0.5*np.pi, 0.5*np.pi) - np.power(0.25*np.pi, 0.25*np.pi), np.power(0.75*np.pi, 0.75*np.pi) - np.power(0.5*np.pi, 0.5*np.pi)) print((np.power(0.5*np.pi, 0.5*np.pi) - np.power(0.25*np.pi, 0.25*np.pi))/np.power(0.75*np.pi, 0.75*np.pi), (np.power(0.75*np.pi, 0.75*np.pi) - np.power(0.5*np.pi, 0.5*np.pi))/np.power(0.75*np.pi, 0.75*np.pi)) x = np.linspace(0, np.pi*0.8, num=100) ax = host_subplot(111, axes_class=AA.Axes) #plt.plot(x, xd) ax.plot(x, np.power(x, 2), 'r') ax.plot(x, np.power(2, x), 'b') ax.plot(x, np.power(x, x), 'g') #ax.plot(x, np.power(x*x, x), 'p') ax.axis('tight') ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis ax2.set_xticks([0., 0.25*np.pi,.5*np.pi, np.pi, 1.5*np.pi, 2*np.pi]) ax2.set_xticklabels(["$0$", r"$\frac{1}{4}\pi$", r"$\frac{1}{2}\pi$", r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"]) ax2.axis["right"].major_ticklabels.set_visible(False) ax2.axis["top"].major_ticklabels.set_visible(True) plt.show()
xhb.index = i xtk = np.arange(0, l, 5) xlb = pd.date_range('2020-01-10', periods=l+5, freq='1d') xlb = xlb.strftime('%m-%d') ii = [] for ix in xtk: ii.append(xlb.values[ix]) x = xhb.index.repeat(xhb['Confirmed']+xhb['Suspected']) bns=np.arange(-0.5,l+0.5,1) ################################# host = host_subplot(311) par = host.twinx() plt.title('New cases confirmed (Hubei)', {'fontsize':10, 'color': '#222222'}) x = xhb.index.repeat(xhb['Confirmed']) #plt.hist(x, bins=bns, rwidth=0.9, alpha=0.4, density=True, color='C8') par.bar(xhb.index, xhb['Confirmed'].values, alpha=0.6, color='#0099cc', label='Confirmed') h1 = len(x)**(-1.0/5.0) h2 = 1.06 * np.std(x) * len(x)**(-1.0/5.0) - 0.35 px = pd.Series(x) px.plot.kde(bw_method=h1, color='#0fa1d3', label='KDE (h='+str(format(h1,'.2f'))+')', linewidth=0.9, alpha=0.4) px.plot.kde(bw_method=h2, color='C2', label='KDE (h='+str(format(h2,'.2f'))+')', linewidth=0.9, alpha=0.9) host.set_ylim(ymin=0, ymax=0.2)
def plot(self, _type=Dumpsys.MEMINFO, filename=None): title = "Dumpsys" if _type == Dumpsys.FRAMESTATS: subtitle = "gfxinfo " + Dumpsys.FRAMESTATS else: subtitle = _type if _type == Dumpsys.MEMINFO: if self.ava: if DEBUG: print("plot:", file=sys.stderr) for k in list(self.ava.keys()): print(" {}: {}".format(k, self.ava[k]), file=sys.stderr) host = host_subplot(111, axes_class=AA.Axes) plt.subplots_adjust(right=0.75) par = {} for k in list(self.ava.keys()): if k != Dumpsys.TOTAL: par[k] = host.twinx() axis = 1 for k in list(self.ava.keys()): if k != Dumpsys.TOTAL and k != Dumpsys.ACTIVITIES: offset = axis * 60 axis += 1 new_fixed_axis = par[k].get_grid_helper().new_fixed_axis par[k].axis["right"] = new_fixed_axis(loc="right", axes=par[k], offset=(offset, 0)) par[k].axis["right"].toggle(all=True) if DEBUG: print("setting host x lim {} {}".format(np.amin(self.na), np.amax(self.na)), file=sys.stderr) minx = np.amin(self.na) maxx = np.amax(self.na) divx = abs(maxx - minx) / (len(self.na) * 1.0) host.set_xlim(minx - divx, maxx + divx) miny = np.amin(self.ava[Dumpsys.TOTAL]) maxy = np.amax(self.ava[Dumpsys.TOTAL]) divy = ceil(abs(maxy - miny) / (len(self.ava[Dumpsys.TOTAL]) * 1.0)) if DEBUG: print("setting host y lim {} {}".format(miny - divy, maxy + divy), file=sys.stderr) host.set_ylim(miny - divy, maxy + divy) host.set_xlabel('N') host.set_ylabel(Dumpsys.TOTAL) for k in list(self.ava.keys()): if k != Dumpsys.TOTAL: par[k].set_ylabel(k) plots = {} if DEBUG: print(" host plot {} : {}".format(self.na, self.ava[Dumpsys.TOTAL]), file=sys.stderr) plots[Dumpsys.TOTAL], = host.plot(self.na, self.ava[Dumpsys.TOTAL], label=Dumpsys.TOTAL, linewidth=2) for k in list(self.ava.keys()): if k != Dumpsys.TOTAL: if DEBUG: print(" {} plot {} : {}".format(k, self.na, self.ava[k]), file=sys.stderr) plots[k], = par[k].plot(self.na, self.ava[k], label=k, linewidth=2) for k in list(self.ava.keys()): if k != Dumpsys.TOTAL: miny = np.amin(self.ava[k]) maxy = np.amax(self.ava[k]) divy = ceil(abs(maxy - miny) / (len(self.ava[k]) * 1.0)) if DEBUG: print("setting {} y lim {}".format(k ,(miny - divy, maxy + divy)), file=sys.stderr) par[k].set_ylim(miny - divy, maxy + divy) host.legend() # host.axis["left"].label.set_color(plots[Dumpsys.TOTAL].get_color()) # for k in self.ava.keys(): # if k != Dumpsys.TOTAL: # par[k].axis["right"].label.set_color(plots[k].get_color()) elif self.va: plt.xlabel('N') plt.ylabel('V') plt.plot(self.na, self.va, label="A") else: raise RuntimeError("No values to plot") elif _type == Dumpsys.FRAMESTATS: if DEBUG: print(" plot: histogram {}".format(self.aava[Dumpsys.FRAMESTATS]), file=sys.stderr) n, bins, patches = plt.hist(self.aava[Dumpsys.FRAMESTATS]) ymax = np.amax(n) x = [] y = [] for v in range(int(ceil(ymax)) + 1): x.append(1 / 60.0 * 10 ** 3) y.append(v) plt.plot(x, y, linewidth=2, color='c') x = [] y = [] for v in range(int(ceil(ymax)) + 1): x.append(1 / 30.0 * 10 ** 3) y.append(v) plt.plot(x, y, linewidth=2, color='r') plt.xlabel('ms') plt.ylabel('Frames') plt.title(title + ' ' + subtitle) plt.grid(True) plt.draw() if filename: plt.savefig(filename) else: plt.show()
def drawWaveform(self, mode): total_chnum=len(dso.ch_list) num=dso.points_num ch_colortable=['#C0B020', '#0060FF', '#FF0080', '#00FF60'] ch=int(dso.ch_list[0][2])-1 #Get the channel of first waveform. plt.cla() plt.clf() #Due to the memory limitation of matplotlib, we must reduce the sample points. if(num==10000000): if(total_chnum>2): down_sample_factor=4 elif(total_chnum==2): down_sample_factor=4 else: down_sample_factor=1 num=num/down_sample_factor else: down_sample_factor=1 dt=dso.dt[0] #Get dt from the first opened channel. t_start=dso.hpos[0]-num*dt/2 t_end =dso.hpos[0]+num*dt/2 t = np.arange(t_start, t_end, dt) #print t_start, t_end, dt, len(t) if((len(t)-num)==1): #Avoid floating point rounding error. t=t[:-1] wave_type='-' #Set waveform type to vector. #Draw waveforms. ax=[[], [], [], []] p=[] for ch in xrange(total_chnum): if(ch==0): ax[ch]=host_subplot(111, axes_class=AA.Axes) ax[ch].set_xlabel("Time (sec)") else: ax[ch]=ax[0].twinx() ax[ch].set_ylabel("%s Units: %s" %(dso.ch_list[ch], dso.vunit[ch])) ch_color=ch_colortable[int(dso.ch_list[ch][2])-1] if(ch>1): new_fixed_axis = ax[ch].get_grid_helper().new_fixed_axis ax[ch].axis["right"] = new_fixed_axis(loc="right", axes=ax[ch], offset=(60*(ch-1), 0)) ax[ch].set_xlim(t_start, t_end) ax[ch].set_ylim(-4*dso.vdiv[ch]-dso.vpos[ch], 4*dso.vdiv[ch]-dso.vpos[ch]) #Setup vertical display range. fwave=dso.convertWaveform(ch, down_sample_factor) #print('Length=%d'%(len(fwave))) if(ch==0): try: p=ax[ch].plot(t, fwave, color=ch_color, ls=wave_type, label = dso.ch_list[ch]) except: if(mode==1): #print sys.exc_info()[0] time.sleep(5) print 'Trying to plot again!', return -1 else: try: p+=ax[ch].plot(t, fwave, color=ch_color, ls=wave_type, label = dso.ch_list[ch]) except: if(mode==1): #print sys.exc_info()[0] time.sleep(5) print 'Trying to plot again!', return -1 if(total_chnum>1): labs = [l.get_label() for l in p] plt.legend(p, labs, loc='upper right') plt.tight_layout() self.canvas.draw() del ax, t, p return 0
medias_gols_por_ano = list(map(CalcularMediaGolsPorAno, years)) print(medias_gols_por_ano) medias_gols_mandante_por_ano = list(map(CalcularMediaGolsMandanteAno, years)) media_gols_visitante_por_ano = list(map(CalcularMediaGolsVisitanteAno, years)) print(medias_gols_mandante_por_ano) qt_partidas_sem_gol = list(map(CalcularPartidasSemGol, years)) print(qt_partidas_sem_gol) qt_partidas_com_gol = list(map(CalcularPartidasComGol, years)) print(qt_partidas_com_gol) # Gráfico 1 - Média de gols por jogo anual data = {'Ano': years, 'Média': medias_gols_por_ano} tabela_final = pd.DataFrame(data=data) print(tabela_final.head(4)) graf1 = host_subplot(111) graf1.set_xlabel("Ano") graf1.set_ylabel("Média de Gols por Partida") p, = graf1.plot(years, medias_gols_por_ano, color='orange', label="Média") leg1 = plt.legend() graf1.xaxis.get_label().set_color('r') graf1.xaxis.set_major_locator(MaxNLocator(integer=True)) graf1.yaxis.get_label().set_color('c') leg1.texts[0].set_color(p.get_color()) #plt.grid(b=True, which='major', color='#666666', linestyle='-')
def plotCrossSpectral(f,ph,coh,phif): plt.figure(figsize=(14,4.5)) ## PLOT 5 plt.subplot(121) plt.grid(axis='y') plt.plot(f,coh, 'y') plt.axvspan(vspan_start,vspan_end, color='gray', alpha=0.2) plt.axvspan(0.0054,0.0056, color='gray', alpha=0.2) plt.axvspan(0.0081,0.0083, color='gray', alpha=0.2) plt.axvspan(0.0108,0.0110, color='gray', alpha=0.2) plt.xticks([(1/366),(1./(366./2)),(1./(366./3)),(1./(366./4))],[str(0.0027),str(0.0055),str(0.0082),str(0.0109)]) plt.xlim(xlim_start,xlim_end) plt.ylim(0,1.01) plt.ylabel('coherence') plt.xlabel('frequency (Hz)') plt.title('coherence x/y with repeated ts: '+str(tile_no)) ## PLOT 9 rad2time = ph/(2*np.pi*f) mtcl2time = phif/(2*np.pi*f) neg_time= np.where(rad2time<0) dur_cycl = (1/f) rad2time[neg_time] = rad2time[neg_time]+dur_cycl[neg_time] ax = host_subplot(122, axes_class=AA.Axes) p1 = plt.Rectangle((0, 0), 1, 1, fc='c', ec='c') p2, = ax.plot(f, rad2time, color='m', zorder=5, label='Phase') p3, = ax.plot(f, dur_cycl, color='gray', linestyle='-.', zorder=5, label='Period') p4, = ax.plot(f, dur_cycl/2, color='gray', linestyle='--', zorder=5, label='Halve period') ax.fill_between(f,(rad2time+mtcl2time),(rad2time-mtcl2time), where=(((rad2time+mtcl2time)<dur_cycl)), facecolor='c' ,edgecolor='c', lw=0.0 ,interpolate=True, zorder=4) ax.fill_between(f,(rad2time-mtcl2time),dur_cycl, where=(((rad2time+mtcl2time)>dur_cycl)), facecolor='c' ,edgecolor='c', lw=0.0 ,interpolate=True, zorder=4) ax.fill_between(f,(rad2time+mtcl2time)-dur_cycl, where=(((rad2time+mtcl2time)>0)), facecolor='c' ,edgecolor='c', lw=0.0 ,interpolate=True, zorder=4) ax.fill_between(f,((rad2time-mtcl2time)+dur_cycl),dur_cycl, where=((rad2time-mtcl2time)<0), facecolor='c' ,edgecolor='c', lw=0.0 ,interpolate=True, zorder=4) ax.set_xlim([xlim_start,xlim_end]) ax.set_ylim([0,365]) ax.set_xticks([(1/366),(1./(366./2)),(1./(366./3)),(1./(366./4))]) ax.set_xticklabels([str(0.0027),str(0.0055),str(0.0082),str(0.0109)]) ax.set_xlabel('frequency (Hz)') ax.set_ylabel('phase (day)') ax.set_title('t (month)', loc='left', fontsize=10) p5= plt.axvspan(vspan_start,vspan_end, color='gray', alpha=0.2, zorder=-1) plt.axvspan(0.0054,0.0056, color='gray', alpha=0.2) plt.axvspan(0.0081,0.0083, color='gray', alpha=0.2) plt.axvspan(0.0108,0.0110, color='gray', alpha=0.2) #axvspan(0.099,0.101, color='gray', alpha=0.1, zorder=0) ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis ax2.set_xlabel('phase spectrum x/y + uncertainty') ax2.set_xticks([(1/366),(1./(366./2)),(1./(366./3)),(1./(366./4))]) ax2.set_xticklabels([str(12),str(6),str(4),str(3)]) ax2.axis["right"].major_ticklabels.set_visible(False) ax2.xaxis.label.set_size(2) lg = plt.legend([p3,p4], ['single period','halve period'], ncol=1) lg.get_frame().set_ec('lightgray') lg.get_frame().set_lw(0.5) plt.grid(axis='y', zorder=0 ) plt.gcf().tight_layout() #plt.savefig(r'C:\Users\lenovo\Documents\HOME//nodetrending_2007_Wet_nohants.png', dpi=400) # frequency index #f_lb = 0.0054 # vspan_start #f_ub = 0.0056 # vspan_end #f_ix = np.where((f > f_lb) * (f < f_ub))[0] #p_r2t = np.mean(rad2time[f_ix], -1) #p_ph = np.mean(ph[f_ix], -1) #print ('phase in radian is', round(p_ph,2)) #print ('which correspond to', round(p_r2t,2), 'day') #plt.savefig(r'C:\Users\lenovo\Documents\HOME\2015-02-05_pics4progress//nodetrending_2006_Wet_nohants.png', dpi=400) plt.show() plt.close()
def plot_relevant_correlations(s, threshold=0.5, mask=None, alpha=0.2, cmap='plasma'): sns.set_context('paper') bss_load_arr = s.get_bss_loadings().split() nmf_load_arr = s.get_decomposition_loadings().split() bss_factor_arr = s.get_bss_factors().split() nmf_factor_arr = s.get_decomposition_factors().split() no_of_nmf = len(nmf_load_arr) no_of_bss = len(bss_load_arr) (xvals, yvals, En) = get_hs_axes(s) X, Y = np.meshgrid(xvals, yvals) for jj in range(0, no_of_bss): y_factor = bss_factor_arr[jj] y_load = bss_load_arr[jj] for kk in range(0, no_of_nmf): x_factor = nmf_factor_arr[kk] x_load = nmf_load_arr[kk] x_data = x_load.data.flatten() y_data = y_load.data.flatten() (rsq, pval) = sp.stats.spearmanr(y_data, b=x_data) if rsq >= threshold: print('BSS %d vs NMF %d R^2 = %0.2f' % (jj, kk, rsq)) f_h = plt.figure() axScatter = plt.subplot(231) if mask is None: plt.scatter(x_data, y_data, cmap=cmap, alpha=alpha, edgecolor='white') else: plt.scatter(x_data, y_data, c=mask.flatten(), alpha=alpha, cmap=cmap, edgecolor='white') axScatter.set_aspect((x_data.max() - x_data.min()) / (y_data.max() - y_data.min())) axScatter.set_title('R$^2$= %0.2f' % rsq) axScatter.set_xlabel('NMF ' + str(kk)) axScatter.set_ylabel('BSS ' + str(jj)) axNMFmesh = plt.subplot(232) img = axNMFmesh.pcolormesh(X, Y, x_load.data, cmap='plasma') axNMFmesh.set_title('NMF ' + str(kk)) axNMFmesh.set_xlabel('$\mu$m') axNMFmesh.set_ylabel('$\mu$m') axNMFmesh.axis('equal') colorbar(img, orientation='horizontal', position='bottom') axBSSmesh = plt.subplot(233) img = axBSSmesh.pcolormesh(X, Y, y_load.data, cmap='plasma') axBSSmesh.set_title('BSS ' + str(jj)) axBSSmesh.set_xlabel('$\mu$m') axBSSmesh.set_ylabel('$\mu$m') axBSSmesh.axis('equal') colorbar(img, orientation='horizontal', position='bottom') axplot = host_subplot(212) axplot.plot(En, x_factor.data, label='NMF ' + str(kk)) axplot.ticklabel_format(axis='y', style='sci', scilimits=(0, 0)) axplot.set_ylabel('NMF ' + str(kk)) axplot2 = axplot.twinx() axplot2.plot(En, y_factor.data, label='BSS ' + str(jj)) axplot2.ticklabel_format(axis='y', style='sci', scilimits=(0, 0)) axplot2.set_ylabel('BSS ' + str(jj)) axplot.legend() axplot.set_xlabel('$E$ (eV)') plt.tight_layout(h_pad=1) sns.set_context('notebook')
def main(): connection = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server=akl-longage3\LONGAGE3;" "Database=LTMAL3;" "UID=RAKON\nikolai;" "Trusted_Connection=yes;") unit_name = 'test1' freq_nom = 26 register_matplotlib_converters() # if all_units: # command = "select * from locData join brdData on locData.fk_brdID = brdData.pk_brdID join runData on runData.pk_runID = locData.fk_runID where runData.currentRun = 'True' and runData.finishDate < CURRENT_TIMESTAMP" # elif crystalType == '': # if moustrap: # command = "select * from locData join brdData on locData.fk_brdID = brdData.pk_brdID join runData on runData.pk_runID = locData.fk_runID where runData.currentRun = 'True' and runData.finishDate < CURRENT_TIMESTAMP and runData.oscillator = 'Mousetrap'" # else: # command = "select * from locData join brdData on locData.fk_brdID = brdData.pk_brdID join runData on runData.pk_runID = locData.fk_runID where runData.currentRun = 'True' and runData.finishDate < CURRENT_TIMESTAMP and runData.oscillator <> 'Mousetrap'" # else: # if moustrap: # command = "select * from locData join brdData on locData.fk_brdID = brdData.pk_brdID join runData on runData.pk_runID = locData.fk_runID where runData.currentRun = 'True' and runData.finishDate < CURRENT_TIMESTAMP and runData.oscillator = 'Mousetrap' and runData.crystalType = " + crystalType # else: # command = "select * from locData join brdData on locData.fk_brdID = brdData.pk_brdID join runData on runData.pk_runID = locData.fk_runID where runData.currentRun = 'True' and runData.finishDate < CURRENT_TIMESTAMP and runData.oscillator <> 'Mousetrap' and runData.crystalType = " + crystalType command = "select * from measData where measData.fk_locID = '5A09D288-6325-431E-9664-ED7CA5A44FAE' and measData.frq <> '9999'" df = pd.read_sql(command, connection) # ********************************************************** # print(df) # sys.exit() # ********************************************************** freq_nom_hz = freq_nom * 1000000 df.sort_values(['measDate'], ascending=[True], inplace=True) df_freq = df['frq'] df_freq_ppm = 1000000 * (df_freq - freq_nom_hz) / freq_nom_hz df['frq_ppm'] = df_freq_ppm # gaussian filter df_filtered = ndimage.gaussian_filter(df_freq, sigma=25, order=0) df['frq_flt'] = df_filtered df_freq_ppm_filtered = 1000000 * (df_filtered - freq_nom_hz) / freq_nom_hz df['frq_ppm_filtered'] = df_freq_ppm_filtered result = df # df = df.drop(columns=[ # 'pk_locID', # 'fk_runID', # 'fk_brdID', # 'fk_ovenID', # 'pk_brdID', # 'status', # 'vchar', # 'pk_runID', # 'ppmStartDate', # 'operator', # 'limUpper', # 'limLower', # 'email', # 'emailSent', # 'emailNoteTime', # 'opemail', # 'sendemail', # 'sendopemail', # 'prodMonitoring', # 'standardProduction', # 'limUpper1', # 'limLower1', # 'hotStore', # 'processExperiment', # 'designExperiment', # 'returnUnits', # 'freqDivider', # 'rma', # 'currentRun', # 'sealingMethod', # 'glue' # ]) # df['startDate'] = df['startDate'].dt.date # df['finishDate'] = df['finishDate'].dt.date # # df.replace(to_replace='oven320', value='') # df = df.set_index('runNumber') # df['nomFrq'] = df['nomFrq']/1000000 # df['nomFrq'] = round(df['nomFrq'],2) # df.sort_values(['runNumber', 'brd', 'loc'], ascending=[True, True, True], inplace=True) # # df['amount'] = df.groupby(['runNumber'])['brd'].count() # # df['locs'] = df.groupby(['runNumber'])['brd'].prod() # df['locs'] = df['loc'].astype(str) # df1 = df.groupby(['runNumber'])['locs'].apply(','.join).reset_index() # # df1['board'] = df['brd'] # df1 = df1.set_index('runNumber') # df = df.drop(columns=['loc', 'locs']) # df1['nbr'] = df.groupby(['runNumber'])['brd'].count() # # print(df) # result = pd.concat([df1, df], axis=1, join='inner') # result = result.drop_duplicates() # result.sort_values(['brd', 'runNumber'], ascending=[True, True], inplace=True) # # ****************************** # result = result.set_index('brd') # df = df.drop(columns=['runNumber']) # ****************************** # filename = filename.replace('.csv', '') + '_filtered.csv' path = r"\\rakdata2\Share\Nikolai\serial\sql_results\\" filename = path + 'result.csv' result.to_csv(filename, encoding='utf-8') figFvI = plt.figure(figsize=(16, 10)) fviHost = host_subplot(111) plt.subplots_adjust(right=1) # Was 0.5 plotTitle = "\nAgeing data " + str(unit_name) fviHost.set_title(plotTitle) fviHost.set_xlabel('Time, ', color='r') fviHost.set_ylabel('Frequency, ppm', color='b') fviHost.tick_params(axis='y', colors='b') fviHost.tick_params(axis='x', colors='r') fviHost.plot(df['measDate'], df['frq_ppm'], color='b', alpha=1, label="Residual", linewidth=.5) # fviHost.plot(df_raw['Offset Frequency (Hz)'], df_raw['PN_FLT'], color='b', alpha = 0.5, label = "Residual", linewidth=1) # fviHost.set_xscale('log') # Show the major grid lines with dark grey lines fviHost.grid(b=True, which='major', color='#666666', linestyle='-', alpha=0.5) # Show the minor grid lines with very faint and almost transparent grey lines fviHost.minorticks_on() fviHost.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2) # save_plot = path + r'\\results//' + str(unit_name) + '.png' save_plot = path + r'//' + str(unit_name) + '.png' figFvI.savefig(save_plot, bbox_inches='tight') plt.close(figFvI) figFvIF = plt.figure(figsize=(16, 10)) fviHostF = host_subplot(111) plt.subplots_adjust(right=1) # Was 0.5 plotTitle = "\nAgeing data " + str(unit_name) + " (smoothed)" fviHostF.set_title(plotTitle) fviHostF.set_xlabel('Time, ', color='r') fviHostF.set_ylabel('Frequency, ppm', color='b') fviHostF.tick_params(axis='y', colors='b') fviHostF.tick_params(axis='x', colors='r') fviHostF.plot(df['measDate'], df['frq_ppm_filtered'], color='b', alpha=1, label="Residual", linewidth=1) # fviHost.plot(df_raw['Offset Frequency (Hz)'], df_raw['PN_FLT'], color='b', alpha = 0.5, label = "Residual", linewidth=1) # fviHostF.set_xscale('log') # xfmt = mdates.DateFormatter('%d-%m-%y %H:%M') # fviHostF.xaxis.set_major_formatter(xfmt) # Show the major grid lines with dark grey lines fviHostF.grid(b=True, which='major', color='#666666', linestyle='-', alpha=0.5) # Show the minor grid lines with very faint and almost transparent grey lines fviHostF.minorticks_on() fviHostF.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2) # save_plot = path + r'\\results//' + str(unit_name) + '.png' save_plot = path + r'//' + str(unit_name) + '_smoothed.png' figFvIF.savefig(save_plot, bbox_inches='tight') plt.close(figFvIF) msg_finish = Tk() msg_finish.withdraw() msg_finish = messagebox.showinfo("Done", "Results are in: " + filename) sys.exit()
def giveDataPlotTimeLineTwoRange(figPath='fig/time.png', timeLine=[], dataOne=[], labelOne="", dotOne='o', yLimOne=3500, dataTwo=[], labelTwo="", dotTwo='o', yLimTwo=100): #fig = plt.figure() #view1 = fig.add_subplot(111, axes_class=AA.Axes) view1 = host_subplot(111, axes_class=AA.Axes) view1.spines['top'].set_visible(False) view2 = view1.twinx() #view3 = view1.twinx() plt.subplots_adjust(right=0.75) # plt.spines['top'].set_visible(False) view1.set_ylim(0, yLimOne) view1.set_ylabel( 'Number of all articles for climate change coverage only') view1.set_xlabel('Year') view1.plot(timeLine, dataOne, markersize=3, marker=dotOne, label=labelOne) #view1.scatter(timeLine, dataOne, label=labelOne) for y, h in zip(timeLine, dataOne): view1.text(y, h + 0.005, '%d' % h, ha='center', va='bottom', fontsize=9) view2.set_ylim(0, yLimTwo) view2.set_ylabel( 'Number of all articles for health and climate change converage both' ) view2.plot(timeLine, dataTwo, 'r', markersize=3, marker=dotTwo, label=labelTwo) #view2.spines['top'].set_visible(False) ny2 = view2.get_grid_helper().new_fixed_axis view2.axis['right'] = ny2(loc='right', axes=view2, offset=(0, 0)) view2.axis['right'].toggle(all=True) for y, h in zip(timeLine, dataTwo): view2.text(y, h + 0.005, '%d' % h, ha='center', va='bottom', fontsize=9) #plt.legend(loc=4) # ny3=view3.get_grid_helper().new_fixed_axis # view3.axis['right'] = ny3(loc='right', axes=view3,offset=(50, 0)) # view3.axis['right'].toggle(all=True) # view3.plot(timeLine, dataThree, 'r', marker='x', label='People\'s Daily (health and climate change coverage after manually check)') # view3.set_ylim(0,50) # view3.set_ylabel('Number of all articles for health and climate change coverage both after manually check') # for y, h in zip(timeLine, dataThree): # view3.text(y, h + 0.005, '%d' % h, ha='center', va='bottom', fontsize=9) plt.legend(loc=1, frameon=False) # plt.xlabel('Year') # plt.ylabel('Number of all articles') plt.show()
def plot_visit(self, show_peaks=False, show_areas=True, show_ID=False): """ Plot the given **Visit** curve. Parameters ---------- show_peaks : bool Flag set to True if maximum and minimum peak must be displayed. show_areas : bool Flag set to True to show the calculation of the areas in the title show_ID : bool Flag set to True to show the ID of the visit(s) """ if self.len_CH4 == self.len_CO2: x_CH4 = np.arange( 0, self.len_CH4 * NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES, NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES).tolist() x_CO2 = np.arange( 0, self.len_CO2 * NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES, NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES).tolist() x_CH4CO2 = np.arange( 0, self.len_CH4 * NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES, NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES).tolist() elif self.len_CO2 > self.len_CH4: start_time = (self.len_CO2 - self.len_CH4) * NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES x_CH4 = np.arange( start_time, self.len_CO2 * NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES, NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES).tolist() x_CO2 = np.arange( 0, self.len_CO2 * NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES, NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES).tolist() x_CH4CO2 = np.arange( start_time, self.len_CO2 * NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES, NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES).tolist() else: # self.len_CO2 < self.len_CH4 start_time = (self.len_CH4 - self.len_CO2) * NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES x_CH4 = np.arange( 0, self.len_CH4 * NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES, NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES).tolist() x_CO2 = np.arange( start_time, self.len_CH4 * NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES, NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES).tolist() x_CH4CO2 = np.arange( start_time, self.len_CH4 * NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES, NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES).tolist() axCO2 = host_subplot(111, axes_class=AA.Axes) plt.subplots_adjust(right=0.75) axCO2.autoscale() axCH4 = axCO2.twinx() axCH4CO2 = axCO2.twinx() new_fixed_axisCH4 = axCH4.get_grid_helper().new_fixed_axis axCH4.axis["right"] = new_fixed_axisCH4(loc="right", axes=axCH4, offset=(0, 0)) new_fixed_axisCH4CO2 = axCH4CO2.get_grid_helper().new_fixed_axis axCH4CO2.axis["right"] = new_fixed_axisCH4CO2(loc="right", axes=axCH4CO2, offset=(50, 0)) p1, = axCO2.plot(x_CO2, self.y_CO2, 'r-', label="CO2") p2, = axCH4.plot(x_CH4, self.y_CH4, 'b-', label="CH4") p3, = axCH4CO2.plot(x_CH4CO2, self.y_CH4_CO2, 'g-', label="CH4/CO2") axCO2.set_xlabel('Seconds') axCO2.set_ylabel("CO2") axCH4.set_ylabel("CH4") axCH4CO2.set_ylabel("CH4/CO2") axCO2.yaxis.label.set_color(p1.get_color()) axCH4.yaxis.label.set_color(p2.get_color()) axCH4CO2.yaxis.label.set_color(p3.get_color()) if show_peaks == True: # Compute abscissa and ordinate for maximum CO2 peak values max_abs_CO2 = [i[0] for i in self.max_pk_CO2] max_ord_CO2 = [i[1] for i in self.max_pk_CO2] # Compute abscissa and ordinate for minimum CO2 peak values min_abs_CO2 = [i[0] for i in self.min_pk_CO2] min_ord_CO2 = [i[1] for i in self.min_pk_CO2] # Compute abscissa and ordinate for maximum CH4 peak values max_abs_CH4 = [i[0] for i in self.max_pk_CH4] max_ord_CH4 = [i[1] for i in self.max_pk_CH4] # Compute abscissa and ordinate for minimum CH4 peak values min_abs_CH4 = [i[0] for i in self.min_pk_CH4] min_ord_CH4 = [i[1] for i in self.min_pk_CH4] # Compute abscissa and ordinate for maximum CH4 peak values max_abs_CH4_CO2 = [i[0] for i in self.max_pk_CH4_CO2] max_ord_CH4_CO2 = [i[1] for i in self.max_pk_CH4_CO2] # Compute abscissa and ordinate for minimum CH4 peak values min_abs_CH4_CO2 = [i[0] for i in self.min_pk_CH4_CO2] min_ord_CH4_CO2 = [i[1] for i in self.min_pk_CH4_CO2] # Plot maximum CO2 peak values axCO2.plot(max_abs_CO2, max_ord_CO2, 'ro') axCO2.plot(min_abs_CO2, min_ord_CO2, 'rx') # Plot maximum CH4 peak values axCH4.plot(max_abs_CH4, max_ord_CH4, 'bo') axCH4.plot(min_abs_CH4, min_ord_CH4, 'bx') # Plot maximum CH4/CO2 peak values axCH4CO2.plot(max_abs_CH4_CO2, max_ord_CH4_CO2, 'go') axCH4CO2.plot(min_abs_CH4_CO2, min_ord_CH4_CO2, 'gx') if show_areas: plt.title("Areas : CO2 : %.3f CH4 : %.3f CH4/CO2 : %.3f" % (self.area_CO2, self.area_CH4, self.area_CH4_CO2)) if show_ID: x_pos = x[len(x) / 2] y_pos = axCO2.get_ylim() # [bottom, top] y_pos = y_pos[0] + 0.97 * (y_pos[1] - y_pos[0] ) # set the text at 97 % of the height axCO2.text(x_pos, y_pos, self.ID[0], ha="center", va="center", size=8) #plt.subplots_adjust(left=0.03,bottom=0.05, right=0.92,top=0.96) # used to export the graphs in PNG on a big screen (24") plt.draw() plt.show()
from mpl_toolkits.axes_grid1 import host_subplot import matplotlib.pyplot as plt import os fig1 = plt.figure('houhou') host = host_subplot(111) par = host.twinx() host.set_xlabel("Distance") host.set_ylabel("Density") par.set_ylabel("Temperature") fig2 = plt.figure('houhou is sorry') host2 = host_subplot(111) par2 = host2.twinx() host2.set_xlabel("Distance2") host2.set_ylabel("Density2") par2.set_ylabel("Temperature2") p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density") p2, = par.plot([0, 1, 2], [0, 3, 2], label="Temperature") p11, = host2.plot([0, 1, 2], [1, 10, 2], label="Density2") p21, = par2.plot([0, 1, 2], [9, 3, 2], label="Temperature2") host.spines['top'].set_visible(False) host.yaxis.set_ticks_position('left') host.xaxis.set_ticks_position('bottom')
def mock_visit(self, nbr_to_plot): """ Method used to show multiple visits in one plot. Just used to set the parameters (as minimums, maximums, times, etc.) Parameters ---------- nbr_to_plot : int Number of visits to plot (the nth first visits) Returns ------- A plot of the nbr_to_plot first visits. With some vertical separators between the visits and the ID and scale of each visit. """ if (nbr_to_plot > len(self.visits)): nbr_to_plot = len(self.visits) prev_row = {'ID': '0'} data_to_plot = [] #list of the indexes of the "change ID" of a visit for index, row in self.df.iterrows(): #print row['ID'] if row['ID'] != prev_row['ID']: # change of animal data_to_plot.append(index) prev_row = row prev = 0 # prev index for i in data_to_plot: if ( i - prev ) >= MIN_VISIT_DURATION / NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES: # check if the visit is long enough self.mock_visits.append( Visit(self.df.iloc[prev:i] )) # select only the nbr_to _plot first visits nbr_to_plot -= 1 if nbr_to_plot <= 0: break prev = i labels = [ ] # contain the label of each visit to show on the graphe (ID + scale) limits = [] # The limit of each visit (in samples) y_CO2 = list() # All the data of the CO2 curve (the nth first visits) y_CH4 = list() # All the data of the CH4 curve (the nth first visits) for visit in self.mock_visits: y_CO2.extend(visit.data.CO2.tolist()) y_CH4.extend(visit.data.CH4.tolist()) labels.append(visit.data.ID.unique()[0] + " " + visit.data.scale.unique()[0]) limits.append(len(visit.data.CO2.tolist())) y_CH4_CO2 = [x / y for x, y in zip(y_CH4, y_CO2)] x = np.arange(0, len(y_CO2) * NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES, NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES).tolist() axCO2 = host_subplot(111, axes_class=AA.Axes) plt.subplots_adjust(right=0.75) axCO2.autoscale() axCH4 = axCO2.twinx() axCH4CO2 = axCO2.twinx() new_fixed_axisCH4 = axCH4.get_grid_helper().new_fixed_axis axCH4.axis["right"] = new_fixed_axisCH4(loc="right", axes=axCH4, offset=(0, 0)) new_fixed_axisCH4CO2 = axCH4CO2.get_grid_helper().new_fixed_axis axCH4CO2.axis["right"] = new_fixed_axisCH4CO2(loc="right", axes=axCH4CO2, offset=(50, 0)) p1, = axCO2.plot(x, y_CO2, 'r-', label="CO2") p2, = axCH4.plot(x, y_CH4, 'b-', label="CH4") p3, = axCH4CO2.plot(x, y_CH4_CO2, 'g-', label="CH4/CO2") axCO2.set_xlabel('Seconds') axCO2.set_ylabel("CO2") axCH4.set_ylabel("CH4") axCH4CO2.set_ylabel("CH4/CO2") axCO2.yaxis.label.set_color(p1.get_color()) axCH4.yaxis.label.set_color(p2.get_color()) axCH4CO2.yaxis.label.set_color(p3.get_color()) curr_time = 0 y_pos = axCO2.get_ylim() # [bottom, top] y_pos = y_pos[0] + 0.93 * (y_pos[1] - y_pos[0] ) # set the text at 93 % of the height for i in range(len(limits)): curr_time += limits[i] * NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES plt.axvline(x=curr_time, linewidth=0.5, color='#555555') axCO2.text(curr_time - 50, y_pos, labels[i], ha="right", va="center", size=8, rotation=90) areaCO2 = np.trapz(y_CO2, dx=NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES) areaCH4 = np.trapz(y_CH4, dx=NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES) areaCH4_CO2 = np.trapz(y_CH4_CO2, dx=NBR_OF_SECONDS_BETWEEN_TWO_SAMPLES) plt.title("Areas : CO2 : %.3f CH4 : %.3f CH4/CO2 : %.3f" % (areaCO2, areaCH4, areaCH4_CO2)) plt.subplots_adjust( left=0.03, bottom=0.05, right=0.92, top=0.96) # used to export the graphs in PNG on a big screen (24") plt.draw() plt.show()
def main(): root = Tk() root.fileName = filedialog.askopenfilename( filetypes=(("Text File", "*.txt"), ("Comma Separated", "*.csv"), ("All Files", "*.*"))) logFile = root.fileName root.quit() root.destroy() #close out the Tk interface from the file opening prompt with open(logFile) as f: loggedData = f.readlines() lineData = [] #get rid of \n and create a list for each set of values loggedData = [i.split('\n') for i in loggedData] i = 1 latitude = [] longitude = [] plotLink = { } #dictionary to link the mouse position in the lower plot to a dot on the GPS plot #this while loop only parses out and converts RPM. Reuse this to do it for everything else while i < len(loggedData): dataPoint = loggedData[i][0] #String of the data point dataPoint = dataPoint.split( ',') #creates a list separating different types of data gpsPoint = dataPoint[0] #get the GPS coordinate from the data point rpmDataItem = (dataPoint[-2]) rpmDataItem = rpmDataItem.replace( " ", "") #eliminate whitespace from the string plotLink[i] = (gpsPoint + ", " + rpmDataItem ) #add the GPS and RPM to the dictionary #RPM separation if rpmDataItem == "": rawRPMData = 0 else: rawRPMData = int(rpmDataItem) rpm.append(rawRPMData) #Throttle Position throttleDataItem = (dataPoint[-1]) throttleDataItem = throttleDataItem.replace( " ", "") #eliminate whitespace, just in case if throttleDataItem == "": rawThrottleData = 0 else: rawThrottleData = int(throttleDataItem) throttlePos.append(rawThrottleData) #End Throttle position #Lean Angle leanAngleItem = (dataPoint[-3]) leanAngleItem = leanAngleItem.replace(" ", "") if leanAngleItem == "": rawLeanAngle = 0 else: rawLeanAngle = float(leanAngleItem) leanAngle.append(rawLeanAngle) #END lean angle #Speed speedItem = (dataPoint[-4]) speedItem = speedItem.replace(" ", "") if speedItem == "": rawSpeed = 0 else: rawSpeed = float(speedItem) speed.append(rawSpeed) #END Speed i = i + 1 #cartesian x/y = (degrees + minutes/60) #gpxLat and gpxLong are used for output to the GPX file - xList and yList are used for plotting the route gpxLat, gpxLong, xList, yList = toCartesian(plotLink) #make a dictionary of points to use for the dot on the GPS plot gpsDots = {} i = 0 while i < len(gpxLat): gpsDots[i] = gpxLat[i], gpxLong[i] i = i + 1 #----------------------------------------- # - # START PLOTTING - # - #----------------------------------------- #Small function to make it easier to clear the GPS plot of red dots #This function simply creates the GPS plot def gpsPlot(): plt.subplot( 211 ) #create a 2 row by 1 column set of subplots (this is the first subplot) originalGPSPlot = plt.plot(xList, yList) plt.axis('off') #turn off axes for the GPS plot fig = plt.figure() plt.figure(1) #plot the GPS gpsPlot() #Set up axes variables host = host_subplot(212, axes_class=AA.Axes) #RPM ax2 = host.twinx() #Throttle Position ax3 = host.twinx() #Lean Angle ax4 = host.twinx() #Speed (MPH) offset = 60 #offset beween axes new_fixed_axis = host.get_grid_helper().new_fixed_axis host.axis['left'] = new_fixed_axis(loc='left', axes=host, offset=(0, 0)) ax2.axis['right'] = new_fixed_axis(loc='right', axes=ax2, offset=(0, 0)) ax3.axis['left'] = new_fixed_axis(loc='left', axes=ax3, offset=(-offset, 0)) ax4.axis['right'] = new_fixed_axis(loc='right', axes=ax4, offset=(offset, 0)) #not sure this block does anything at all host.axis['left'].toggle(all=True) ax2.axis['right'].toggle(all=True) ax3.axis['left'].toggle(all=True) ax4.axis['right'].toggle(all=True) host.set_xlabel('Time') host.set_ylabel('RPM', color='blue') ax2.set_ylabel('Throttle', color='green') ax3.set_ylabel('Lean Angle', color='orange') ax4.set_ylabel('Speed (MPH)', color='red') #not using these tuples right now, just plot the stuff hostTicks, = host.plot(rpm, color='blue', label='RPM') ax2Ticks, = ax2.plot(throttlePos, color='green', label='Throttle Position') ax3Ticks, = ax3.plot(leanAngle, color='orange', label='Lean Angle') ax4Ticks, = ax4.plot(speed, color='red', label='Speed (MPH)') #Turn off all axis stuff for the lean angle on the right #without this the lean angle y axis would be duplicated and overlap the #throttle on the right side ax3.axis['right'].toggle(all=False) fig.subplots_adjust(hspace=.5) #spacing between the plots ax = plt.gca() #get the current axes plt.xlim(0, 500) #limit the x axis to 500 data points at a time fig.suptitle( "Use the 'Pan Axes' button to move the data plot left and right. " + "Hold the 'X' key while scrolling horizontally", fontweight='bold') #------------------------------------------------- # EVENT HANDLING STUFF - For mouse movement #------------------------------------------------- class Cursor: def __init__(self, ax): self.ax = ax self.lx = ax.axhline(color='k') # the horiz line self.ly = ax.axvline(color='k') # the vert line # text location in axes coords self.txt = ax.text(0.7, 0.9, '', transform=ax.transAxes) def mouse_move(self, event): if not event.inaxes: return #establish use of the GPS plot again or dots will draw on the 'GPS to file' button plt.subplot(211).clear() gpsPlot() if event.xdata != None and (event.xdata >= 0 and event.xdata <= len(xList)): x, y = event.xdata, event.ydata mouseX = int(event.xdata) # update the line positions self.lx.set_ydata(y) self.ly.set_xdata(x) plt.plot(xList[mouseX], yList[mouseX], 'ro', linewidth=1) #GPS Dot plt.draw() #NEW CURSOR EVENTS cursor = Cursor(ax) fig.canvas.mpl_connect('motion_notify_event', cursor.mouse_move) #Building KML File class Kml: def toKML(self, event): #print("TO KML") XMLVER = ET.Element('?xml version="1.0" encoding="UTF-8"?') ROOT = ET.Element('gpx') ROOT.set('version', '1.0') TRACK = ET.SubElement(ROOT, 'trk') NAME = ET.SubElement(TRACK, 'name') NAME.text = 'GPX Track' TRACKSEG = ET.SubElement(TRACK, 'trkseg') for item in gpsDots: TRACKPOINT = ET.SubElement(TRACKSEG, 'trkpt') TRACKPOINT.set('lat', str(gpsDots[item][0])) TRACKPOINT.set('lon', str(gpsDots[item][1])) tree = ET.ElementTree(ROOT) tree.write("UNIQUEname.gpx") btn = plt.axes([0.5, 0.5, 0.1, 0.075 ]) #place the button roughly in the middle of the screen callback = Kml() toKMLButton = Button(btn, "GPS to GPX File") toKMLButton.on_clicked(callback.toKML) ax.format_coord = format_coord fig.canvas.set_window_title("Vehicle Data Viewer") #title of window #maximize the window on startup figMgr = plt.get_current_fig_manager() figMgr.window.state('zoomed') plt.show()