def plot_threshold( ax, list_noise_x, list_noise_y, xlim, ylim, list_x, mode="flux", ): """ """ # plot for i in range(len(list_x)): noise_x = min(list_noise_x[i]) # np.median(list_noise_x[i]) noise_y = min(list_noise_y[i]) # np.median(list_noise_y[i]) color = cm.gnuplot(i / 9.) ax.plot([np.log10(noise_x * 3.0), np.log10(noise_x * 3.0)], ylim, "-", color=color, alpha=0.5) if mode == "flux": ax.plot(xlim, [np.log10(noise_y * 3.0), np.log10(noise_y * 3.0)], "-", color=color, alpha=0.5)
def plot(self, X, Y, title="Example", features_name= ["Feature 1"," Feature 2"], use_time=True ): X_aug = np.append(X, Y, axis=1) fig = plt.figure() if use_time: ax = fig.add_subplot(111, projection='3d') else: ax = fig.add_subplot(111) classes = np.unique(Y) colors = cm.gnuplot(np.linspace(0, 1, len(classes))) for clazz, c in zip(classes, colors): elementFromClass = X_aug[X_aug[:,-1] == clazz] if use_time: ax.scatter(elementFromClass[:, 0], elementFromClass[:, 1], list(range(0, elementFromClass.shape[0])), color=c, label=clazz) else: ax.scatter(elementFromClass[:, 0], elementFromClass[:, 1], color=c, label=clazz) plt.legend() if use_time: ax.set_zlabel("Time") ax.set_xlabel(features_name[0]) ax.set_ylabel(features_name[1]) #plt.xlabel(features_name[0]) #plt.ylabel(features_name[1]) plt.title(title) plt.show()
def get_colors(self, qty): qty = np.power(qty / qty.max(), 1.0 / CONTRAST) if COLORMAP == 0: rgba = cm.gray(qty, alpha=ALPHA) elif COLORMAP == 1: rgba = cm.afmhot(qty, alpha=ALPHA) elif COLORMAP == 2: rgba = cm.hot(qty, alpha=ALPHA) elif COLORMAP == 3: rgba = cm.gist_heat(qty, alpha=ALPHA) elif COLORMAP == 4: rgba = cm.copper(qty, alpha=ALPHA) elif COLORMAP == 5: rgba = cm.gnuplot2(qty, alpha=ALPHA) elif COLORMAP == 6: rgba = cm.gnuplot(qty, alpha=ALPHA) elif COLORMAP == 7: rgba = cm.gist_stern(qty, alpha=ALPHA) elif COLORMAP == 8: rgba = cm.gist_earth(qty, alpha=ALPHA) elif COLORMAP == 9: rgba = cm.spectral(qty, alpha=ALPHA) return rgba
def test_get_standard_colors_no_appending(self): # GH20726 # Make sure not to add more colors so that matplotlib can cycle # correctly. from matplotlib import cm from pandas.plotting._matplotlib.style import _get_standard_colors color_before = cm.gnuplot(range(5)) color_after = _get_standard_colors(1, color=color_before) assert len(color_after) == len(color_before) df = DataFrame(np.random.randn(48, 4), columns=list("ABCD")) color_list = cm.gnuplot(np.linspace(0, 1, 16)) p = df.A.plot.bar(figsize=(16, 7), color=color_list) assert (p.patches[1].get_facecolor() == p.patches[17].get_facecolor())
def Draw_datasamples_and_pictures(X_data, X_scaled, labels, real_classes, method, title, number, pdf, time): """ Plotataan datanäytteet sekä kuvaikkunat samaan kuvaajaan """ fig, ax = plt.subplots(figsize=(15, 10), dpi=40) Draw_example_pictures_to_figure(X_data, X_scaled, ax) Draw_datasamples_to_figure(X_scaled, labels, ax) plt.title('{} dataset with images for {} ({}/6)'.format( title, method, number), fontsize=16) plt.subplots_adjust(left=0.04, bottom=0.11, right=0.89, top=0.92, wspace=0.11, hspace=0.26) num_cls = len(list(set(labels))) markers = ['${}$'.format(i) for i in range(1, num_cls + 1)] patches = [ plt.plot([], [], marker=markers[i], color=cm.gnuplot((int(i) + 1) / num_cls), linestyle='None', label=real_classes[i])[0] for i in range(len(real_classes)) ] ax.legend(handles=patches, loc='center left', bbox_to_anchor=(1, 0.5)) ax.set_xlabel('Evaluated accuracy = {}%\ntime:{} sec'.format( round(Evaluation(X_scaled, labels), 2), round(time, 2))) pdf.savefig(plt.gcf()) plt.close(plt.gcf())
def test_get_standard_colors_no_appending(self): # GH20726 # Make sure not to add more colors so that matplotlib can cycle # correctly. from matplotlib import cm color_before = cm.gnuplot(range(5)) color_after = plotting._style._get_standard_colors( 1, color=color_before) assert len(color_after) == len(color_before) df = DataFrame(np.random.randn(48, 4), columns=list("ABCD")) color_list = cm.gnuplot(np.linspace(0, 1, 16)) p = df.A.plot.bar(figsize=(16, 7), color=color_list) assert (p.patches[1].get_facecolor() == p.patches[17].get_facecolor())
def amp_Der_compute_true_u(cb, nsamples, amp_line, pi_line, kc=1, plot=False, write=False): X = np.zeros((4)) y = np.zeros((1)) cb.Nx = 202 cb.Nt = 202 cb.line_x = np.linspace(0, cb.L, cb.Nx) cb.itmax = 250 # colors = iter(cm.gist_heat(np.arange(len(amp_line)*10))) colors = iter(cm.gnuplot(np.arange(len(amp_line) * 10))) for amp in amp_line: print("nsample(s) = %d" % nsamples) for n in range(nsamples): print("amp = %.2f \t n = %d" % (amp, n)) filename = "%.2f_init_kc%d_%d" % (amp, kc, n) uu = cb.init_u(amp, phase=np.random.choice(pi_line)) for cc in range(8): next(colors) plt.figure("Initialisation cases") plt.plot(cb.line_x, uu, color=next(colors)) plt.xlabel("X-domain") plt.ylabel("init conditions") plt.ylim((-2.1, 2.1)) plt.pause(0.01) _, abs_work = LW_solver(uu, cb.itmax, filename=filename, write=write, plot=plot) for it in range(1, cb.itmax): u_curr = np.load( osp.join(abs_work, filename + "_it%d.npy" % (it))) u_next = np.load( osp.join(abs_work, filename + "_it%d.npy" % (it + 1))) for j in range(1, len(uu) - 1): X = np.block([[X], [u_curr[j-1], u_curr[j], u_curr[j+1],\ (u_curr[j+1] - u_curr[j-1])*0.5/cb.dx]]) y = np.block([[y], [u_next[j]]]) X = np.delete(X, 0, axis=0) y = np.delete(y, 0, axis=0) return X, y
def colored_with_affinity(arr, domains, affinity=False, chr=None, cc=None): arr = np.ma.fix_invalid(arr) # PuBu colored = cm.jet(pltcol.LogNorm()(arr)) normalizer = Normalize(vmin=-1, vmax=3) non_empty_domains = remove_empty_domains(arr, topify(domains)) if affinity: doms_affinity = domains_affinity(arr, non_empty_domains) heatmap_notlog(np.clip(doms_affinity, 0, 10)) doms_affinity_log = np.log(doms_affinity) affinity_thr = np.nanmean(doms_affinity_log) + np.nanstd(doms_affinity_log) affinity_thr = np.exp(affinity_thr) affinity_thr = np.nanmean(doms_affinity) + 1 * np.nanstd(doms_affinity) affinity_normalizer = Normalize(vmin=affinity_thr, vmax=10) for i, dom in enumerate(domains): begin, end = dom.get_begin(), dom.get_end() if end - begin < DOM_THR: continue color = dom.color or BORDER_COLOR try: color_num = int(dom.color) if color_num >=0 : color = COLOR_LIST[color_num] else: color = COLORS['0'] except: pass if cc: color = COLORS[cc.get((chr, dom.color), '0')] color = colorConverter.to_rgba(color) for i in range(begin, end + 1): if i != end: colored[i, end] = color if i != begin: colored[begin, i] = color #colored[begin, begin] = colorConverter.to_rgba('black') #colored[end, end] = colorConverter.to_rgba('black') if affinity: for i, dom in enumerate(non_empty_domains): begin, end = dom.get_begin(), dom.get_end() for j, dom2 in enumerate(non_empty_domains): if j <= i: continue begin2, end2 = dom2.get_begin(), dom2.get_end() if doms_affinity[i, j] < affinity_thr: continue color = cm.gnuplot(affinity_normalizer(doms_affinity[i, j])) for k in range(begin, end + 1): colored[k, begin2] = color colored[k, end2] = color for k in range(begin2, end2 + 1): colored[begin, k] = color colored[end, k] = color return colored
def set_color(c,n): if c == "rainbow": color = cm.rainbow(n/8.) elif c == "gnuplot": color = cm.gnuplot(n/8.) elif c == "autumn": color = cm.autumn(n/8.) elif c == "cool": color = cm.cool(n/8.) return color
def Draw_datasamples_to_figure(X_scaled, labels, axis): """ Plotataan datanäytteet kuvaajaan. Datanäytteiden luokkia on kuvattu numeroin ja värein """ markers = ['${}$'.format(i) for i in labels] num_cls = len(list(set(labels))) for (X_plot, Y_plot, y, label) in zip(X_scaled[:, 0], X_scaled[:, 1], markers, labels): axis.scatter(X_plot, Y_plot, color=cm.gnuplot(int(label) / num_cls), marker=y, s=60)
def plot_convergence(Energies, coeffs, iteration): xscale = int(np.log10(MC_par['N_mcs'])) + 4 plt.figure(figsize=(xscale, 6)) cmax = np.max(coeffs) for c in coeffs: plt.plot(Energies[c], label=c, color=cm.gnuplot(c / cmax), linewidth=2) plt.xscale('log') plt.legend(loc=3) plt.xlabel('# iteration') plt.ylabel('Energy/KT') plt.figtext(0.99, 0.99, git_v, fontsize=8, ha='right', va='top') plt.savefig(out_root + 'iters_output/convergence_%03d.png' % iteration, dpi=600) plt.close('all') return
def plot3d_save_images(self, X, Y, title="Example", features_name= ["Feature 1"," Feature 2"] ): X_aug = np.append(X, Y, axis=1) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') classes = np.unique(Y) colors = cm.gnuplot(np.linspace(0, 1, len(classes))) color_classes = {} elements_class = {} for clazz, c in zip(classes, colors): elements_class[clazz] = X_aug[X_aug[:,-1] == clazz] color_classes[clazz] = c time = datetime.datetime.now().strftime("%Y%m%d%H%M%S") if not os.path.isdir("out_img/"): os.mkdir("out_img") os.mkdir('out_img/'+time) for i in range(0,int(X.shape[0]/len(classes))): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for k,v in elements_class.items(): ax.scatter(v[i][0], v[i][1], i, color=color_classes[k],label=k) # PLOTA O PONTO ANTERIOR # if i > 0: # for k,v in elements_class.items(): # ax.scatter(v[i-1][0], v[i-1][1], i-1, color=color_classes[k],label=k) # PLOTA TODOS OS PONTOS ANTERIORES AO PONTO ATUAL for k,v in elements_class.items(): ax.scatter(v[:i,0], v[:i,1], range(0,i), color=color_classes[k]) ax.set_zlabel("Time") ax.set_xlabel(features_name[0]) ax.set_ylabel(features_name[1]) ax.set_xlim(np.amin(X[:,0]*1.2),np.amax(X[:,0]*1.2)) ax.set_ylim(np.amin(X[:,1]*1.2),np.amax(X[:,1]*1.2)) ax.set_zlim([0,X.shape[0]/len(elements_class)]) plt.legend() plt.title(title) plt.savefig("out_img/"+time+"/"+str(i)+".png") plt.close(fig)
def save_animation(): w = 1 << 8 h = 1 << 8 sl = SmoothLife(h, w) sl.add_speckles() from skvideo.io import FFmpegWriter from matplotlib import cm fps = 60 frames = 100 w = FFmpegWriter("smoothlife.mp4", inputdict={"-r": str(fps)}) for i in range(frames): frame = cm.gnuplot(sl.field) frame *= 255 frame = frame.astype("uint8") w.writeFrame(frame) sl.step() w.close()
def view_sammon(self, X, Y): target = Y.flatten() [y,E] = sammon(X, maxiter=20) names = np.unique(target) colors = cm.gnuplot(np.linspace(0, 1, len(names))) for clazz, c in zip(names, colors): # Plot plt.scatter(y[target == clazz, 0], y[target == clazz, 1], s=20, c=c, label=clazz) plt.title('Sammon Plot') plt.legend(loc=2) plt.show() return y,Y.T[0]
def time_windows(n_windows, X, Time, C, ax): """ n_windows – number of time windows X – fixed relation t2/t1 Time – time-domain points array C – capacitance data """ import matplotlib.pyplot as plt from matplotlib import cm import numpy as np ax.set_ylabel('Capacitance $C, nF$') ax.set_xlabel('Time $t, s$') ax.grid(True) c = cm.gnuplot(np.linspace(0,1,len(C))) for i in range(len(C)): ax.plot(Time,C[i], c=c[i]) T1 = [] T2 = [] for j in range(1, n_windows + 1): ax.axvline(x = Time[j*1], color=str(j/n_windows), linestyle =':') T1.append(j) for i in range(len(Time)): if Time[i] >= X*Time[j*1]: ax.axvline(x = Time[i], color=str(j/n_windows), linestyle =':') T2.append(i) break #print(np.array(Time[T2])/np.array(Time[T1])) if len(T1)!=len(T2): print('!!!!!!!!!!!!!!!!!!!!!!!!!!\n'+ '!!!!!!!!!!!!!!!!!!!!!!!!!!\n'+ '!!!! Too many windows !!!!\n'+ '!!!!!!!!!!!!!!!!!!!!!!!!!!\n'+ '!!!!!!!!!!!!!!!!!!!!!!!!!!') return T1, T2
def dlts_plot(T, Time, C, T1, T2, n_windows, ax, Smooth, Bounds): import matplotlib.pyplot as plt from matplotlib import cm import numpy as np from scipy.signal import savgol_filter ax.set_ylabel(r'$\Delta C/C_0$ $arb. units$') ax.set_xlabel('Temperature $T, K$') ax.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) ax.axvspan(Bounds[0], Bounds[1], alpha=0.1, color='red') DLTS = [] for j in range(n_windows): DLTSx = [] for i in range(0, len(T)): x = (C[i][T2[j]] - C[i][T1[j]]) / C[i][-1] DLTSx.append(x) if Smooth == 1: DLTS.append(DLTSx) else: DLTS.append(savgol_filter(DLTSx, Smooth, 1)) DLTS = np.asarray(DLTS) c = cm.gnuplot(np.linspace(0, 0.9, n_windows)) for i in range(n_windows): tau = (Time[T2[i]] - Time[T1[i]]) / np.log(Time[T2[i]] / Time[T1[i]]) ax.plot(T, DLTS[i], c=c[i], label=r'$\tau = %.3f$ s' % (tau)) if n_windows <= 11: ax.legend() ax.grid(True, ls="-") plt.tight_layout() return DLTS
def result_size_dist_3d(path): fig, ax = plt.subplots(subplot_kw={'projection': '3d'}) for i, result_data_path in enumerate(path): data = np.load(result_data_path) beta = data['beta'] num_of_strings = data['num_of_strings'] L = data['L'] frames = data['frames'] Ls = data['Ls'].astype(np.float) size_dist = data['size_dist'] X, Y = np.meshgrid(Ls, range(len(size_dist[0]))) ax.plot_wireframe(X, Y, size_dist.T, rstride=1, alpha=0.3, color=cm.gnuplot(float(i) / len(path))) ax.set_title("Histogram of the size of subclusters in the region with $L$") ax.set_xlabel("$L$") ax.set_ylabel("Size of a subcluster") ax.set_zlabel("Freq") plt.show()
def plot_multi(self, fig, datafile, line_style, xformat, legendStyle, sort, loc, markeveryInp): f = open(datafile) hasErrorBar = False hash = dict() sub_plot_num = 111 for line in f: line = line.split("\t") if len(line) > 3: sub_plot_num = int(line[3].strip()) p_name = line[2].strip() # if not hash.has_key(sub_plot_num): if not sub_plot_num in hash: # Does not work in Python3 hash[sub_plot_num] = dict() if not p_name in hash[sub_plot_num]: x = list() y = list() err = list() hash[sub_plot_num][p_name] = (x, y, err) hash[sub_plot_num][p_name][0].append(line[0]) if len(line[1].split(";")) == 1: # Check for error bars hash[sub_plot_num][p_name][1].append(line[1]) hash[sub_plot_num][p_name][2].append(0) # else: hasErrorBar = True hash[sub_plot_num][p_name][1].append(line[1].split(";")[0]) # Append Y value hash[sub_plot_num][p_name][2].append(line[1].split(";")[1]) # Append Error Value f.close() subplots = list() ax1 = 0 ticks = list() sorted_hash = sorted(iter(hash.keys())) for sub_plot_num in sorted_hash: if ax1 == 0: ax = fig.add_subplot(sub_plot_num) ax1 = ax else: ax = fig.add_subplot(sub_plot_num, sharex=ax1) subplots.append(ax) plots = list() if sort == "int": sorted_names = map(lambda x: str(x), sorted(map(lambda x: int(x), hash[sub_plot_num]))) else: sorted_names = sorted(hash[sub_plot_num]) # for p_name in hash[sub_plot_num]: i = 0 cm_len = float(len(sorted_names)) y_valsStacked = list() longestStacked = 0 for p_name in sorted_names: if xformat == "cdf": y_vals = self.calc_cdf(hash[sub_plot_num][p_name][1]) x_vals = hash[sub_plot_num][p_name][0] hash[sub_plot_num][p_name][0][:0] = [0] # prepend 0 elif xformat == "ccdf": y_vals = self.calc_ccdf(hash[sub_plot_num][p_name][1]) x_vals = hash[sub_plot_num][p_name][0] # hash[sub_plot_num][p_name][0].append(x_vals[-1]) # x_vals = hash[sub_plot_num][p_name][0] elif xformat == "eccdf": # ECCDF has to update the X values as well. x_vals, y_vals = self.ecdf(hash[sub_plot_num][p_name][0], hash[sub_plot_num][p_name][1]) else: if hasErrorBar: y_vals = [float(a) for a in hash[sub_plot_num][p_name][1]] y_err = [float(a) for a in hash[sub_plot_num][p_name][2]] y_err_high = [ float(a) + float(b) for a, b in zip(hash[sub_plot_num][p_name][1], hash[sub_plot_num][p_name][2]) ] y_err_low = [ float(a) - float(b) for a, b in zip(hash[sub_plot_num][p_name][1], hash[sub_plot_num][p_name][2]) ] else: y_vals = hash[sub_plot_num][p_name][1] x_vals = hash[sub_plot_num][p_name][0] if line_style == "multi": dots = ".x+" ax.plot(x_vals, y_vals, dots[i % len(dots)], c=cm.hsv(i / cm_len, 1)) elif line_style == "multi-": dots = ["-v", "-x", "-o"] if hasErrorBar: plt.errorbar(x_vals, y_vals, fmt=dots[i % len(dots)], c=cm.hsv(i / cm_len, 1), yerr=y_err) else: ax.plot(x_vals, y_vals, dots[i % len(dots)], c=cm.hsv(i / cm_len, 1)) elif line_style == "multi--": dots = ["--v", "--x", "--o"] if hasErrorBar: # plt.errorbar(x_vals, y_vals, fmt=dots[i%len(dots)], c=cm.gnuplot(i/cm_len,1), yerr=y_err) plt.errorbar(x_vals, y_vals, fmt=dots[i % len(dots)], yerr=y_err) else: ax.plot(x_vals, y_vals, dots[i % len(dots)], c=cm.gnuplot(i / cm_len, 1)) elif line_style == "multismall-": dots = ["-", "-+", "-x"] ax.plot(x_vals, y_vals, dots[i % len(dots)], c=cm.hsv(i / cm_len, 1)) elif line_style == "multismall": dots = [".", "+", "x"] ax.plot(x_vals, y_vals, dots[i % len(dots)], c=cm.hsv(i / cm_len, 1)) elif line_style == "bnw": dots = ["h", "+", "x", "d", "v", "o", "D", "."] ax.plot(x_vals, y_vals, dots[i % len(dots)]) elif line_style == "bnw-": dots = ["-h", "-+", "-x", "-d", "-v", "-o", "-D", "-."] ax.plot(x_vals, y_vals, dots[i % len(dots)], markevery=int(markeveryInp)) # ax.plot(x_vals, y_vals, dots[i%len(dots)]) elif xformat == "stack": y = np.array(y_vals, dtype=float) y_valsStacked.append(y) if longestStacked < len(y): longestX = x_vals longestStacked = max(longestStacked, len(y)) elif xformat == "fill": ax.fill( x_vals, y_vals, line_style, edgecolor="black", hatch=self.hatches[i % len(self.hatches)], color=cm.Pastel2(i / cm_len, 1), ) else: if hasErrorBar: plt.errorbar(x_vals, y_vals, linestyle=line_style, yerr=y_err) else: ax.plot(x_vals, y_vals, line_style) plots.append(p_name) i += 1 if xformat == "stack": print longestStacked # ys = [np.array(y, dtype=float).resize(longestStacked) for y in y_valsStacked] stacks = list() y_cnt = 0 for y in y_valsStacked: y = np.copy(y) y.resize(longestStacked) print y stacks.append(y) y_cnt += 1 # ys = [np.array(y, dtype=float) for y in y_valsStacked] # ys = [y.resize(longestStacked) for y in ys] ax.stackplot(np.array(longestX, dtype=float), *stacks, baseline="wiggle") if legendStyle == "none": pass elif (legendStyle == "single" or legendStyle == "single-outside") and i > 1: pass elif legendStyle == "outside": leg = ax.legend(plots, bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.5) elif legendStyle == "below": ax.legend(plots, loc="upper center", bbox_to_anchor=(0.5, -0.15), fancybox=True, shadow=True, ncol=2) else: try: loc = int(loc) except: loc = loc finally: leg = ax.legend(plots, loc=loc) ax.grid(True) if legendStyle == "single": leg = subplots[0].legend(plots, "best") elif legendStyle == "single-outside": leg = subplots[0].legend(plots, bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.5) if xformat == "time": ax.xaxis.set_major_formatter(ticker.FuncFormatter(self.format_time)) fig.autofmt_xdate() elif xformat == "date": ax.xaxis.set_major_formatter(ticker.FuncFormatter(self.format_date)) fig.autofmt_xdate() elif xformat == "days": min_time = int(min(x)) self.start_day = min_time - min_time % 86400 ax.xaxis.set_major_formatter(ticker.FuncFormatter(self.format_days)) elif xformat == "tiny": ax.xaxis.set_major_formatter(ticker.FuncFormatter(self.format_tiny)) ax.yaxis.set_major_formatter(ticker.FuncFormatter(self.format_tiny)) # fig.autofmt_xdate() elif xformat == "dict": ax.xaxis.set_major_formatter(ticker.FuncFormatter(self.format_dict)) fig.autofmt_xdate() return subplots
def Draw_all_figures(X_data, labels, real_classes, title, params, pdf, print_pictures=True): """ Suoritetaan valitulle datajoukolle kaikilla vähentämismenetelmillä kuvaajien piirtäminen """ fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2, 3, figsize=(15, 10), dpi=40) X_data_pca, time1 = Train_model(X_data, params, 'PCA') Draw_datasamples_to_figure(X_data_pca, labels, ax1) ax1.set_title('PCA', fontsize=16) ax1.set_xlabel('Evaluated accuracy = {}%\ntime:{} sec'.format( round(Evaluation(X_data_pca, labels), 2), round(time1, 4))) print("1/6") X_data_mds, time2 = Train_model(X_data, params, 'MDS') Draw_datasamples_to_figure(X_data_mds, labels, ax2) ax2.set_title('MDS', fontsize=16) ax2.set_xlabel('Evaluated accuracy = {}%\ntime:{} sec'.format( round(Evaluation(X_data_mds, labels), 2), round(time2, 2))) print("2/6") X_data_lle, time3 = Train_model(X_data, params, 'LLE') Draw_datasamples_to_figure(X_data_lle, labels, ax3) ax3.set_title('LLE', fontsize=16) ax3.set_xlabel('Evaluated accuracy = {}%\ntime:{} sec'.format( round(Evaluation(X_data_lle, labels), 2), round(time3, 2))) print("3/6") X_data_isomap, time4 = Train_model(X_data, params, 'ISOMAP') Draw_datasamples_to_figure(X_data_isomap, labels, ax4) ax4.set_title('ISOMAP', fontsize=16) ax4.set_xlabel('Evaluated accuracy = {}%\ntime:{} sec'.format( round(Evaluation(X_data_isomap, labels), 2), round(time4, 4))) print("4/6") X_data_tsne, time5 = Train_model(X_data, params, 'TSNE') Draw_datasamples_to_figure(X_data_tsne, labels, ax5) ax5.set_title('T-SNE', fontsize=16) ax5.set_xlabel('Evaluated accuracy = {}%\ntime:{} sec'.format( round(Evaluation(X_data_tsne, labels), 2), round(time5, 2))) print("5/6") X_data_umap, time6 = Train_model(X_data, params, 'UMAP') Draw_datasamples_to_figure(X_data_umap, labels, ax6) ax6.set_title('UMAP', fontsize=16) ax6.set_xlabel('Evaluated accuracy = {}%\ntime:{} sec'.format( round(Evaluation(X_data_umap, labels), 2), round(time6, 2))) fig.suptitle("2D-visualization of {} dataset".format(title), fontsize=20) plt.subplots_adjust(left=0.04, bottom=0.11, right=0.89, top=0.92, wspace=0.11, hspace=0.26) print("6/6") num_cls = len(list(set(labels))) markers = ['${}$'.format(i) for i in range(1, num_cls + 1)] patches = [ plt.plot([], [], marker=markers[i], color=cm.gnuplot((int(i) + 1) / num_cls), linestyle='None', label=real_classes[i])[0] for i in range(len(real_classes)) ] ax3.legend(handles=patches, loc='center left', bbox_to_anchor=(1, 0.5)) pdf.savefig(plt.gcf()) plt.close(plt.gcf()) if print_pictures: Draw_datasamples_and_pictures(X_data, X_data_pca, labels, real_classes, 'PCA', title, '1', pdf, time1) Draw_datasamples_and_pictures(X_data, X_data_mds, labels, real_classes, 'MDS', title, '2', pdf, time2) Draw_datasamples_and_pictures(X_data, X_data_lle, labels, real_classes, 'LLE', title, '3', pdf, time3) Draw_datasamples_and_pictures(X_data, X_data_isomap, labels, real_classes, 'ISOMAP', title, '4', pdf, time4) Draw_datasamples_and_pictures(X_data, X_data_tsne, labels, real_classes, 'T-SNE', title, '5', pdf, time5) Draw_datasamples_and_pictures(X_data, X_data_umap, labels, real_classes, 'UMAP', title, '6', pdf, time6)
RenrichoverRvir_binned_Q1_list.append(RenrichoverRvir_binned_Q1) RenrichoverRvir_binned_Q3_list.append(RenrichoverRvir_binned_Q3) # Now plot stuff! label_list = ["2","5","10","30","100"] plt.figure(figsize=(3.54331,3.14*2)) #90 mm, 80x2 mm plt.axes([0.1, 0.12, 0.8, 0.83]) params = {"font.size": 10,'legend.fontsize': 8, 'legend.linewidth': 1}#,'figure.subplot.left':0.4,'figure.subplot.right':0.6} #'figure.subplot.left':0.2 plt.rcParams.update(params) plt.subplot(211) for i in np.arange(N_curve): plt.plot(np.log10(mbins_med)+10.,Renrich_binned_med_list[i],c=cm.gnuplot(np.int(256./N_curve*i)),label=label_list[i]) plt.fill_between(np.log10(mbins_med)+10.,Renrich_binned_Q1_list[i],Renrich_binned_Q3_list[i],alpha=0.4,color=cm.gnuplot(np.int(256./N_curve*i))) plt.legend(loc=2) plt.xlabel(r"${\rm Log}_{10}\left({\rm Mass}/(M_\odot h^{-1}) \right)$") plt.ylabel(r"$r_{\rm enrich} {\rm [pkpc]}$") plt.subplot(212) for i in np.arange(N_curve): plt.plot(np.log10(mbins_med)+10.,RenrichoverRvir_binned_med_list[i],c=cm.gnuplot(np.int(256./N_curve*i)))#,label=name_list[i]) plt.fill_between(np.log10(mbins_med)+10.,RenrichoverRvir_binned_Q1_list[i],RenrichoverRvir_binned_Q3_list[i],alpha=0.4,color=cm.gnuplot(np.int(256./N_curve*i))) plt.legend(loc=2) plt.xlabel(r"${\rm Log}_{10}\left({\rm Mass}/(M_\odot h^{-1}) \right)$") plt.ylabel(r"$r_{\rm enrich} [R_{\rm 200}]$") plt.savefig("z_thresh_fac.pdf",bbox_inches='tight')
def make_orbit_density(OrbitInstance,orbit=None,window=[0,10000],replot=False,scalelength=0.01,colorplot=True,nsamp=56,transform=True,rescale=True): ''' Makes density plot of a single orbit Parameters ----------- OrbitInstance -with transformation and polar coordinates setup. will add forcing for this at some point ''' lo = window[0] hi = window[1] if (lo) > OrbitInstance['T'].size: print('orbit.make_orbit_density: invalid lower time boundary. resizing...') lo = 0 # check size boundaries if (hi+1) > OrbitInstance['T'].size: hi = OrbitInstance['T'].size - 1 if transform: try: x_coord_tmp = OrbitInstance['TX'] y_coord_tmp = OrbitInstance['TY'] except: print('orbit.make_orbit_density: transformation must be defined in orbit dictionary.') else: x_coord_tmp = OrbitInstance['X'] y_coord_tmp = OrbitInstance['Y'] z_coord_tmp = OrbitInstance['Z'] # check if orbit instance is multidimensional try: orbit += 1 orbit -= 1 x_coord = x_coord_tmp[lo:hi,orbit] y_coord = y_coord_tmp[lo:hi,orbit] z_coord = z_coord_tmp[lo:hi,orbit] except: x_coord = x_coord_tmp[lo:hi] y_coord = y_coord_tmp[lo:hi] z_coord = z_coord_tmp[lo:hi] # undo scaling scalefac = 1./scalelength if not replot: fig = plt.figure(figsize=(6.46,4.53),dpi=100) else: plt.clf() fig = plt.gcf() # #want to re-scale the extent to make a more intelligent boundary # extentx_in = 1.2*np.max(abs(x_coord)) extenty_in = 1.2*np.max(abs(y_coord)) extentz_in = 1.2*np.max(abs(z_coord)) # xbins = np.linspace(-extentx_in,extentx_in,nsamp) ybins = np.linspace(-extenty_in,extenty_in,nsamp) xx,yy = np.meshgrid( xbins,ybins) zbins = np.linspace(-extentz_in,extentz_in,nsamp) xxz,zz = np.meshgrid( xbins,zbins) # test the kde waters try: tt = kde_3d.fast_kde_two(x_coord,y_coord,\ gridsize=(nsamp,nsamp), extents=(-extentx_in,extentx_in,-extenty_in,extenty_in),\ nocorrelation=True, weights=None) tz = kde_3d.fast_kde_two(x_coord,z_coord,\ gridsize=(nsamp,nsamp), extents=(-extentx_in,extentx_in,-extentz_in,extentz_in),\ nocorrelation=True, weights=None) except: tt = tz = np.zeros([nsamp,nsamp]) # set up the axes ax1 = fig.add_axes([0.15,0.55,0.25,0.35]) ax2 = fig.add_axes([0.52,0.55,0.25,0.35]) ax3 = fig.add_axes([0.80, 0.55, 0.03, 0.35]) ax4 = fig.add_axes([0.15,0.15,0.25,0.35]) ax5 = fig.add_axes([0.52,0.15,0.25,0.35]) if colorplot: ax6 = fig.add_axes([0.80, 0.15, 0.03, 0.35]) # _ = ax1.contourf(scalefac*xx,scalefac*yy,np.flipud(tt/np.sum(tt)),cmap=cm.Greys) _ = ax2.contourf(scalefac*xxz,scalefac*zz,np.flipud(tz/np.sum(tz)),cmap=cm.Greys) _ = ax2.set_ylabel('Z [R$_d$]') _ = ax5.set_ylabel('Z [R$_d$]') if transform: _ = ax1.set_ylabel('Y$_{\\rm bar}$ [R$_d$]') _ = ax4.set_ylabel('Y$_{\\rm bar}$ [R$_d$]') _ = ax4.set_xlabel('X$_{\\rm bar}$ [R$_d$]') _ = ax5.set_xlabel('X$_{\\rm bar}$ [R$_d$]') else: _ = ax1.set_ylabel('Y [R$_d$]') _ = ax4.set_ylabel('Y [R$_d$]') _ = ax4.set_xlabel('X [R$_d$]') _ = ax5.set_xlabel('X [R$_d$]') _ = ax1.set_xticklabels(()) _ = ax2.set_xticklabels(()) if colorplot: loT = OrbitInstance['T'][lo] hiT = OrbitInstance['T'][hi] dT = (hiT-loT)/float(hi-lo) spacing = 5 for indx in range(1,(hi-lo)+1,spacing): _ = ax4.plot(scalefac*x_coord[indx:indx+spacing+1],scalefac*y_coord[indx:indx+spacing+1],color=cm.gnuplot(indx/float(hi-lo),1.),lw=0.5) _ = ax5.plot(scalefac*x_coord[indx:indx+spacing+1],scalefac*z_coord[indx:indx+spacing+1],color=cm.gnuplot(indx/float(hi-lo),1.),lw=0.5) else: _ = ax4.plot(scalefac*x_coord,scalefac*y_coord,color='black',lw=0.5) _ = ax5.plot(scalefac*x_coord,scalefac*z_coord,color='black',lw=0.5) # double all window sizes? pfac = 1. pfacz = 1. if rescale: # allow for rescaling of the plots? # e.g. don't use this if making a library if np.max([np.max(x_coord),np.max(y_coord)]) < 0.75*scalelength: pfac = 0.5 if np.min([np.max(x_coord),np.max(y_coord)]) > 1.5*scalelength: pfac = 2. if np.min([np.max(x_coord),np.max(y_coord)]) > 2.5*scalelength: pfac = 4. if np.max(z_coord) > 0.7*scalelength: pfacz = 1.5 if np.max(z_coord) < 0.33*scalelength: pfacz = 0.5 _ = ax1.axis([-2.*pfac,2.*pfac,-2.*pfac,2.*pfac]) _ = ax4.axis([-2.*pfac,2.*pfac,-2.*pfac,2.*pfac]) _ = ax2.axis([-2.*pfac,2.*pfac,-0.8*pfacz,0.8*pfacz]) _ = ax5.axis([-2.*pfac,2.*pfac,-0.8*pfacz,0.8*pfacz]) xy_lims = [str(int(np.round(-2.*pfac,0))),str(int(np.round(-1.*pfac,0))),str(int(np.round(1.*pfac,0))),str(int(np.round(2.*pfac,0)))] xz_lims = [str(np.round(-0.8*pfacz,1)),str(np.round(-0.4*pfacz,1)),str(np.round(0.4*pfacz,1)),str(np.round(0.8*pfacz,1))] _ = ax4.set_xticklabels([xy_lims[0],'',xy_lims[1],'','0','',xy_lims[2],'',xy_lims[3]],size=12) _ = ax4.set_yticklabels([xy_lims[0],'',xy_lims[1],'','0','',xy_lims[2],'',xy_lims[3]],size=12) _ = ax1.set_yticklabels([xy_lims[0],'',xy_lims[1],'','0','',xy_lims[2],'',xy_lims[3]],size=12) _ = ax2.set_yticklabels([xz_lims[0],'',xz_lims[1],'','0','',xz_lims[2],'',xz_lims[3]],size=12) _ = ax5.set_xticklabels([xy_lims[0],'',xy_lims[1],'','0','',xy_lims[2],'',xy_lims[3]],size=12) _ = ax5.set_yticklabels([xz_lims[0],'',xz_lims[1],'','0','',xz_lims[2],'',xz_lims[3]],size=12) cmap = mpl.cm.Greys; norm = mpl.colors.Normalize(vmin=0., vmax=1.) cb1 = mpl.colorbar.ColorbarBase(ax3, cmap=cmap,norm=norm) _ = cb1.set_label('Relative Frequency',size=10) _ = cb1.set_ticks([0.,0.25,0.5,0.75,1.]) if colorplot: cmap = mpl.cm.gnuplot; norm = mpl.colors.Normalize(vmin=loT, vmax=hiT) cb1 = mpl.colorbar.ColorbarBase(ax6, cmap=cmap,norm=norm) _ = cb1.set_label('System Time',size=10) _ = cb1.set_ticks([np.round(loT,2),np.round( 0.33*(hiT-loT) + loT,2),np.round( 0.66*(hiT-loT) + loT,2),np.round( 0.98*(hiT-loT) + loT,2)])
# cut data Ico21 = Ico21_tmp_[cut_all] * co21_jy2k Ico10 = Ico10_tmp_[cut_all] * co10_jy2k r21 = Ico21 / Ico10 meds_axis.append(j + 0.5) meds_co10.append(np.median(np.log10(Ico21))) meds_co10_err.append(np.std(np.log10(Ico21))**2) meds_co21.append(np.median(np.log10(r21))) meds_co21_err.append(np.std(np.log10(r21))**2) # ax1 ax1.scatter(np.log10(Ico21), np.log10(r21), color=cm.gnuplot(j / 8.), alpha=0.1, s=20, lw=0) y1 = np.log10(np.median(Rco21[Rco21 > 0]) * co21_jy2k) ax1.plot([y1, y1], ylim, "-", c=cm.gnuplot(j / 8.), alpha=0.4) if j == 0 or j == 7: n, _ = np.histogram(np.log10(Ico21), bins=10, range=[y1, 2.5]) sy, _ = np.histogram(np.log10(Ico21), bins=10, range=[y1, 2.5], weights=np.log10(r21)) sy2, _ = np.histogram(np.log10(Ico21), bins=10,
def plot_hist_bottom( ax, list_x, statslist_x, list_beamname, xlim, xlabel, bins=60, ): """ """ # setup ax ax.tick_params(labelleft=False) ax.spines["top"].set_visible(False) ax.spines["left"].set_visible(False) ax.spines["right"].set_visible(False) ax.tick_params(top=False, left=False, right=False) ax.set_xlim(xlim) ax.set_ylim([9, 0]) ax.grid(axis="x") ax.set_xlabel(xlabel) # # plot data stats_step = [] for i in range(len(list_x)): # preparation x = np.log10(list_x[i]) beam = list_beamname[i].replace("p0", "\"") color = cm.gnuplot(i / 9.) # # histogram histo = np.histogram(x, bins=bins, range=xlim) y = np.delete(histo[1], -1) x = histo[0] / (histo[0].max() * 1.05) width = (xlim[1] - xlim[0]) / bins # # plot ax.plot(y, x + i, drawstyle="steps-mid", color="grey", lw=0.5) ax.bar(y, x, width=width, lw=0, color=color, alpha=0.4, bottom=i, align="center") # stats_step.append(i + 0.5) # ### plot stats stats_step = np.array(stats_step) p84 = np.log10(np.array(statslist_x)[:, 0]) p50 = np.log10(np.array(statslist_x)[:, 1]) p16 = np.log10(np.array(statslist_x)[:, 2]) # # plot ax.plot(p84, stats_step, "--", color="black", markeredgewidth=0, markersize=3, lw=2) ax.plot(p50, stats_step, "o-", color="black", markeredgewidth=2, markersize=7, lw=2) ax.plot(p16, stats_step, "--", color="black", markeredgewidth=0, markersize=3, lw=2)
linestyle="dashed", linewidth = 2) a00.plot([limit[0],limit[1]], [0.5,0.5], "black", linestyle="dashed", linewidth = 2) a00.plot([limit[0],limit[1]], [0.2,0.2], "black", linestyle="dashed", linewidth = 2) for i in range(len(txtfiles)): x, y, ap_size, bm_size = load_data(txtfiles[i]) a00.scatter(x, y, s=70, c=cm.gnuplot(i/8.), alpha=0.4, linewidth=0, label = str(int(bm_size))+"\"") length = limit[1] - limit[0] length2 = limit2[1] - limit2[0] a00.text(limit[0] + length*0.05, limit2[1] - length2*0.15, "b) $I_{CO(2-1),w}$ vs. $R_{21,w}$ with \n varying beam size") a00.legend(bbox_to_anchor=(1.02, -0.2), loc="upper left", ncol=2, title="Beam Size (Fixed Aperture = 20\")") ### ax1 # histogram x_ax1, y_ax1, ap_size, bm_size = load_data(txtfiles[0])
6, 8, 10, 12, 14, 16, 18, 20, ] fig = plt.figure(figsize=(8, 6)) clr = ['#1f77b4', '#ff7f0e', '#2ca02c'] for j, periodic in enumerate(['per', 'non', 'gauss']): color = iter(cm.gnuplot(np.linspace(0.95, 0.05, len(ns)))) for nidx, n in enumerate(ns): c = next(color) data = np.load('data/data2_2_' + periodic + str(n) + '.npy') ns_part, Ss = data[0], data[1] if nidx == 0: plt.plot(ns_part, Ss, '.-', color=clr[j], label=periodic) else: plt.plot( ns_part, Ss, '.-', color=clr[j], )
# False negative rate FNR = FN / (TP + FN) # False discovery rate FDR = FP / (TP + FP) # Overall accuracy ACC = (TP + TN) / (TP + FP + FN + TN) return TPR, TNR, ACC targets = [ 'RCCA', 'REICA', 'RIICA', 'RACA', 'RMCA', 'RPCA', 'REVA', 'RIVA', 'BA', 'LCCA', 'LEICA', 'LIICA', 'LACA', 'LMCA', 'LPCA', 'LEVA', 'LIVA' ] source = 'ex' portions = [0.2, 0.3, 0.4, 0.5, 0.6, 0.7] colors = cm.gnuplot(np.linspace(0, 0.5, len(targets))) fig, axes = plt.subplots(nrows=17, ncols=2, sharex=True, figsize=(10, 20), constrained_layout=False) for inx, target in enumerate(targets): sen_por = [] sdv_por = [] for portion in portions: result = cdu.get_result('fs_grid' + os.sep + target + '_ex_' + str(portion) + '_fs.csv') length = int(result.shape[0] / 10) start = 0 end = length sen = []
@author: James """ import sys import numpy as np import matplotlib.pyplot as plt import matplotlib from matplotlib import animation, cm from matplotlib.colors import ListedColormap sys.path.insert(0, r'./') import synthwave_parts as synth background = '#000000' horizon = { 'grad': cm.gnuplot(range(28)), # only take black to purple part of gradient 'dist': 18 } ground = { 'grad': cm.gnuplot(range(12)), # only black -> purple gradient 'dist': 50 } matplotlib.rcParams['axes.facecolor'] = background # key parameters perspective = (0, 5) motion_lines = 10 frames = 200 xlim = (-100, 100) ylim = (-50, 70)
def ELW_Der_compute_true_u(cb, nsamples, amp_line, pi_line, kc=1, plot=False, write=False): """ Considerant plusieurs conditions initiales, cette fonction fait evoluer ces conditions avec un solver LW. Les solutions sont ensuites concatenees en deux matrices X et y pour etre utilisees comme support d\'entrainement d\'une intelligence artificielle. Arguments : ----------- cb : nsamples : nombre de tirages pour chaque cas amp_line : np.array des amplitudes que l\'on veut considerer pour les conditions intiale ex : [0.4, 0.8, 1.2] pi_line : intervalle entre -pi/2 et pi/2 a partir duquel un dephasage est choisi aleatoirement pour chaque CI kc : (optionnel) : gere la complexite des conditions initiales, fixe a 1 plot : (optionnel) : boolen, True si l\'on veut voir l\'evolution de la CI write : (optionnel) : booleen, True si l\'on veut ecrire les champs de vitesses pour toutes les iterations """ X = np.zeros((4)) y = np.zeros((1)) cb.Nx = 202 cb.Nt = 202 cb.line_x = np.linspace(0, cb.L, cb.Nx) # cb.itmax = 250 # colors = iter(cm.gist_heat(np.arange(len(amp_line)*10))) colors = iter(cm.gnuplot(np.arange(len(amp_line) * 10))) for amp in amp_line: print("nsample(s) = %d" % nsamples) for n in range(nsamples): print("amp = %.2f \t n = %d" % (amp, n)) filename = "%.2f_init_kc%d_%d" % (amp, kc, n) uu = cb.init_u(amp, phase=np.random.choice(pi_line)) for cc in range(8): next(colors) plt.figure("Initialisation cases") plt.plot(cb.line_x, uu, color=next(colors)) plt.xlabel("X-domain") plt.ylabel("init conditions") plt.ylim((-2.1, 2.1)) plt.pause(0.01) _, abs_work = LW_solver(uu, cb.itmax, filename=filename, write=write, plot=plot) for it in range(1, cb.itmax): u_curr = np.load( osp.join(abs_work, filename + "_it%d.npy" % (it))) u_next = np.load( osp.join(abs_work, filename + "_it%d.npy" % (it + 1))) for j in range(1, len(uu) - 1): X = np.block([[X], [u_curr[j-1], u_curr[j], u_curr[j+1],\ (u_curr[j+1] - u_curr[j-1])*0.5/cb.dx]]) y = np.block([[y], [float(u_next[j] - u_curr[j]) / cb.dt]]) X = np.delete(X, 0, axis=0) y = np.delete(y, 0, axis=0) write_X_y(X, y) return X, y
def Plot_data(titles, all_datasets, all_labels, num_classes, orig_labels): """ Piirretään datajoukot viiteen pienempään kuvaajaan """ fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2, 3) st = fig.suptitle(titles[0]) num_cls = copy.deepcopy(num_classes) for i in range(len(num_classes)): if num_classes[i] > 1: num_cls[i] -= 1 for i in range(len(all_labels)): if num_classes[i] == len(list(set(orig_labels[i]))): all_labels[i] = Choose_best_color(all_labels[i], orig_labels[i]) for i in range(len(all_labels[0])): ax1.scatter(all_datasets[0][i, 0], all_datasets[0][i, 1], c=[cm.gnuplot(all_labels[0][i] / (num_cls[0]))], s=7, marker='o') for i in range(len(all_labels[1])): ax2.scatter(all_datasets[1][i, 0], all_datasets[1][i, 1], c=[cm.gnuplot(all_labels[1][i] / (num_cls[1]))], s=7, marker='o') for i in range(len(all_labels[2])): ax3.scatter(all_datasets[2][i, 0], all_datasets[2][i, 1], c=[cm.gnuplot(all_labels[2][i] / (num_cls[2]))], s=7, marker='o') for i in range(len(all_labels[3])): ax4.scatter(all_datasets[3][i, 0], all_datasets[3][i, 1], c=[cm.gnuplot(all_labels[3][i] / (num_cls[3]))], s=7, marker='o') for i in range(len(all_labels[4])): ax5.scatter(all_datasets[4][i, 0], all_datasets[4][i, 1], c=[cm.gnuplot(all_labels[4][i] / (num_cls[4]))], s=7, marker='o') ax1.set_title(titles[1]) ax2.set_title(titles[2]) ax3.set_title(titles[3]) ax4.set_title(titles[4]) ax5.set_title(titles[5]) ax1.set_xlabel('Accuracy = {}%'.format( accuracy(all_labels[0], orig_labels[0]))) ax2.set_xlabel('Accuracy = {}%'.format( accuracy(all_labels[1], orig_labels[1]))) ax3.set_xlabel('Accuracy = {}%'.format( accuracy(all_labels[2], orig_labels[2]))) ax4.set_xlabel('Accuracy = {}%'.format( accuracy(all_labels[3], orig_labels[3]))) ax5.set_xlabel('Accuracy = {}%'.format( accuracy(all_labels[4], orig_labels[4]))) ax6.set_visible(False) fig.tight_layout() st.set_y(0.95) fig.subplots_adjust(top=0.85)
def get_random_plot(name, direc): """ Random plot generation method. Inputs: name: (string) name of the plot which will be saved. Outputs: ax : (matplotlib obj) Matplotlib object of the axes of the plot fig : (matplotlib obj) Matplotlib object of the figure of the plot x, y : (list, list) Actuall x and y coordinates of the points. s : (list) sizes of the points. categories : (list) categories of the points. tick_size : (list) Tick size on the plot. [width, length] axes_x_pos, axes_y_pos: (float, float) Position of the labels of the axis. """ # PLOT STYLE style = random.choice(styles) plt.style.use(style) # POINT DISTRIBUTION distribution = random.choice(point_dist) # RESOLUTION AND TICK SIZE dpi = int(dpi_min + np.random.rand(1)[0] * (dpi_max - dpi_min)) figsize = (figsize_min + np.random.rand(2) * (figsize_max - figsize_min)).astype(int) tick_size = [(tick_size_width_min + np.random.rand(1)[0] * (tick_size_width_max - tick_size_width_min)), (tick_size_length_min + np.random.rand(1)[0] * (tick_size_length_max - tick_size_length_min))] tick_size.sort() fig, ax = plt.subplots(figsize=figsize, dpi=dpi) # ACTUAL POINTS points_nb = int(points_nb_min + (np.random.rand(1)[0]**1.5) * (points_nb_max - points_nb_min)) #print points_nb x_scale = int(x_min_top + np.random.rand(1)[0] * (x_max_top - x_min_top)) #print x_scale y_scale = int(y_min_top + np.random.rand(1)[0] * (y_max_top - y_min_top)) #print y_scale x_scale_range = x_scale + int(np.random.rand(1)[0] * x_scale_range_max) #print x_scale_range y_scale_range = y_scale + int(np.random.rand(1)[0] * y_scale_range_max) #print y_scale_range x_min = (-np.random.rand(1)[0] + np.random.rand(1)[0]) * 10**(x_scale) x_max = (-np.random.rand(1)[0] + np.random.rand(1)[0]) * 10**(x_scale_range) x_min, x_max = min(x_min, x_max), max(x_min, x_max) y_min = (-np.random.rand(1)[0] + np.random.rand(1)[0]) * 10**(y_scale) y_max = (-np.random.rand(1)[0] + np.random.rand(1)[0]) * 10**(y_scale_range) y_min, y_max = min(y_min, y_max), max(y_min, y_max) if distribution == 'uniform': x = x_min + np.random.rand(points_nb) * (x_max - x_min) y = y_min + np.random.rand(points_nb) * (y_max - y_min) elif distribution == 'linear': x = x_min + np.random.rand(points_nb) * (x_max - x_min) y = x * (max(y_max, -y_min) / (max(x_max, -x_min))) * random.choice( [-1.0, 1.0]) + (y_min + np.random.rand(points_nb) * (y_max - y_min)) * np.random.rand(1)[0] / 2.0 elif distribution == 'quadratic': x = x_min + np.random.rand(points_nb) * (x_max - x_min) y = x**2 * (1.0 / (max(x_max, -x_min)))**2 * max( y_max, -y_min) * random.choice( [-1.0, 1.0]) + (y_min + np.random.rand(points_nb) * (y_max - y_min)) * np.random.rand(1)[0] / 2.0 # POINTS VARIATION nb_points_var = 1 + int(np.random.rand(1)[0] * max_points_variations) nb_points_var_colors = 1 + int(np.random.rand(1)[0] * nb_points_var) nb_points_var_markers = 1 + int( np.random.rand(1)[0] * (nb_points_var - nb_points_var_colors)) nb_points_var_size = max( 1, 1 + nb_points_var - nb_points_var_colors - nb_points_var_markers) rand_color_number = np.random.rand(1)[0] if rand_color_number <= 0.5: colors = cm.rainbow(np.random.rand(nb_points_var_colors)) elif rand_color_number > 0.5 and rand_color_number <= 0.7: colors = cm.gnuplot(np.random.rand(nb_points_var_colors)) elif rand_color_number > 0.7 and rand_color_number <= 0.8: colors = cm.copper(np.random.rand(nb_points_var_colors)) else: colors = cm.gray(np.linspace(0, 0.6, nb_points_var_colors)) s_set = (size_points_min + np.random.rand(nb_points_var_size) * (size_points_max - size_points_min))**2 markers_subset = list(np.random.choice(markers, size=nb_points_var_markers)) markers_empty = np.random.rand(1)[0] > 0.75 markers_empty_ratio = random.choice([0.0, 0.5, 0.7]) # BUILDING THE PLOT s = [] categories = [] cat_dict = {} index_cat = 0 for _x, _y, in zip(x, y): s_ = random.choice(s_set) c_ = random.choice(colors) m_ = random.choice(markers_subset) if m_ in markers_with_full and markers_empty: e_ = np.random.rand(1)[0] > markers_empty_ratio else: e_ = False cat = [s_, c_, m_, e_] if cat_in_dict(cat, cat_dict) is False: cat_dict[index_cat] = cat index_cat += 1 categories.append(cat_in_dict(cat, cat_dict)) s.append(s_) if e_: plt.scatter(_x, _y, s=s_, color=c_, marker=m_, facecolors='none') else: plt.scatter(_x, _y, s=s_, color=c_, marker=m_) # PAD BETWEEN TICKS AND LABELS #labs = [item.get_text() for item in ax.get_xticklabels()] #print labs pad_x = max(tick_size[1] + 0.5, int(pad_min + np.random.rand(1)[0] * (pad_max - pad_min))) pad_y = max(tick_size[1] + 0.5, int(pad_min + np.random.rand(1)[0] * (pad_max - pad_min))) direction_ticks_x = random.choice(direction_ticks) direction_ticks_y = random.choice(direction_ticks) # NON-DEFAULT TICKS PROB, WITH THRESHOLD OF 0.6 weid_ticks_prob = np.random.rand(1)[0] # TICKS STYLE AND LOCATION (X AXIS) if np.random.rand(1)[0] > 0.5: axes_x_pos = 1 ax.xaxis.tick_top() ax.xaxis.set_label_position("top") if weid_ticks_prob > 0.6: ax.xaxis.set_tick_params(width=tick_size[0], length=tick_size[1], color='black', pad=pad_x, direction=direction_ticks_x, bottom=np.random.rand(1)[0] > 0.5, top=True) else: ax.xaxis.set_tick_params(bottom=np.random.rand(1)[0] > 0.5, top=True) if np.random.rand(1)[0] > 0.5: ax.spines['bottom'].set_visible(False) ax.xaxis.set_tick_params(bottom=False) if np.random.rand(1)[0] > 0.5: axes_x_pos = np.random.rand(1)[0] ax.spines['top'].set_position(('axes', axes_x_pos)) else: axes_x_pos = 0 if weid_ticks_prob > 0.6: ax.xaxis.set_tick_params(width=tick_size[0], length=tick_size[1], color='black', pad=pad_x, direction=direction_ticks_x, bottom=True, top=np.random.rand(1)[0] > 0.5) else: ax.xaxis.set_tick_params(bottom=True, top=np.random.rand(1)[0] > 0.5) if np.random.rand(1)[0] > 0.5: ax.spines['top'].set_visible(False) ax.xaxis.set_tick_params(top=False) if np.random.rand(1)[0] > 0.5: axes_x_pos = np.random.rand(1)[0] ax.spines['bottom'].set_position(('axes', axes_x_pos)) # TICKS STYLE AND LOCATION (Y AXIS) if np.random.rand(1)[0] > 0.5: axes_y_pos = 1 ax.yaxis.tick_right() ax.yaxis.set_label_position("right") if weid_ticks_prob > 0.6: ax.yaxis.set_tick_params(width=tick_size[0], length=tick_size[1], color='black', pad=pad_y, direction=direction_ticks_y, left=np.random.rand(1)[0] > 0.5, right=True) else: ax.yaxis.set_tick_params(left=np.random.rand(1)[0] > 0.5, right=True) if np.random.rand(1)[0] > 0.5: ax.spines['left'].set_visible(False) ax.yaxis.set_tick_params(left=False) if np.random.rand(1)[0] > 0.5: axes_y_pos = np.random.rand(1)[0] ax.spines['right'].set_position(('axes', axes_y_pos)) else: axes_y_pos = 0 if weid_ticks_prob > 0.6: ax.yaxis.set_tick_params(width=tick_size[0], length=tick_size[1], color='black', pad=pad_y, direction=direction_ticks_y, left=True, right=np.random.rand(1)[0] > 0.5) else: ax.yaxis.set_tick_params(left=True, right=np.random.rand(1)[0] > 0.5) if np.random.rand(1)[0] > 0.5: ax.spines['right'].set_visible(False) ax.yaxis.set_tick_params(right=False) if np.random.rand(1)[0] > 0.5: axes_y_pos = np.random.rand(1)[0] ax.spines['left'].set_position(('axes', axes_y_pos)) # LABEL ROTATION if np.random.rand(1)[0] > 0.77: plt.xticks(rotation=int(np.random.rand(1)[0] * 90)) if np.random.rand(1)[0] > 0.77: plt.yticks(rotation=int(np.random.rand(1)[0] * 90)) # SUB-TICKs if weid_ticks_prob > 0.6: color_subtick = random.choice(color_subtick_list) length_subtick = 0.75 * np.random.rand(1)[0] * tick_size[1] if np.random.rand(1)[0] > 0.7: minorLocator = AutoMinorLocator() ax.xaxis.set_minor_locator(minorLocator) ax.xaxis.set_tick_params(which='minor', length=length_subtick, direction=direction_ticks_x, color=color_subtick, bottom=ax.spines['bottom'].get_visible(), top=ax.spines['top'].get_visible()) if np.random.rand(1)[0] > 0.7: minorLocator = AutoMinorLocator() ax.yaxis.set_minor_locator(minorLocator) ax.yaxis.set_tick_params(which='minor', length=length_subtick, direction=direction_ticks_y, color=color_subtick, left=ax.spines['left'].get_visible(), right=ax.spines['right'].get_visible()) # FONT AND SIZE FOR LABELS (tick labels, axes labels and title) font = random.choice(font_list) size_ticks = int(tick_label_size_min + np.random.rand(1)[0] * (tick_label_size_max - tick_label_size_min)) size_axes = int(axes_label_size_min + np.random.rand(1)[0] * (axes_label_size_max - axes_label_size_min)) size_title = int(title_size_min + np.random.rand(1)[0] * (title_size_max - title_size_min)) ticks_font = font_manager.FontProperties(fname=font, style='normal', size=size_ticks, weight='normal', stretch='normal') axes_font = font_manager.FontProperties(fname=font, style='normal', size=size_axes, weight='normal', stretch='normal') title_font = font_manager.FontProperties(fname=font, style='normal', size=size_title, weight='normal', stretch='normal') # TEXTS FOR AXIS LABELS AND TITLE label_x_length = int(axes_label_length_min + np.random.rand(1)[0] * (axes_label_length_max - axes_label_length_min)) #print label_x_length label_y_length = int(axes_label_length_min + np.random.rand(1)[0] * (axes_label_length_max - axes_label_length_min)) title_length = int(title_length_min + np.random.rand(1)[0] * (title_length_max - title_length_min)) x_label = ("".join([ random.choice(string.ascii_letters + ' ') for i in range(label_x_length) ])).strip() #print x_label y_label = ("".join([ random.choice(string.ascii_letters + ' ') for i in range(label_y_length) ])).strip() title = ("".join([ random.choice(string.ascii_letters + ' ') for i in range(title_length) ])).strip() plt.xlabel(x_label, fontproperties=axes_font) plt.ylabel(y_label, fontproperties=axes_font, color='black') if axes_x_pos == 1: plt.title(title, fontproperties=title_font, color='black', y=1.1) else: plt.title(title, fontproperties=title_font, color='black') for label in ax.get_xticklabels(): label.set_fontproperties(ticks_font) for label in ax.get_yticklabels(): label.set_fontproperties(ticks_font) # GRID if np.random.rand(1)[0] > 0.7: plt.grid(b=True, which='major', color=random.choice(color_grid), linestyle=random.choice(linestyles)) # AXIS LIMITS xmin = min(x) xmax = max(x) deltax = 0.05 * abs(xmax - xmin) plt.xlim(xmin - deltax, xmax + deltax) ymin = min(y) ymax = max(y) deltay = 0.05 * abs(ymax - ymin) plt.ylim(ymin - deltay, ymax + deltay) # BACKGROUND AND PATCH COLORS if np.random.rand(1)[0] > 0.75: color_bg = (1 - colorbg_transparant_max ) + colorbg_transparant_max * np.random.rand(3) ax.set_axis_bgcolor(color_bg) if np.random.rand(1)[0] > 0.75: color_bg = (1 - colorbg_transparant_max ) + colorbg_transparant_max * np.random.rand(3) fig.patch.set_facecolor(color_bg) # MAKE SURE THE PLOT FITS INSIDE THE FIGURES try: plt.tight_layout() plt.savefig("./data/{}/".format(direc) + name, dpi='figure', facecolor=fig.get_facecolor()) except RuntimeError: pass return ax, fig, x, y, s, categories, tick_size, axes_x_pos, axes_y_pos
plt.savefig( "/Users/saito/data/phangs/co_ratio/eps/f05c_r21_median_vs_bm_n4321.png", dpi=100) # plot 2 data = np.loadtxt(dir_data + "bm_vs_ap_r21_median.txt") plt.figure(figsize=(10, 8)) plt.rcParams["font.size"] = 18 for i in range(16): r21_tmp = data[data[:, 0] == 4 + i * 2] r21 = r21_tmp[r21_tmp[:, 1].argsort(), :] plt.plot(r21[:, 1] * scale, r21[:, 3], linewidth=2, c=cm.gnuplot(i / 15.), marker="o", alpha=0.6) plt.scatter( [ 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100 ], np.array([4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32]) * scale, c=np.array([4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32]) * scale, cmap="gnuplot") cbar = plt.colorbar()
def plot_hmm(s_seq, e_seq, **kargs): n = e_seq.shape[0] if 'time' in kargs: X = kargs['time'] else: X = numpy.arange(n) Y0 = numpy.zeros(n) Y1 = numpy.ones(n) fig, ax = plt.subplots() ax.set_aspect('equal') plt.xlim(numpy.amin(X) - 1, numpy.amax(X) + 1), plt.xticks([]) plt.ylim(-2, 3), plt.yticks([]) e_num = numpy.amax(e_seq) + 1 s_num = numpy.amax(s_seq) + 1 last_time = X[0] - 1 for (x, y, c) in zip(X, Y1, s_seq): plt.annotate(c, xy=(x, y), xycoords='data', xytext=(-5, -5), textcoords='offset points', fontsize=16) ax.add_artist( plt.Circle((x, y), 0.3, color=cm.gnuplot(c / s_num), alpha=0.4)) ax.arrow(last_time + 0.3, y, -0.7 + (x - last_time), 0, head_width=0.35, head_length=0.1, fc='k', ec='k') ax.arrow(x, y - 0.3, 0, -0.3, head_width=0.35, head_length=0.1, fc='k', ec='k') last_time = x for (x, y, c) in zip(X, Y0, e_seq): ax.add_artist( plt.Circle((x, y), 0.3, color=cm.gnuplot(0.9 * c / e_num + 0.1), alpha=0.7)) plt.annotate(c, xy=(x, y), xycoords='data', xytext=(-5, -5), textcoords='offset points', fontsize=16) plt.show()
def plot_scatter( ax, axb, list_x, list_y, snr_x, snr_y, list_beamname, xlim, ylim, xlabel, ylabel, text, galname, txtfile, ncol=1, annotation="flux", ): """ """ ### setup ax ax.tick_params(labelbottom=False) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.grid(axis="both") ax.set_ylabel(ylabel) # axb.tick_params(labelbottom=False, labelleft=False) axb.set_xlim(xlim) axb.set_ylim(ylim) axb.set_xlabel(xlabel) # ### plot data list_output = [] for i in range(len(list_x)): # preparation x = np.log10(list_x[i]) y = np.log10(list_y[i]) sigmay = np.log10(snr_y[i]) beam = str(int(float(list_beamname[i].replace("p", ".")))) + "\"" color = cm.gnuplot(i / 9.) binrange = [x.min(), x.max()] # # correlation coefficient #coeff = str(np.round(np.corrcoef(x, y)[0,1], 2)) coeff = pearsonr(x, y) #err_coeff = str(np.round((1 - float(coeff)**2) / float(len(x)), 4)) # fit popt, pcov = curve_fit(func1, x, y, p0=[1.0, 0.0], maxfev=10000, sigma=sigmay) slope = str(np.round(popt[0], 2)) inter = str(np.round(popt[1], 2)) err_slope = str(np.round(np.sqrt(np.diag(pcov))[0], 2)) err_inter = str(np.round(np.sqrt(np.diag(pcov))[1], 2)) # beam, coeff, slope, err_slope, inter, err_inter print(beam + ", coeff = " + str(coeff[0]) + ", slope = " + slope + " $\pm$ " + err_slope + ", inter = " + inter + " $\pm$ " + err_inter) list_output.append([ float(list_beamname[i].replace("p", ".")), np.round(coeff[0], 2), np.round(coeff[1], 5), np.round(popt[0], 2), np.round(np.sqrt(np.diag(pcov))[0], 2), np.round(popt[1], 2), np.round(np.sqrt(np.diag(pcov))[1], 2) ]) # # plot ax.scatter(x, y, color=color, alpha=0.4, s=20, lw=0, label=beam) # + ' ($\\rho$ = ' + coeff + ")") if i == 0: binx, mean, std = get_binned_dist(x, y, binrange) ax.errorbar(binx, mean, yerr=std, color="dimgrey", ecolor="dimgrey", lw=4) # # plot error bar mean_snr_x = np.mean(snr_x[i]) mean_snr_y = np.mean(snr_y[i]) posx = xlim[0] + (xlim[1] - xlim[0]) * 0.6 + i * 0.13 posy = ylim[1] - (ylim[1] - ylim[0]) * 0.9 # bar_right = np.log10(10**posx + 10**posx / mean_snr_x) bar_left = np.log10(10**posx - 10**posx / mean_snr_x) bar_top = np.log10(10**posy + 10**posy / mean_snr_y) bar_bottom = np.log10(10**posy - 10**posy / mean_snr_y) ax.plot([bar_left, bar_right], [posy, posy], color=color, lw=2, zorder=1) ax.plot([posx, posx], [bar_top, bar_bottom], color=color, lw=2, zorder=1) #r = patches.Rectangle(xy=(posx, posy), width=1.0, heights=0.25, ec='#000000') # # plot annotation if annotation == "flux": ax.plot(xlim, ylim, "--", color="black", lw=3, alpha=0.7) # x_line2 = [np.log10(1 / 0.7 * 10**xlim[0]), xlim[1]] y_line2 = [ylim[0], np.log10(0.7 * 10**ylim[1])] ax.plot(x_line2, y_line2, "--", color="grey", lw=1, alpha=0.9) # x_line3 = [np.log10(1 / 0.4 * 10**xlim[0]), xlim[1]] y_line3 = [ylim[0], np.log10(0.4 * 10**ylim[1])] ax.plot(x_line3, y_line3, "--", color="grey", lw=1, alpha=0.9) # # # plot text ax.text(xlim[0] + (xlim[1] - xlim[0]) * 0.1, ylim[1] - (ylim[1] - ylim[0]) * 0.08, text, backgroundcolor="white") ax.text(xlim[0] + (xlim[1] - xlim[0]) * 0.1, ylim[1] - (ylim[1] - ylim[0]) * 0.14, galname, backgroundcolor="white") if "628" in galname: ax.text(xlim[0] + (xlim[1] - xlim[0]) * 0.04, ylim[1] - (ylim[1] - ylim[0]) * 0.89, "1:1", rotation=45, fontsize=12) ax.text(xlim[0] + (xlim[1] - xlim[0]) * 0.14, ylim[1] - (ylim[1] - ylim[0]) * 0.89, "1:0.7", rotation=45, fontsize=12) ax.text(xlim[0] + (xlim[1] - xlim[0]) * 0.23, ylim[1] - (ylim[1] - ylim[0]) * 0.89, "1:0.4", rotation=45, fontsize=12) elif annotation == "ratio": ax.plot(xlim, [0, 0], "--", color="black", lw=3, alpha=0.7) # x_line2 = [xlim[0], xlim[1]] y_line2 = [np.log10(0.7), np.log10(0.7)] ax.plot(x_line2, y_line2, "--", color="grey", lw=1, alpha=0.9) # x_line3 = [xlim[0], xlim[1]] y_line3 = [np.log10(0.4), np.log10(0.4)] ax.plot(x_line3, y_line3, "--", color="grey", lw=1, alpha=0.9) # # plot text ax.text(xlim[0] + (xlim[1] - xlim[0]) * 0.1, ylim[1] - (ylim[1] - ylim[0]) * 0.08, text, backgroundcolor="white") ax.text(xlim[0] + (xlim[1] - xlim[0]) * 0.1, ylim[1] - (ylim[1] - ylim[0]) * 0.14, galname, backgroundcolor="white") if "628" in galname: ax.text(xlim[0] + (xlim[1] - xlim[0]) * 0.06, ylim[1] - (ylim[1] - ylim[0]) * 0.42, "1.0", fontsize=12) ax.text(xlim[0] + (xlim[1] - xlim[0]) * 0.06, ylim[1] - (ylim[1] - ylim[0]) * 0.49, "0.7", fontsize=12) ax.text(xlim[0] + (xlim[1] - xlim[0]) * 0.06, ylim[1] - (ylim[1] - ylim[0]) * 0.61, "0.4", fontsize=12) # # set legend ax.legend(bbox_to_anchor=(1.05, -0.05), loc="upper left", ncol=ncol) # save txt os.system("rm -rf " + txtfile) np.savetxt(txtfile, np.array(list_output), fmt='%.2f')
def plot_hist_right( ax, axb, list_y, statslist_y, list_beamname, ylim, ylabel, bins=60, ): """ """ ### setup ax ax.tick_params(labelbottom=False, labelleft=False) ax.spines["top"].set_visible(False) ax.spines["left"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.tick_params(top=False, left=False, bottom=False) ax.set_ylim(ylim) ax.grid(axis="y") # axb.tick_params(labelbottom=False) axb.spines["top"].set_visible(False) axb.spines["left"].set_visible(False) axb.spines["bottom"].set_visible(False) axb.tick_params(top=False, left=False, bottom=False) axb.set_ylim(ylim) axb.set_ylabel(ylabel) # ### plot data stats_step = [] for i in range(len(list_y)): # preparation y = np.log10(list_y[i]) beam = list_beamname[i].replace("p0", "\"") color = cm.gnuplot(i / 9.) # # histogram histo = np.histogram(y, bins=bins, range=ylim) x = np.delete(histo[1], -1) y = histo[0] / (histo[0].max() * 1.05) height = (ylim[1] - ylim[0]) / bins # # plot ax.plot(y + i, x, drawstyle="steps", color="grey", lw=0.5) ax.barh(x, y, height=height, lw=0, color=color, alpha=0.4, left=i) # stats_step.append(i + 0.5) # ### plot stats stats_step = np.array(stats_step) p84 = np.log10(np.array(statslist_y)[:, 0]) p50 = np.log10(np.array(statslist_y)[:, 1]) p16 = np.log10(np.array(statslist_y)[:, 2]) # # plot ax.plot(stats_step, p84, "--", color="black", markeredgewidth=0, markersize=3, lw=2, label="84% and 16%") ax.plot(stats_step, p50, "o-", color="black", markeredgewidth=2, markersize=7, lw=2, label="Median") ax.plot(stats_step, p16, "--", color="black", markeredgewidth=0, markersize=3, lw=2) # ax.legend()