def getMFigure(self,nodeBc,measureName,measureShorthand): #sort bc by mean names=nodeBc.keys() meanNodeBc={} for name in names: meanNodeBc[name]=pylab.mean(nodeBc[name]) names.sort(key=lambda x:meanNodeBc[x],reverse=True) data=[] for name in names: data.append(nodeBc[name]) #top 5 distributions nTop=5 fig=pylab.Figure(figsize=(5,8), dpi=80) fig.subplots_adjust(bottom=0.08,right=0.95,top=0.95) for nodeIndex in range(nTop): axes=fig.add_subplot(nTop,1,nodeIndex+1) axes.hist(data[nodeIndex],100) axes.set_ylabel(names[nodeIndex],fontsize=8) for tick in axes.get_yticklabels(): tick.set_fontsize(10) tick.set_fontname("Times") if nodeIndex==0: axes.set_title("Distribution of "+measureShorthand+"s for top "+str(nTop)+" locations") axes.set_xlabel(measureName) return fig
def __init__(self, data, x, y, slice_idx, cmap=P.cm.gray, norm=None, interpolation="bilinear", extent=None): self.norm = norm self.cmap = cmap self.interpolation = interpolation self.slice_idx = slice_idx # extent should be static, so set it and leave it alone if not extent: y, x = data.shape[-2:] extent = [-x / 2., x / 2., -y / 2., y / 2.] self.extent = extent self.ylim = tuple(extent[2:]) self.xlim = tuple(extent[:2]) fig = P.Figure(figsize=P.figaspect(data), dpi=80) ax = fig.add_subplot(111) ax.yaxis.tick_right() ax.title.set_y(1.05) FigureCanvas.__init__(self, fig) self.setData(data) self._init_crosshairs(x, y)
def __init__(self, parent, latex_installed, proj_3d=False): self.myWidget = parent plot_background = myConfig.read("Plotting", "plot_background") plot_CanvasBackground = str(myConfig.read("Plotting", "plot_CanvasBackground")) plot_fontSize = int(myConfig.read("Plotting", "plot_fontSize")) plot_topOfPlot = float(myConfig.read("Plotting", "plot_topOfPlot")) plot_leftOfPlot = 0.12#float(myConfig.read("Plotting", "plot_leftOfPlot")) plot_rightOfPlot = float(myConfig.read("Plotting", "plot_rightOfPlot")) plot_bottomOfPlot = 0.1#float(myConfig.read("Plotting", "plot_bottomOfPlot")) self.fig = pl.Figure(facecolor=plot_background) pl.matplotlib.rc('font', size=plot_fontSize) # Check if LaTeX and dvipng are installed on this system since this # is required by matplotlib for fine rendering. If it is not installed # only basic rendering will be done in the following rc('text', usetex=latex_installed) # ALIASING # TODO: read aliasing variables: # pl.matplotlib.rc('lines', antialiased=False) # pl.matplotlib.rc('text', antialiased=False) # pl.matplotlib.rc('patch', antialiased=False) self.axes = self.fig.add_subplot(111, projection="3d" if proj_3d else None) # Matplotlib 2.0 vs. 1.5 behavior... try: self.axes.set_facecolor(plot_CanvasBackground) # Matplotlib >= 2 except AttributeError: self.axes.set_axis_bgcolor(plot_CanvasBackground) # Matplotlib < 2 # matplotlib background transparent (issues on old versions?) if myConfig.get_boolean("Plotting", "plot_backgroundTransparent"): self.fig.frameon = False self.adjust = self.fig.subplots_adjust(top=plot_topOfPlot, left=plot_leftOfPlot, right=plot_rightOfPlot, bottom=plot_bottomOfPlot) FigureCanvas.__init__(self, self.fig) self.setParent(parent) self.navigationToolbar = Toolbar(self) # TODO: rather as a real toolbar: # self.toolbar = NavigationToolbar(self, self.myWidget.mpl_layout, coordinates=True) # self.myWidget.mplvl.addWidget(self.toolbar) FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) # zoom mode on/off self.zoomMode = False myLogger.debug_message(str(self) + ": initialized")
def createFigure(xdim, ydim): fig = P.Figure(facecolor='white') dpi = fig.get_dpi() curr_size = fig.get_size_inches() xinches = float(xdim) / float(dpi) yinches = float(ydim) / float(dpi) fig.set_size_inches((xinches, yinches)) return fig
def __init__(self, master): frame = Frame(master) frame.pack() Label(frame, text="PM 2.5: ", font=("Courier", 10, "bold"), width=8).grid(row=0, column=0, columnspan=3) Label(frame, text=u"µg/m\u00b3 ", font=("Courier", 10, "bold"), width=6).grid(row=0, column=3) Label(frame, text="PM 10: ", font=("Courier", 10, "bold"), width=8).grid(row=1, column=0, columnspan=3) Label(frame, text=u"µg/m\u00b3 ", font=("Courier", 10, "bold"), width=6).grid(row=1, column=3) self.result_pm25 = DoubleVar() Label(frame, textvariable=self.result_pm25, font=("Courier", 10, "normal"), width=5).grid(row=0, column=2) self.result_pm10 = DoubleVar() Label(frame, textvariable=self.result_pm10, font=("Courier", 10, "normal"), width=5).grid(row=1, column=2) button0 = Button(frame, text="Start", command=self.sensor_wake) button0.grid(row=2, column=0) button1 = Button(frame, text="Stop", command=self.sensor_sleep) button1.grid(row=2, column=1) button2 = Button(frame, text="Read", command=self.sensor_read) button2.grid(row=2, column=2) button3 = Button(frame, text="Record", command=self.sensor_live) button3.grid(row=2, column=3) button4 = Button(frame, text="Quit", command=self.quit) button4.grid(row=2, column=4) #Label(frame, text="").grid(row=3, column=3) fig = pylab.Figure() self.canvas = FigureCanvasTkAgg(fig, master=master) self.canvas.show() self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) self.ax = fig.add_subplot(111) self.ax.grid(True) self.ax.set_title("PM2.5 and PM10") self.ax.set_xlabel("Time (seconds)") self.ax.set_ylabel(u"PM (ug/m\u00b3)") self.ax.axis([0, 300, 0, 60])
def GraphUtilRawDataLineGraphs(self, gTitle, xLabel, yLabel, statTip, tabName, xx, whichG): """Generic graph method that helps graph the raw data. :param gTitle: Title of the graph :param xLabel: x-axis label :param yLabel: y-axis label :param statTip: status tip :param tabName: tab name :param xx: x-axis values :param whichG: char to know which graph to plot """ mainGraph = qtWidgets.QWidget() fig = plab.Figure((3.0, 3.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(mainGraph) axes = fig.add_subplot(111) nRow = self.dockedOpt.TT.shape[0] # Gets the number of rows nCol = self.dockedOpt.TT.shape[1] if whichG == 'L': for j in range(nCol): yy = self.dockedOpt.TT[:, j] axes.plot(xx, yy) elif whichG == 'C': tMax = np.max(self.dockedOpt.TT) tMin = np.min(self.dockedOpt.TT) z = np.linspace(tMin, tMax) yx = range(nCol) axes.contourf(yx, xx, self.dockedOpt.TT, z, cmap='jet') fig.colorbar(axes.contourf(yx, xx, self.dockedOpt.TT, z, cmap='jet')) contrastBtn = qtWidgets.QPushButton("Contrast") contrastBtn.clicked.connect(self.ColorGraphContrastDialog) axes.set_title(gTitle) axes.set_xlabel(xLabel) axes.set_ylabel(yLabel) canvas.draw() tab = qtWidgets.QWidget() tab.setStatusTip(statTip) vbox = qtWidgets.QVBoxLayout() graphNavigationBar = NavigationToolbar(canvas, self) vbox.addWidget(graphNavigationBar) if whichG == 'C': hBox = qtWidgets.QHBoxLayout() hBox.addStretch() hBox.addWidget(contrastBtn) vbox.addLayout(hBox) vbox.addWidget(canvas) tab.setLayout(vbox) self.savingCanvasTabs(tab, tabName, canvas, fig)
def graficaCaja(datasetList,low,hight,steps): ''' genera una grafica de caja y bigote con los set de datos incluidos en datasetList ''' pylab.Figure() pylab.title("Hipervolumen") pylab.ylabel("Hipervolumen") pylab.xlabel("Funciones") #pylab.yticks(range(low,hight,steps)) pylab.boxplot(datasetList) pylab.xticks([1,2,3,4],['ZDT2','ZDT3','ZDT6','DTLZ2']) pylab.show()
def graphEachFitRawData(self, xx, yy, fitData, whichFit): """This method graphs the raw data and the fitted data for each column. :param xx: bins :param yy: raw data column :param popt: from the gaussian fit :param whichPeak: number of peaks """ try: self.mainGraph = qtWidgets.QDialog(self.myMainWindow) self.mainGraph.resize(600, 600) dpi = 100 fig = plab.Figure((3.0, 3.0), dpi=dpi) canvas = FigureCanvas(fig) canvas.setParent(self.mainGraph) axes = fig.add_subplot(111) xAxisName, xAxis, scan = self.myMainWindow.getScanxAxis() axes.set_xlabel(xAxisName) xx = xAxis axes.plot(xx, yy, 'b+:', label='data') if whichFit == 'G': axes.plot(xx, fitData, 'ro:', label='fit') axes.set_title('Gaussian Fit') elif whichFit == 'L': axes.plot(xx, fitData, 'ro:', label='fit') axes.set_title("Lorentzian Fit") elif whichFit == 'V': axes.plot(xx, fitData, 'ro:', label='fit') axes.set_title("Voigt Fit") axes.legend() axes.set_ylabel('Intensity') canvas.draw() vbox = qtWidgets.QVBoxLayout() hbox = qtWidgets.QHBoxLayout() self.skipEachFitGraphButton() self.nextFitGraphButton() hbox.addWidget(self.skipEachFitGraphBtn) hbox.addStretch(1) hbox.addWidget(self.nextFitGraphBtn) graphNavigationBar = NavigationToolbar(canvas, self.mainGraph) vbox.addLayout(hbox) vbox.addWidget(graphNavigationBar) vbox.addWidget(canvas) self.mainGraph.setLayout(vbox) self.mainGraph.exec_() except Exception as e: qtWidgets.QMessageBox.warning(self.myMainWindow, "Error", "Please make sure the guesses are realistic when fitting. \n\n" + str(e))
def _create_canvas(self, parent): self.fig = pylab.Figure() self.canvas = FigureCanvas(self, -1, self.fig) #self.canvas = FigureCanvas(parent, -1, self.fig) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.sizer) self._create_toolbar() tw, th = self.toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() self.toolbar.SetSize(wx.Size(fw, th)) self.toolbar.update() #?? self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.Fit() self.canvas.mpl_connect('pick_event', self.onpick)
def GraphUtilGaussianFitGraphs(self, name, x, y, error, xLabel, yLabel, whichGraph): """Generic plotting method that plots depending on which graph is being plotted. :param canvas: canvas for widget :param fig: figure for graph :param name: name of tab :param x: x-values :param y: y-values :param error: error values for gaussian fit graphs :param xLabel: x-axis label :param yLabel: y-axis label :param whichGraph: char that represents either gaussian or lattice fit """ mainGraph = qtWidgets.QWidget() fig = plab.Figure((5.0, 4.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(mainGraph) axes = fig.add_subplot(111) axes.plot(x, y) print(y) print("Fitted Data") print(name) if whichGraph == 'G': axes.errorbar(x, y, yerr=error, fmt='o') elif whichGraph == 'L': axes.plot(x, y, 'go') axes.yaxis.set_major_formatter(plab.FormatStrFormatter('%.4f')) axes.set_title(name) axes.set_xlabel(xLabel) axes.set_ylabel(yLabel) canvas.draw() tab = qtWidgets.QWidget() tab.setStatusTip(name) vbox = qtWidgets.QVBoxLayout() graphNavigationBar = NavigationToolbar(canvas, mainGraph) vbox.addWidget(graphNavigationBar) vbox.addWidget(canvas) tab.setLayout(vbox) self.myMainWindow.savingCanvasTabs(tab, name, canvas, fig)
def __init__(self, figSize=(5.0, 3.0), dpi=300): # Initialize class variables self.numPlots = 0 self._plotDescriptions = [] # Create a figure self._figure = pylab.Figure(figsize=figSize, dpi=dpi) # Perform some figure setup pylab.hold(True) pylab.grid(True) # Add a formatter for the y-axis self._formatter = FuncFormatter(self._formatDollars) # Create a SetTitle method self.SetTitle = pylab.title return
def getTopRankedFigure(self,nodeBcRank,measureShorthand,nTop=5,plotAtMost=10): tops={} for node in nodeBcRank.iterkeys(): for rank in nodeBcRank[node]: if rank<nTop: tops[node]=tops.get(node,0)+1 names=tops.keys() names.sort(key=lambda x:tops[x],reverse=True) data=[] for name in names: data.append(tops[name]) fig=pylab.Figure(figsize=(5,3.8),dpi=80) fig.subplots_adjust(bottom=0.3) axes=fig.add_subplot(111) nums=range(min(len(data),plotAtMost)) axes.bar(nums,data[:plotAtMost]) axes.set_xticklabels(names,rotation=45,fontsize=8) axes.set_xticks(map(lambda x:x+0.5,nums)) axes.set_title("# of times at top "+str(nTop)) return fig
def run(): results = get_antibio_datas(1) print "yes" col = 4 row = (len(results["data"])/col) + 1 fig = pylab.Figure(facecolor="red") fig.set_axis_on() # fig.canvas.set_window_title(results["name"]) colors = ["#77DD77","#FFB347","#FF6961"] i=1 for atb in results["data"]: sizes = [atb["S"],atb["I"],atb["R"]] pylab.subplot(row,col,i) pylab.title(atb["name"], fontsize=10) pylab.pie(sizes, colors=colors) pylab.axis('equal') i+=1 pylab.subplots_adjust(hspace = .5) pylab.axis('equal') pylab.show()
Eb = Es / (N.sinh(k*h)**2) ##print "Energy at Top:", ##print Es[0:1] ##print "Energy at Bottom:", ##print Eb[0:1] ##print "Ratio:" ##print Eb[0:1] / Es[0:1] # total energy Etotal = N.sum(Eb, 1)# sum across rows print "max energy", N.maximum.reduce(Etotal) # Plot energy over time: F = pylab.Figure() ax = pylab.subplot(1,1,1) #print "Position:", ax.get_position() left, bottom, width, height = ax.get_position() delta = 0.08 ax.set_position([left, bottom + delta, width, height-delta]) #pylab.plot(pylab.date2num(datetimes), Etotal ) #pylab.plot_date(pylab.date2num(datetimes), Etotal, "-" ) ax.plot_date(pylab.date2num(datetimes), Etotal, "-" ) ax.set_title("Total wave energy at the bottom at a depth of %i ft."%(h * 3.281,)) #Trim axis: if MaxVal is not None:
def Load_CSV(disable_widgets, enable_widgets): global array, canvas for widget in disable_widgets: widget.config(state="disabled") for widget in enable_widgets: widget.config(state="normal") file_type = (option_menu_title.get())[-4:] if file_type == '.csv': CSV_name = option_menu_title.get() CSV_path = join('Data', CSV_name) root.title(('PPP: {0}').format(CSV_name)) file = open(CSV_path) csv_reader = csv.reader(file) lines = 0 #count lines in the chosen csv for row in csv_reader: lines += 1 ref.lines = lines array = np.zeros((lines, 2)) ref.array_length = lines #make empty array file = open( CSV_path ) #for some reason i need to repeate this bit otherwise it wont work WHO KNOWS reader = csv.reader(file) for index, row in enumerate(reader): #populate array array[index, 0] = float(row[0]) array[index, 1] = float(row[1]) elif file_type == '.txt': TXT_name = option_menu_title.get() TXT_path = join('Data', TXT_name) text_file = open(TXT_path, 'r') reader = text_file.readlines() array = np.zeros((len(reader), 2)) for index, line in enumerate(reader): # print(index) # print(line[:(line.find('\t'))]) # print(line[(line.find('\t')):]) # print('') x, y = float(line[:(line.find('\t'))]), float( line[(line.find('\t')):]) array[index, 0] = float(x) array[index, 1] = float(y) ref.lines = len(reader) #fix this to be the number of lines fig = pl.Figure(figsize=(16, 9)) plot1 = fig.add_subplot(111) plot1.plot(array[:, 0], array[:, 1]) canvas = FigureCanvasTkAgg(fig, master=root) canvas.draw() toolbar = NavigationToolbar2Tk(canvas, root) toolbar.update() canvas.get_tk_widget().place(x=0, y=7) over_view = pl.figure() pl.xlabel('ADC') pl.ylabel('Entries') pl.title('SiPM Output') pl.plot(array[:, 0], array[:, 1]) pl.xlim(min(array[:, 0]), max(array[:, 0]) / 2) pl.rcParams['figure.figsize'] = 16, 9 pl.savefig('Saved/fig0.png') pl.close(over_view) def callback(event): x = int(event.xdata) y = int(event.ydata) most_recent_coords.set(('Current Coords:\n' + str(x) + ', ' + str(y))) ref.lastest_coords = (x, y) canvas.mpl_connect('button_press_event', callback)
slipRateE = mask1 * V1 + mask2 * V2 + mask3 * V3 + mask4 * V4 + mask5 * V5 + mask6 * V6 stateVarE = theta muE = mu0 + a * numpy.log(slipRateE / V0) + b * numpy.log(V0 * stateVarE / L) # ---------------------------------------------------------------------- h5 = h5py.File("output/ratestate_%s-fault.h5" % sim, "r") time = h5['time'][:].ravel() slip = h5['vertex_fields/slip'][:] slipRate = h5['vertex_fields/slip_rate'][:] stateVar = h5['vertex_fields/state_variable'][:] traction = h5['vertex_fields/traction'][:] h5.close() fig = pylab.Figure() p = 2 ax = pylab.subplot(1, 4, 1) ax.plot(time, slip[:, p, 0], 'r--') ax = pylab.subplot(1, 4, 2) ax.plot(t, numpy.log10(numpy.abs(slipRateE)), 'b-', time, numpy.log10(numpy.abs(slipRate[:, p, 0])), 'r--') ax.set_ylim(-12, 0.0) ax = pylab.subplot(1, 4, 3) ax.plot(t, numpy.log10(stateVarE), 'b-', time, numpy.log10(stateVar[:, p, 0]), 'r--') ax.set_ylim(-2.0, 6.0)
resu_lin,erru_lin,rest,aparm_lin,averr_lin = error_analysis(fldrn) fldrn = '/media/haiau/Data/PyFEM_Results/result_linear_si_' resu_lin_si,erru_lin_si,rest,aparm_lin_si,averr_lin_si = error_analysis(fldrn) #fig = pl.Figure() # for i in range(1,len(num_steps)): pl.semilogy(rest[i-1],erru_nl[i-1],label='$\Delta_t=$'+str(1.0e-3/num_steps[i-1])+'$s$') pl.legend(loc=4,prop={'size': 8}) pl.xlabel('$t$') pl.ylabel('$e$') fig = pl.Figure() for i in range(1,len(num_steps)): pl.semilogy(rest[i-1],erru_lin[i-1],label='$\Delta_t=$'+str(1.0e-3/num_steps[i-1])+'$s$') pl.legend(loc=4,prop={'size': 8}) pl.xlabel('$t$') pl.ylabel('$e$') fig = pl.Figure() for i in range(1,len(num_steps)): pl.semilogy(rest[i-1],erru_lin_si[i-1],label='$\Delta_t=$'+str(1.0e-3/num_steps[i-1])+'$s$') pl.legend(loc=4,prop={'size': 8}) pl.xlabel('$t$')
print 'Analyser() Fin ...' print "Analysis_time:%0.1fms" % ((time.time()-starttime)*1000) return Metricdata if __name__ == "__main__": # アナライズ Metricdata = analyser() # Create Qt Application app = QtGui.QApplication([]) # Create Figure Object fig = pl.Figure(figsize=(100,100), dpi=72, facecolor=(1,1,1), edgecolor=(0,0,0)) ax1 = fig.add_subplot(3,2,1) ax1.plot(Metricdata.trange, Metricdata.wavdata ) ax2 = fig.add_subplot(3,2,2) ax2.plot(Metricdata.fscalek, Metricdata.AdftLog) ax3 = fig.add_subplot(3,2,3) ax3.plot(Metricdata.fscalek, Metricdata.dftSpc_env) ax4 = fig.add_subplot(3,2,4) ax4.plot(Metricdata.fscalek, Metricdata.dftSpc_det) pl.xlim(0, 2) ax5 = fig.add_subplot(3,2,5)
def __init__(self, parent=None): # Standard Matplotlib code to generate the plot self.fig = plt.Figure() # initialize the canvas where the Figure renders into FigureCanvasQTAgg.__init__(self, self.fig) self.setParent(parent)
xticks=None, xticklabels=None, xmin=None, ymax=None): if xlabel: subplot.set_xlabel(xlabel) if ylabel: subplot.set_ylabel(ylabel) for t, n in zip(bins, hist): subplot.bar(t, n, width=width) if xmin: subplot.set_xlim(xmin=xmin) if ymax: subplot.set_ylim(ymax=ymax) if xticks is not None: subplot.set_xticks(xticks) if xticklabels: subplot.set_xticklabels(xticklabels) x = x0 figure = pylab.Figure() for simulator in simulators: for num_nodes in nodes: col = 1 subplot = figure.add_axes([x, y0 + 2.9 * dy, w, h]) subplot.set_title("%s (np%d)" % (simulator[:6].upper(), num_nodes), fontsize='x-large') subplot.set_ylabel("Membrane potential (mV)") # Get info about dataset from header of .v file exec( get_header("Results/VAbenchmark_%s_exc_%s_np%d.v" % (benchmark, simulator, num_nodes))) # Plot membrane potential trace allvdata = numpy.loadtxt("Results/VAbenchmark_%s_exc_%s_np%d.v" %
import sys import re import collections from DBUtil import * from numpy import mean import pylab as P if __name__ == '__main__': try: param = {'src': '/home/arya/bigdata/pmc/mesh.db', 'pipeline': 'mesh'} param['dst'] = param['src'] with dbConnector(param) as db_conn: mesh = db_conn.getAll() n = map(lambda x: len(eval(x[0])), mesh) P.Figure() nm, bins, patches = P.hist(n, 50, histtype='stepfilled') P.title( 'Number of MeSH headings per Paper on PMC (mean={})'.format( mean(n))) print mean(n) P.savefig("num_mesh.png") P.show() except (IOError, ValueError) as e: print str(e) sys.exit(1) print 'Done!'
def default(self): import pylab as plt fig = plt.Figure(facecolor='white') #fig.set_size_inches(self.width / float(fig.dpi), self.height / float(fig.dpi)) ax = fig.add_subplot(111) return ax
def Load_File(load_last=False): # this function loads the selected file Remove_Coords(clear=True) global array, canvas, info if load_last == True: #if load last is selcted this repalces the apth and name with the saved ones config_file = open(join('Config', 'config.txt'), 'r') reader = config_file.readlines() #loads data from the save file name = str(reader[3]) config_file.close() name = name.replace('\n', '') if name == 'None': tk.messagebox.showerror("Error", "No last file saved") return else: path = join('Data', name) else: name = option_menu_title.get() file_type = (name)[-4:] #get file type if file_type == '.csv': path = join('Data', name) root.title(('PPP: {0}').format(name)) file = open(path) csv_reader = csv.reader(file) #determine the number of rows in the csv row_count = sum(1 for row in csv_reader) # fileObject is your csv.reader array = np.zeros((row_count, 2)) #make empty array file = open( path ) #for some reason i need to repeate this bit otherwise it wont work WHO KNOWS reader = csv.reader(file) for index, row in enumerate(reader): #populate array array[index, 0] = float(row[0]) array[index, 1] = float(row[1]) elif file_type == '.txt': #method for reading atxt file path = join('Data', name) text_file = open(path, 'r') reader = text_file.readlines() row_count = (len(reader)) array = np.zeros((row_count, 2)) for index, line in enumerate(reader): x, y = float(line[:(line.find('\t'))]), float( line[(line.find('\t')):]) array[index, 0] = float(x) array[index, 1] = float(y) if load_last == False: #if load last is file saves it to the file config_file = open(join('Config', 'config.txt'), 'r') reader = config_file.readlines() #loads data from the save file adc_entry = int(reader[0]) #reads the first 3 lines elec_entry = int(reader[1]) stdev_entry = int(reader[2]) file_info.previous_load = str(reader[3]) auto_zoom = int(reader[4]) config_file.close() config_file = open(join('Config', 'config.txt'), 'w') last = str(name) # config_file.write(("{0}\n{1}\n{2}\n{3}\n{4}").format( adc_entry, elec_entry, stdev_entry, last, auto_zoom)) # writes to the file with the enw last load config_file.close() for widget in widgets.disable_on_load: #enable and disable required widgets widget.config(state="disabled") for widget in widgets.enable_on_load: widget.config(state="normal") path = path.replace('\n', '') size = stat(path).st_size file_info.size = size file_info.rows = row_count file_info.name = name if len(name) > 20: name = name[:20] + '...' info.set( ('File:\nName: {0}\nSize (bytes): {1}\n# Data points: {2}').format( name, size, row_count)) #sets the file info box to correct stuff print(sum(array[:, 1])) fig = pl.Figure(figsize=(16, 9)) plot1 = fig.add_subplot(111) zoom.xmin = min(array[:, 0]) zoom.xmax = max(array[:, 0]) x_min, x_max = True, True x_lim = zoom.xmax = max(array[:, 1]) / 20 if default.auto_zoom == True: for index in range(1, file_info.rows): x = int(array[index, 0]) y = int(array[index, 1]) if y != 0.0 and x_min == True: x_min = x - 50 index = file_info.rows - index x = int(array[index, 0]) y = int(array[index, 1]) if y >= x_lim and x_max == True: x_max = x + 50 zoom.xmin = x_min zoom.xmax = x_max plot1.set_xlim(x_min, x_max) plot1.plot(array[:, 0], array[:, 1]) global toolbar canvas = FigureCanvasTkAgg(fig, master=root) canvas.draw() if Data.already_loaded == True: toolbar.destroy() toolbar = NavigationToolbar2Tk(canvas, root) toolbar.update() elif Data.already_loaded == False: toolbar = NavigationToolbar2Tk(canvas, root) toolbar.update() canvas.get_tk_widget().place(x=0, y=7) over_view = pl.figure() pl.xlabel('ADC') pl.ylabel('Entries') pl.title('SiPM Output') pl.plot(array[:, 0], array[:, 1]) pl.xlim(zoom.xmin, zoom.xmax) pl.rcParams['figure.figsize'] = 16, 9 pl.savefig('Saved/fig0.png') pl.rcParams.update({'font.size': 20}) pl.show() pl.close(over_view) over_view = pl.figure() pl.xlabel('ADC') pl.ylabel('Entries') pl.title('SiPM Output') pl.plot(array[:, 0], array[:, 1]) pl.rcParams['figure.figsize'] = 16, 9 pl.savefig('Saved/fig0.png') pl.rcParams.update({'font.size': 20}) pl.show() pl.close(over_view) def callback(event): x = int(event.xdata) y = int(event.ydata) most_recent_coords.set(('\nCurrent Coords:\n' + str(x) + ', ' + str(y)) + ((default.max_peaks) * '\n')) Data.current_coords = (x, y) canvas.mpl_connect('button_press_event', callback) Data.already_loaded = True
#data.head() #sort by the amount of ratings data.groupby('title')['rating'].count().sort_values(ascending=False).head() #print(ratings) print(data) ratings = pd.DataFrame(data.groupby('title')['rating'].mean()) ratings.head() print(ratings) ratings['num of ratings'] = pd.DataFrame( data.groupby('title')['rating'].count()) ratings.head() print(ratings) #histograms #plt.figure(figsize=(10,4)) f = pl.Figure(figsize=(10, 4)) ratings['num of ratings'].hist(bins=70) #showing the graph pl.show() f = pl.Figure(figsize=(10, 4)) ratings['rating'].hist(bins=70) pl.show() sns.jointplot(x='rating', y='num of ratings', data=ratings, alpha=0.5) pl.show()