def SI(self): p_list = [] t_list = [] infected_list = [] for p in self.frange(0, 1, 0.1): t, num_infected = self.infect(p) p_list.append(p) t_list.append(t) infected_list.append( float(num_infected) / self.network.number_of_nodes()) plt.title("Infected Length vs Probability of Infection") plt.plot(p_list, t_list) plt.xlabel("Probability of Infection") plt.ylabel("Length of Infection (time steps)") plt.savefig("soundcould_infection_length.png") plt.clear() plt.title("Infected Percentage vs Probability of Infection") plt.plot(p_list, infected_list) plt.xlabel("Probability of Infection") plt.ylabel("Percent Infected") plt.savefig("soundcould_infection_percent.png") plt.clear()
def plot_multiple_figure(figure_names: vector, plot_handler, tight_layout=False, saved_path=None, max_cols=-1): # plt.gca() N = figure_names.length if N == 0: return False if max_cols == -1: cols = math.floor(math.sqrt(N)) else: cols = min(math.floor(math.sqrt(N)), max_cols) rows = (N + cols - 1) // cols plt.clear() fig = plt.figure(figsize=(cols * 4, rows * 4)) for index in range(N): ax = plt.subplot(rows, cols, index + 1) plot_handler[figure_names[index]](ax) if tight_layout: plt.tight_layout() if saved_path is not None: if saved_path.endswith("pdf"): with PdfPages(saved_path, "w") as f: plt.savefig(f, format="pdf") else: plt.savefig(saved_path, dpi=300) else: plt.show() return True
def plotTSP(tsp : TSP, plotArea): plt = plotArea.figure.gca() plt.clear() xList = [] yList = [] for city in tsp.cityList: xList.append(city.posX) yList.append(city.posY) plt.plot(xList, yList) plotArea.Layout()
def _plot_x_y(self, ix, iy, xlabel, ylabel, scatter, modes=None, fig=None, axes=None, xlim=None, ylim=None, show=True, clear=False, legend=True, png_filename=None, **kwargs): """builds the plot""" self.fix() if kwargs is None: kwargs = {} modes, imodes = _get_modes_imodes(self.modes, modes) if fig is None: fig = plt.figure() axes = fig.add_subplot(111) symbols = self.symbols for i, imode, mode in zip(count(), imodes, modes): symbol = symbols[i] freq = self.results[imode, :, self.ifreq].ravel() xs = self.results[imode, :, ix].ravel() ys = self.results[imode, :, iy].ravel() iplot = np.where(freq != np.nan) #iplot = np.where(freq > 0.0) axes.plot(xs[iplot], ys[iplot], symbol, label='Mode %i' % mode, markersize=0) if scatter: scatteri = np.linspace(.75, 50., len(xs)) #assert symbol[2] == '-', symbol axes.scatter(xs[iplot], ys[iplot], s=scatteri, color=symbol[0], marker=symbol[1]) axes.grid(True) axes.set_xlabel(xlabel) axes.set_ylabel(ylabel) if xlim: axes.set_xlim(xlim) if ylim: axes.set_ylim(ylim) title = 'Subcase %i' % self.subcase if png_filename: title += '\n%s' % png_filename fig.suptitle(title) if legend: axes.legend(**kwargs) if show: plt.show() if png_filename: plt.savefig(png_filename) if clear: plt.clear() return axes
def plot_transient(sample_df, sample_name, save_dir): # plot the time sequence parameter plt.figure(figsize=(16, 12)) plt.subplot(221) plt.plot(sample_df.index.values, sample_df.gateSignalVoltage.values) plt.title('Gate Signal Voltage', fontsize='xx-large') plt.xlabel('Time /10ns', fontsize='xx-large') plt.ylabel('Voltage /V', fontsize='xx-large') plt.xticks(fontsize=12) plt.yticks(fontsize=12) plt.ylim([-2, 12]) plt.tight_layout() # plt.savefig( 'transient_picture/gateSignalVoltage'+sample_name+'.png') plt.subplot(222) plt.plot(sample_df.index.values, sample_df.gateEmitterVoltage.values) plt.title('Gate Emitter Voltage', fontsize='xx-large') plt.xlabel('Time /10ns', fontsize='xx-large') plt.ylabel('Voltage /V', fontsize='xx-large') plt.xticks(fontsize=12) plt.yticks(fontsize=12) plt.ylim([-2, 12]) plt.tight_layout() # plt.savefig( 'transient_picture/gateEmitterVoltage'+sample_name+'.png') # plot the time sequence parameter plt.subplot(223) plt.plot(sample_df.index.values, sample_df.collectorEmitterVoltage.values) plt.title('Collector Emitter Voltage', fontsize='xx-large') plt.xlabel('Time /10ns', fontsize='xx-large') plt.ylabel('Voltage /V', fontsize='xx-large') plt.xticks(fontsize=12) plt.yticks(fontsize=12) plt.ylim([-2, 12]) plt.tight_layout() # plt.savefig('transient_picture//collectorEmitterVoltage'+sample_name+'.png') # collectorEmitterCurrentSingal # plot the time sequence parameter plt.subplot(224) plt.plot(sample_df.index.values, sample_df.collectorEmitterCurrentSingal.values) plt.title('Collector Emitter Current', fontsize='xx-large') plt.xlabel('Time /10ns', fontsize='xx-large') plt.ylabel('Current /A', fontsize='xx-large') plt.xticks(fontsize=12) plt.yticks(fontsize=12) plt.ylim([-2, 12]) plt.tight_layout() plt.savefig(save_dir + sample_name + '.png') plt.clear("all")
def _plot_x_y(self, ix, iy, xlabel, ylabel, scatter, modes=None, fig=None, xlim=None, ylim=None, show=True, clear=False, legend=True, png_filename=None, **kwargs): """builds the plot""" self.fix() if kwargs is None: kwargs = {} modes, imodes = self._get_modes_imodes(modes) if fig is None: fig = plt.figure() axes = fig.add_subplot(111) self._set_xy_limits(xlim, ylim) symbols = self.symbols for i, imode, mode in zip(count(), imodes, modes): symbol = symbols[i] freq = self.results[imode, :, self.ifreq].ravel() real = self.results[imode, :, ix].ravel() imag = self.results[imode, :, iy].ravel() iplot = np.where(freq != np.nan) #iplot = np.where(freq > 0.0) axes.plot(real[iplot], imag[iplot], symbol, label='Mode %i' % mode, markersize=0) if scatter: s = np.linspace(.75, 50., len(real)) #assert symbol[2] == '-', symbol axes.scatter(real[iplot], imag[iplot], s=s, color=symbol[0], marker=symbol[1]) axes.grid(True) axes.set_xlabel('Eigenvalue (Real)') axes.set_ylabel('Eigenvalue (Imaginary)') title = 'Subcase %i' % self.subcase if png_filename: title += '\n%s' % png_filename fig.suptitle(title) if legend: axes.legend(**kwargs) if show: plt.show() if png_filename: plt.savefig(png_filename) if clear: plt.clear()
def animate(i): pullData = open("sampleText.txt", "r").read() dataList = pullData.split('\n') xList = [] yList = [] for eachLine in dataList: if len(eachLine) > 1: x, y = eachLine.split(',') x = datetime.strptime(x, "%Y-%m-%d %H:%M:%S.%f") x = matplotlib.dates.date2num(x) xList.append(int(x)) yList.append(int(y)) plt.clear() plt.plot(xList, yList) plt.show()
def update(i): var_t_val=var_t_vals[i] label = str(var_t_val) # print(label) # Update the line and the axes (with a new xlabel). Return a tuple of # "artists" that have to be redrawn for this frame. plt.clear() var_x_vals = (merge_df.loc[merge_df[var_t]==var_t_val,var_x]).reset_index(drop=True) var_y_vals = (merge_df.loc[merge_df[var_t]==var_t_val,(var_y+"_"+source)]).reset_index(drop=True) # line.set_xdata(var_x_vals) # line.set_ydata(var_y_vals) plt.plot(var_x_vals, var_y_vals, color=colour_models(var_y)) #line, = ax.plot(var_x_vals, var_y_vals, 'ro', linewidth=2) plt.set_xlabel(label) #plt.title(label) return line, ax
def draw_plot(x, y, title="plot", xlabel="x axis", ylabel="y axis", legends=[]): coef_margin = 0.1 x_len = np.max(x) - np.min(x) y_len = np.max(y) - np.min(y) plt.clear() plt.title(title) plt.axis([np.min(x) - coef_margin * x_len, np.max(x) + coef_margin * x_len, \ np.min(y) - coef_margin * y_len, np.max(y) + coef_margin * y_len]) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.plot(x, y) plt.show()
def plot_graph(self): self.ui.tempGraph.plot(self.idx_list, self.temp_list) plt = self.ui.tempGraph.canvas.ax plt.clear() plt.set_xlabel('Latest 10 values') if self.mode == "C": plt.set_ylabel('Temperature (Celsius)') plt.set_title('Temperature') #| Average = {0:0.1f} deg C elif self.mode == "F": plt.set_ylabel('Temperature (Fahrenheit)') plt.set_title('Temperature') # | Average = {0:0.1f} deg F.format(self.avgT).format(self.avgT) self.ui.tempGraph.canvas.draw() self.ui.humGraph.plot(self.idx_list, self.hum_list) plt2 = self.ui.humGraph.canvas.ax plt2.clear() plt2.set_xlabel('Latest 10 values') plt2.set_ylabel('Humidity (%)') plt2.set_title('Humidity') #| Average = {0:0.1f} %.format(self.avgH) self.ui.humGraph.canvas.draw()
def plot_vg_vf(self, fig=None, modes=None, show=None, png_filename=None, clear=False, legend=None, xlim=None, ylim_damping=None, ylim_freq=None): """ Make a V-g and V-f plot Parameters ---------- modes : List[int] / int ndarray; (default=None -> all) the modes; typically 1 to N """ self.fix() if fig is None: fig = plt.figure() # figsize=(12,9), self.subcase gridspeci = gridspec.GridSpec(2, 4) damp_axes = fig.add_subplot(gridspeci[0, :3]) freq_axes = fig.add_subplot(gridspeci[1, :3], sharex=damp_axes) #self._set_xy_limits(xlim, ylim) modes, imodes = self._get_modes_imodes(modes) symbols = self.symbols _kvelocity, velocity_units = self._get_unit_factor('velocity') legend_items = ['Mode %i' % mode for mode in modes] for i, imode, mode in zip(count(), imodes, modes): vel = self.results[imode, :, self.ivelocity].ravel() damping = self.results[imode, :, self.idamping].ravel() freq = self.results[imode, :, self.ifreq].ravel() #iplot = np.where(freq > 0.0) #damp_axes.plot(vel, damping, symbols[i], label='Mode %i' % mode) #freq_axes.plot(vel, freq, symbols[i]) iplot = np.where(freq != np.nan) damp_axes.plot(vel[iplot], damping[iplot], symbols[i], label='Mode %i' % mode) freq_axes.plot(vel[iplot], freq[iplot], symbols[i]) damp_axes.set_xlabel('Velocity [%s]' % velocity_units) damp_axes.set_ylabel('Damping') damp_axes.grid(True) if xlim is not None: damp_axes.set_xlim(xlim) if ylim_damping is not None: damp_axes.set_ylim(ylim_damping) freq_axes.set_xlabel('Velocity [%s]' % velocity_units) freq_axes.set_ylabel('Frequency [Hz]') freq_axes.grid(True) if xlim is not None: freq_axes.set_xlim(xlim) if ylim_freq is not None: freq_axes.set_ylim(ylim_freq) title = 'Subcase %i' % self.subcase if png_filename: title += '\n%s' % png_filename damp_axes.set_title(title) #plt.suptitle(title) if legend: damp_axes.legend(legend_items, fontsize=10, bbox_to_anchor=(1.125, 1.), loc=2) #fig.subplots_adjust(hspace=0.25) #fig.subplots_adjust(hspace=.5) #plt.legend() #damp_axes.legend(legend_items, bbox_to_anchor=anchor, ncol=2) #fig.subplots_adjust(hspace=0.25) #fig.subplots_adjust(hspace=.5) if show: plt.show() if png_filename: plt.savefig(png_filename) if clear: plt.clear()
def update(): area_from_ξ(ξ, show=True, params=p) plt.clear('all')
def destroy_fig(self): plt.clear(self.fig)
def inline_train(self, input, output): ''' Function to execute the inline training of the RHONN Parameters ---------- input - an iterable with the input given to the system. output - an iterable with the output measured from the system. ''' # Initial values if not self.inline_started: self.s_x = np.zeros(self.in_size) self.weights = np.random.rand(self.out_size, self.num_z) self.error = np.zeros(self.out_size) self.z = np.random.rand(self.out_size, self.num_z) self.x_estimated = np.zeros(self.out_size) self.k = 0 # Var to save the training history self.inputs = [] self.outputs = [] self.net_outputs = [] self.errors = [] # Create figures for ploting data fig_error = plt.figure('Error') error_ax = fig_error.add_subplot(111) figs = [ plt.figure('State variable {}'.format(n + 1)) for n in range(self.out_size) ] axes = [figs[n].add_subplot(111) for x in range(self.out_size)] self.inline_started = True self.inputs.append(input) self.outputs.append(output) # Applying activation functions for n in range(len(self.activation_funcs)): self.s_x[n] = self.activation_funcs[n](input[n]) # TODO: Fix the elements in the Z vector # Calculating network output if self.z_structure is not None: self.z = self.calculate_z(self.s_x) else: self.z = np.array([self.s_x for x in range(self.num_z)]) self.x_estimated = [ np.dot(self.weights[n].T, self.z[n]) for n in range(self.out_size) ] # Calculating the error self.error = np.subtract(output, self.x_estimated) # Save results self.net_outputs.append(self.x_estimated) self.errors.append(self.error) if self.debug: print self.str_result.format(k, output, self.x_estimated, self.error) # Calculating the adjustment for all the array with EFK if self.fnc_weights_adjsmnt is None: weights_res = self.EKF_weights_adjustment(self.z, self.weights, self.error) estimated_weights = weights_res[0] self.EKF_P = weights_res[1] else: estimated_weights = self.fnc_weights_adjsmnt( self.weights, self.error) # Save the new weights self.weights = estimated_weights # Save the time units elapsed self.k += 1 # Ploting data if self.plot_data: plt.clear() for n in range(self.out_size): line = error_ax.plot(self.error[:, n], label='State var {}'.format(n + 1)) plt.legend() for n in range(self.out_size): axes[n].clear() line_1, = axes[n].plot(self.outputs[:, [n]], label='System') line_2, = axes[n].plot(self.net_out[:, [n]], linestyle='--', label='RHONN', color='red') plt.legend() plt.show() pass
print(INSTR_IDX) if INSTR_IDX == 1 and button == 'next': frame.create_image(0, 0, image=img, anchor=NW) root.title("Instructions- page 2/2") INSTR_IDX += 1 elif INSTR_IDX == 2 and button == 'prev': frame.create_image(0, 0, image=img, anchor=NW) root.title("Instructions- page 1/2") INSTR_IDX -= 1 elif INSTR_IDX == 1 and button == 'prev': return else: root.destroy() """-------------------------------------------------- this function creates buttons 'next','reset','hint' in GUI, after user clears the current choice (after plt.clear() is called) ... no params for this function --------------------------------------------------""" def make_buttons(): global im_hint global im_hint_off_1 global show_suggestions_axes next_button_axes = plt.axes([0.91, 0.46, 0.08, 0.08]) im_next = pilim.open("imgs/Toggle_next.png") next_graph_but = matButton(next_button_axes,
def plot_vg_vf(self, fig=None, damp_axes=None, freq_axes=None, modes=None, show=None, plot_type='tas', png_filename=None, clear=False, legend=None, xlim=None, ylim_damping=None, ylim_freq=None, nopoints=False): """ Make a V-g and V-f plot Parameters ---------- modes : List[int] / int ndarray; (default=None -> all) the modes; typically 1 to N """ #self.fix() if fig is None: fig = plt.figure() # figsize=(12,9), self.subcase gridspeci = gridspec.GridSpec(2, 4) damp_axes = fig.add_subplot(gridspeci[0, :3]) freq_axes = fig.add_subplot(gridspeci[1, :3], sharex=damp_axes) #self._set_xy_limits(xlim, ylim) modes, imodes = _get_modes_imodes(self.modes, modes) symbols = self.symbols legend_items = ['Mode %i' % mode for mode in modes] ix, xlabel = self._plot_type_to_ix_xlabel(plot_type) for i, imode, mode in zip(count(), imodes, modes): vel = self.results[imode, :, ix].ravel() damping = self.results[imode, :, self.idamping].ravel() freq = self.results[imode, :, self.ifreq].ravel() #iplot = np.where(freq > 0.0) #damp_axes.plot(vel, damping, symbols[i], label='Mode %i' % mode) #freq_axes.plot(vel, freq, symbols[i]) #iplot = np.where(freq != np.nan) #damp_axes.plot(vel[iplot], damping[iplot], symbols[i], label='Mode %i' % mode) #freq_axes.plot(vel[iplot], freq[iplot], symbols[i]) if symbols and not nopoints: symbol = symbols[i] damp_axes.plot(vel, damping, symbol, label='Mode %i' % mode) freq_axes.plot(vel, freq, symbol) else: damp_axes.plot(vel, damping, label='Mode %i' % mode) freq_axes.plot(vel, freq) damp_axes.set_xlabel(xlabel) freq_axes.set_xlabel(xlabel) damp_axes.set_ylabel('Damping') damp_axes.grid(True) if xlim is not None: damp_axes.set_xlim(xlim) if ylim_damping is not None: damp_axes.set_ylim(ylim_damping) freq_axes.set_ylabel('Frequency [Hz]') freq_axes.grid(True) if xlim is not None: freq_axes.set_xlim(xlim) if ylim_freq is not None: freq_axes.set_ylim(ylim_freq) title = 'Subcase %i' % self.subcase if png_filename: title += '\n%s' % png_filename damp_axes.set_title(title) #plt.suptitle(title) if legend: damp_axes.legend(legend_items, fontsize=10, bbox_to_anchor=(1.125, 1.), loc=2) #fig.subplots_adjust(hspace=0.25) #fig.subplots_adjust(hspace=.5) #plt.legend() #damp_axes.legend(legend_items, bbox_to_anchor=anchor, ncol=2) #fig.subplots_adjust(hspace=0.25) #fig.subplots_adjust(hspace=.5) if show: plt.show() if png_filename: plt.savefig(png_filename) if clear: plt.clear()
# Thu, 08 Jun 2017 01:04:08 import numpy as np import matplotlib.pyplot as plt import time plt.axis([0, 10, 0, 1]) plt.ion() for i in range(10): y = np.random.random() plt.scatter(i, y) plt.pause(0.01) time.sleep(1) # Thu, 08 Jun 2017 01:04:27 plt.clear() # Thu, 08 Jun 2017 01:04:30 plt.cla() # Thu, 08 Jun 2017 01:04:38 import numpy as np import matplotlib.pyplot as plt import time plt.axis([0, 10, 0, 1]) plt.ion() for i in range(10): y = np.random.random() plt.scatter(i, y) plt.pause(0.01) time.sleep(1)
def listofpeakinfo(x,y,indexes,samplename):#x and y are np.arrays peakdata=[] try: plt.clear() except: pass plt.figure(figsize=(10,6)) plt.plot(x,y,'black',label=samplename) for item in range(len(indexes)): nbofpoints=80#on each side of max position while(1): try: x0=x[indexes[item]-nbofpoints:indexes[item]+nbofpoints] y0=y[indexes[item]-nbofpoints:indexes[item]+nbofpoints] #baseline height bhleft=np.mean(y0[:20]) bhright=np.mean(y0[-20:]) baselineheightatmaxpeak=(bhleft+bhright)/2 if abs(bhleft-bhright)<50:#arbitrary choice of criteria... #find FWHM d=y0-((max(y0)-bhright)/2) ind=np.where(d>bhright)[0] hl=(x0[ind[0]-1]*y0[ind[0]]-y0[ind[0]-1]*x0[ind[0]])/(x0[ind[0]-1]-x0[ind[0]]) ml=(y0[ind[0]-1]-hl)/x0[ind[0]-1] yfwhm=((max(y0)-baselineheightatmaxpeak)/2)+baselineheightatmaxpeak xleftfwhm=(yfwhm - hl)/ml hr=(x0[ind[-1]]*y0[ind[-1]+1]-y0[ind[-1]]*x0[ind[-1]+1])/(x0[ind[-1]]-x0[ind[-1]+1]) mr=(y0[ind[-1]]-hr)/x0[ind[-1]] xrightfwhm=(yfwhm - hr)/mr FWHM=abs(xrightfwhm-xleftfwhm) Peakheight=max(y0)-baselineheightatmaxpeak center=x[indexes[item]] plt.plot(x0, y0, 'red') plt.plot([x0[0],x0[-1]],[bhleft,bhright],'blue') # plt.plot(x0,y0,ms=0) plt.plot([xleftfwhm,xrightfwhm],[yfwhm,yfwhm],'green') plt.text(center,max(y0)+200,str('%.1f' % float(center)),rotation=90,verticalalignment='bottom',horizontalalignment='center',multialignment='center') peakdata.append([center,FWHM,Peakheight]) break else: if nbofpoints>=15: nbofpoints-=10 else: print("indexerror unsolvable") break except IndexError: if nbofpoints>=15: nbofpoints-=10 else: print("indexerror unsolvable") break plt.scatter(x[indexes],y[indexes],c='red',s=12) plt.legend() plt.ylabel("Intensity (a.u.)") plt.xlabel("2\u0398 (degree)") plt.savefig(samplename+'.pdf') # plt.show() plt.close() return peakdata
def plotGraph(xList, yList, name, plotArea): plt = plotArea.figure.gca() plt.clear() plotArea.figure.axes.clear() plt.plot(xList, yList) plotArea.Layout()
def plot_option_scores(): xs = [10 + 10 * x for x in range(1000)] scores = bruteforce_option_stats() top_scorers = {} worst_scorers = {} score_history = {} # for option_ids, option_scores in list(scores.items()): # scores[option_ids] = np.log(1 + option_scores) for option_ids, option_scores in scores.items(): for score_idx, nr_iter in enumerate(xs): option_score = option_scores[score_idx] top_scorers[nr_iter] = (option_ids, option_score) worst_scorers[nr_iter] = (option_ids, option_score) score_history[nr_iter] = [] break for option_ids, option_scores in tqdm.tqdm(scores.items()): for score_idx, nr_iter in enumerate(xs): option_score = option_scores[score_idx] if top_scorers[nr_iter][1] < option_score: top_scorers[nr_iter] = (option_ids, option_score) if worst_scorers[nr_iter][1] > option_score: worst_scorers[nr_iter] = (option_ids, option_score) score_history[nr_iter].append(option_score) scores = bruteforce_options() no_options = scores[(None, None, None, None)] xs = [10, 30, 60, 200, 500, 1000, 2000, 4000, 8000, xs[-1]] import seaborn as sns sns.set(color_codes=True) data = [] # xs = sorted(score_history.keys()) for x in xs: data.append(score_history[x]) plt.figure(1, figsize=(15, 5)) y_low, y_high = worst_scorers[xs[0]][1], top_scorers[xs[-1]][1] y_high = np.log(1000) plt.ylim(ymin=y_low, ymax=y_high) # plt.subplot( data = np.array(data) no_options_show = [] xs_full = [10 + 10 * x for x in range(1000)] for idx, x in enumerate(xs_full): if x in xs: no_options_show.append(no_options[idx]) percentiles_ranges = [1, 50, 90, 95, 99, 99.9, 100] percentiles = [{} for nr_iter in percentiles_ranges] for nr_iter in tqdm.tqdm(xs, desc="percentiels"): for idx, perc in enumerate(percentiles_ranges): percentiles[idx][nr_iter] = np.percentile(score_history[nr_iter], perc) x_labels = [str(idx) + "_" + str(x) + "_iter" for idx, x in enumerate(xs)] # plt.plot(x_labels, data) plt.plot(x_labels, data.mean(axis=1), 'o', label="mean") # print(percentiles) for idx, perc in tqdm.tqdm(enumerate(percentiles_ranges), desc="plot percs"): ys = [percentiles[idx][x] for x in xs] plt.plot(x_labels, ys, 'o', label="perc:" + str(perc)) plt.legend(loc='upper right') plt.title("percentiles") plt.savefig("percentiles.png") plt.plot(x_labels, no_options_show, label="no options") plt.legend(loc='upper left') plt.title("percentiles and no options") plt.savefig("percentiles_and_no_options.png") plt.clear() x_labels = [ str(idx) + "_" + str(x) + "%" for idx, x in enumerate(percentiles_ranges) ] for nr_iter in tqdm.tqdm(percentiles[0].keys(), desc="perc vs score"): ys = [ percentiles[percentiles_ranges.index(perc)][nr_iter] for perc in percentiles_ranges ] plt.plot(x_labels, ys, 'o', label="iter:" + str(nr_iter)) plt.legend(loc='upper left') plt.title("perc vs score") plt.savefig("perc_vs_score.png") plt.clear() x_labels = [str(idx) + "_" + str(x) + "_iter" for idx, x in enumerate(xs)] ys = [ percentiles[percentiles_ranges.index(100)][nr_iter] for nr_iter in xs ] plt.plot(x_labels, ys, '-', label="best") plt.legend(loc='upper left') plt.title("best") plt.savefig("best.png") # plt.clear() plt.plot(x_labels, no_options_show, label="no options") plt.legend(loc='upper left') plt.title("best and no options") plt.savefig("best_and_no_options.png") plt.clear() # ys = [percentiles[percentiles_ranges.index(1)][nr_iter] for nr_iter in xs] # plt.plot(x_labels, ys, label="perc:1%") # ys = [percentiles[percentiles_ranges.index(90)][nr_iter] for nr_iter in xs] # plt.plot(x_labels, ys, label="perc:90%") ys = [percentiles[percentiles_ranges.index(50)][nr_iter] for nr_iter in xs] plt.plot(x_labels, ys, label="perc:50%") plt.legend(loc='upper left') plt.title("perc:50%") plt.savefig("perc:50%.png") plt.clear() # ys = [percentiles[percentiles_ranges.index(95)][nr_iter] for nr_iter in xs] # plt.plot(x_labels, ys, label="perc:95%") ys = [percentiles[percentiles_ranges.index(99)][nr_iter] for nr_iter in xs] plt.plot(x_labels, ys, label="perc:99%") plt.legend(loc='upper left') plt.title("perc:99%") plt.savefig("perc:99%.png") plt.clear() # plt.legend(loc='upper left') # plt.show() cutoff = { nr_iter: percentiles[percentiles_ranges.index(99.9)][nr_iter] for nr_iter in xs } best_sets = {} for nr_iter in xs: best_sets[nr_iter] = [] print("best sets") for option_ids, option_scores in tqdm.tqdm(scores.items(), desc="best sets"): for iter_idx, option_score in enumerate(option_scores): nr_iter = xs_full[iter_idx] if nr_iter in xs: if option_score > cutoff[nr_iter]: best_sets[nr_iter].append((option_ids, option_score)) for nr_iter in best_sets.copy().keys(): best_sets[nr_iter].sort(key=lambda _x: -_x[1]) import pprint pprint.pprint(best_sets) import pickle with open("best_sets.txt", "wb") as fout: pickle.dump(pprint.pformat(best_sets), fout)
def plot_single_run_over_time(single_run_data, directory): plt.clear() plt.plot(single_run_data["Generation"], np.log(single_run_data["Average_Fitness"])) plt.savefig(directory + "/single_run_over_time.png")
import matplotlib.colors as colors import math print 'Script started' fig = plt.figure() ax = fig.add_subplot(111) ratio = 1.0 / 3.0 count = math.ceil(math.sqrt(len(colors.cnames))) x_count = count * ratio y_count = count / ratio x = 0 y = 0 w = 1 / x_count h = 1 / y_count print '\tStarting loop...' for c in colors.cnames: pos = (x / x_count, y / y_count) ax.add_patch(patches.Rectangle(pos, w, h, color=c)) ax.annotate(c, xy=pos) if y >= y_count - 1: x += 1 y = 0 else: y += 1 print '\tloop ended' plt.show() plt.clear('all') print 'Script finished successfully'
def _plot_x_y2(self, ix, iy1, iy2, xlabel, ylabel1, ylabel2, scatter, modes=None, fig=None, axes1=None, axes2=None, xlim=None, ylim1=None, ylim2=None, show=True, clear=False, legend=True, png_filename=None, **kwargs): """builds the plot""" self.fix() if kwargs is None: kwargs = {} modes, imodes = _get_modes_imodes(self.modes, modes) if fig is None: fig = plt.figure() gridspeci = gridspec.GridSpec(2, 4) axes1 = fig.add_subplot(gridspeci[0, :3]) axes2 = fig.add_subplot(gridspeci[1, :3], sharex=axes1) if xlim: axes1.set_xlim(xlim) if ylim1: axes1.set_ylim(ylim1) if ylim2: axes2.set_ylim(ylim2) symbols = self.symbols for i, imode, mode in zip(count(), imodes, modes): symbol = symbols[i] freq = self.results[imode, :, self.ifreq].ravel() xs = self.results[imode, :, ix].ravel() y1s = self.results[imode, :, iy1].ravel() y2s = self.results[imode, :, iy2].ravel() iplot = np.where(freq != np.nan) #iplot = np.where(freq > 0.0) axes1.plot(xs[iplot], y1s[iplot], symbol, label='Mode %i' % mode, markersize=0) axes2.plot(xs[iplot], y2s[iplot], symbol, label='Mode %i' % mode, markersize=0) if scatter: scatteri = np.linspace(.75, 50., len(xs)) #assert symbol[2] == '-', symbol axes1.scatter(xs[iplot], y1s[iplot], s=scatteri, color=symbol[0], marker=symbol[1]) axes2.scatter(xs[iplot], y2s[iplot], s=scatteri, color=symbol[0], marker=symbol[1]) axes1.grid(True) axes1.set_xlabel(xlabel) axes1.set_ylabel(ylabel1) axes2.grid(True) axes2.set_xlabel(xlabel) axes2.set_ylabel(ylabel2) title = 'Subcase %i' % self.subcase if png_filename: title += '\n%s' % png_filename fig.suptitle(title) if legend: axes1.legend(**kwargs) if show: plt.show() if png_filename: plt.savefig(png_filename) if clear: plt.clear()
def plot_single_run_over_time(single_run_data, directory): plt.clear() plt.plot(single_run_data["Generation"], np.log(single_run_data["Average_Fitness"])) plt.savefig(directory+"/single_run_over_time.png")
plt.minorticks_on() plt.grid(b=True, which='minor', alpha=0.2) #interpolations for imshow of images # https://matplotlib.org/gallery/images_contours_and_fields/interpolation_methods.html plt.imshow(image, interpolation='nearest') #marker type #https://matplotlib.org/3.1.0/api/markers_api.html # 's' = square # '.' = dot # 'x' = cross ### CLEARING CHARTS--------------------------------------- plt.cla() #clears an axis, i.e. the currently active axis in the current figure. It leaves the other axes untouched. plt.clear() #clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots. plt.close() #closes a window, which will be the current window, if not specified otherwise. hline = plt.axhline(y = line, color = "red", lw=1) hline.remove() #remove an object in the chart # remove x & y axes plt.axis('off') ### SAVE CHART IMAGE--------------------------------------- plt.plot(range(10)) plt.savefig('testplot.png', dpi=300) #save as png import Image Image.open('testplot.png').save('testplot.jgp', 'JPEG') #save as jpeg using Pillow
def hist_plot_ns(chrom_len_dict, ns_window_dict, window_size, scaffold_list): """TODO: Docstring for hist_plot_ns. :chom_len_dict: TODO :ns_window_dict: TODO :window_size: TODO :returns: TODO """ if scaffold_list == None: for chrom, val in ns_window_dict.items(): get_chrom_len = int(chrom_len_dict[chrom]) create_x_range = range(0, get_chrom_len, window_size) #Enumerate Bins correctly x_pos = [i for i, _ in enumerate(create_x_range)] print("Plotting %s" % chrom) #print(len(create_x_range)) #print(len(val)) #print(x_pos) #Titles and width x_label = "Window size of %s" % str(window_size) y_label = "N freq, max with window size (%s)" % str(window_size) title = "Distribution of Ns in %s with length %s bp" % (str(chrom), \ str(get_chrom_len)) bar_width = 0.5 #Create and show plot plt.bar(x_pos, val, bar_width) plt.xlabel(x_label) plt.ylabel(y_label) plt.title(title) #plt.xticks(rotation=90) #plt.xticks(np.arange(min(x_pos), max(x_pos)+1, 1)) creat_file_name = chrom + '_plot.pdf' plt.savefig(creat_file_name) plt.gcf().clear() #plt.show() #If given a list to work with, only pring and write the given ones elif scaffold_list != None: for chrom, val in ns_window_dict.items(): if chrom in scaffold_list: get_chrom_len = int(chrom_len_dict[chrom]) create_x_range = range(0, get_chrom_len, window_size) #Enumerate Bins correctly x_pos = [i for i, _ in enumerate(create_x_range)] print("Plotting %s" % chrom) #print(len(create_x_range)) #print(len(val)) #print(x_pos) #Titles and width x_label = "Window size of %s" % str(window_size) y_label = "N freq, max with window size (%s)" % str( window_size) title = "Distribution of Ns in %s with length %s bp" % (str(chrom), \ str(get_chrom_len)) bar_width = 0.5 #Create and show plot plt.bar(x_pos, val, bar_width) plt.xlabel(x_label) plt.ylabel(y_label) plt.title(title) #plt.xticks(rotation=90) #plt.xticks(np.arange(min(x_pos), max(x_pos)+1, 1)) creat_file_name = chrom + '_plot.pdf' plt.savefig(creat_file_name) #Clear the plot plt.clear() else: pass