def _draw_resource( plt: "matplotpib.axes.Axes", # type: ignore # noqa: F821 xaxis: List[float], reports: List[PerformanceReport], resources_range: List[int], title: str, ) -> None: """ Draw a plot for specific resource. :param plt: a subplot to draw on :param xaxis: list of values for x axis :param reports: performance reports to get values from :param resources_range: list of resource ids in performance.resource list to draw values for :param title: title for chart. :return: None """ for r in resources_range: res = reports[0].resources[r] label = res.name plt.plot(xaxis, [i.resources[r].value for i in reports], label=label) plt.set_ylabel(res.unit) plt.set_title(title) plt.legend()
def show_line_chart_for_pr_rejection_rates_over_time( pulls, based_on_devstats_data=False, companies=[]): pulls = pulls.dropna(subset=["created_at", "closed_at"]) if based_on_devstats_data: pulls = p.determine_company_for_issues_with_history(pulls) pulls['company'] = np.where(pulls['company'].isin(companies), pulls['company'], 'unknown') else: users = c.get_issue_authors_with_company("kubernetes", "kubernetes") pulls = p.merge_issues_with_company_column(pulls, users) pulls["company"].fillna("others", inplace=True) pulls = p.add_dummy_column_for_rounded_year(pulls) # pulls = p.add_dummy_column_for_month(pulls) pulls = p.add_dummy_column_for_pr_merge_state(pulls) # companies = set(pulls["company"].values) # _normalized_stacked_chart(pulls, "company", "month", "line") df = pulls.groupby(["company", "year"])["pr_is_merged"].mean().unstack(level=0) print(df) plt = df.plot(kind="line") plt.set_ylabel("acceptance rate") plt.set_title("PR Acceptance Rate over the Community Lifetime", fontsize=10)
def plot_graph(self): self.ui.tempGraph.plot(self.idx_list, self.temp_list) plt = self.ui.tempGraph.canvas.ax self.ui.tempGraph.canvas.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 plt.savefig('Temperature.png' ) #Saves the plots to be pulled up on the HTML 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 self.ui.humGraph.canvas.clear() plt2.set_xlabel('Latest 10 values') plt2.set_ylabel('Humidity (%)') plt2.set_title('Humidity') #| Average = {0:0.1f} %.format(self.avgH) plt2.savefig( 'Humidity.png') #Saves the plots to be pulled up on the HTML self.ui.humGraph.canvas.draw()
def plot_training_score_cmap(training_history, num_ticks, show=True, init=True): if init: plt.gcf().init() #print('Availible variables to plot: {}'.format(training_history.training_history.keys())) epochs = len(training_history['loss']) # Visualize the plot, to be applied after traing is complete plot_cmap(plt,range(1,epochs+1), training_history['loss'], 'Blues', max(training_history['loss'] + [1]), reverse=True) plot_cmap(plt,range(1,epochs+1), training_history['val_loss'], 'Greens', max(training_history['val_loss'] + [1]), reverse=True) plt.legend(['Training loss is blue', 'Validation loss is green']) plt.set_xlabel('epochs') plt.set_ylabel('loss') plt.xticks(range(2,epochs + 1, int(epochs/num_ticks))) plt.title('Loss of training set vs validation set') plt.show() plot_cmap(plt,range(1,epochs+1), training_history['acc'], 'Blues', 1, reverse=True) plot_cmap(plt,range(1,epochs+1), training_history['val_acc'], 'Greens', 1, reverse=True) plt.legend(['Training accuracy is blue', 'Validation accuracy is green']) plt.set_xlabel('epochs') plt.set_ylabel('accuracy') plt.xticks(range(2,epochs + 1, int(epochs/num_ticks))) plt.title('Accuracy of training set vs validation set') if show: plt.show() return plt
def graph_time_func(func, t_start=0, t_end=10, steps=100): t_steps = np.linspace(t_start, t_end, steps) x, y = np.split(np.array([func(t) for t in t_steps]), 2, 1) plt.plot(x, y) plt.set_xlabel("x(t)") plt.set_ylabel("y(t)") plt.show()
def set_data(ax, title, x, y): plt.title(title, fontsize=13) plt.set_xlabel(x, fontsize=12) plt.set_ylabel(y, fontsize=12) #set the figure size sns.set(rc={'figure.figsize': (6, 4)}) sns.set_style("whitegrid")
def plot_bar_pdf(self): """Function to plot the data and a plot of the probability density function along the same range Args: n_spaces (int): number of data points Returns: list: x values for the pdf plot list: y values for the pdf plot """ x = [] y = [] # calculate the x values to visualize for k in range(self.n + 1): x.append(k) y.append(self.pdf(k)) # make the plots plt.bar(x, y) plt.set_title('Binomial Distribution for \n Sample with p probability') plt.set_ylabel('Probability') plt.set_xlabel('Outcome') plt.show() return x, y # write a method to output the sum of two binomial distributions. Assume both distributions have the same p value. """Function to add together two Binomial distributions with equal p
def Histo(self,std,stderr,P,orient='horizontal',xlabel='',ylabel=''): ''' Function that plot the histogramm of the distribution given in x imputs: -x is the distrib itself (array) -mean is the mean of the distrib (float) -sigma_mean : the error on the average (float) -std : the standard deviation (RMS) of the distribution (float) -stderr : the errot on the RMS (float) -P is the figure where the histogram will be plotted. -xylabel and y label are the name ofthe axis. ''' numBins = 20 plt.hist(self.X,numBins,color='blue',alpha=0.8,orientation=orient,label='average = ' + str("%.5f" % np.mean(self.X)) + '$\pm$' + str("%.5f" % self.MEANerr()) + '\n' + 'rms =' + str("%.5f" % self.rms()) + '$\pm$' +str("%.5f" % self.RMSerr())) if xlabel == '': plt.set_xlabel('number of SNe') else: plt.set_xlabel(xlabel) if ylabel == '': plt.set_ylabel('number of SNe') else: plt.set_ylabel(ylabel) plt.set_title('Residuals') plt.legend(bbox_to_anchor=(0.95, 1.0),prop={'size':10})
def plot_expand_results_var(random, ez, we, plt): diffs = [d - SIZE for d in TEST_SIZES[::-1]] plt.title.set_text('Variational Difference for WeakExpand') l1 = plt.plot(diffs, random[::-1], linestyle="dashed", color="red", marker="o", label='Random Replacement')[0] l2 = plt.plot(diffs, ez[::-1], linestyle="dashed", color="blue", marker="^", label='Zero Replacement')[0] l3 = plt.plot(diffs, we[::-1], linestyle="dashed", color="green", marker="o", label='WeakExpand')[0] # plt.plot([d for d in diffs][::-1], rand_select, label="Minimum Weight") plt.set_xlabel('Neuron Delta') plt.set_ylabel('Norm of Difference in Activation') return [l1, l2, l3]
def plotter (xs, ys): xs = np.asarray(xs) trend = np.polyfit(xs, ys, 1) # fit a straight line plt.set_xlabel('Article Index') plt.set_ylabel(ys) plt.plot(xs, ys,'o') plt.plot(xs,trend[1]+trend[0]*xs)
def draw_twitter_dupicate(plt): f = open("../compare/avg_degree/dup_Twitter_Mhrw.txt", "r") try: _x = [] _y = [] for line in f: x, b = line.split(" ") y = b.split("\n")[0] _x.append(x) _y.append(y) finally: f.close() f = open("../compare/avg_degree/dup_Twitter_UD.txt", "r") try: _x_ = [] _y_ = [] for line in f: x, b = line.split(" ") y = b.split("\n")[0] _x_.append(x) _y_.append(y) finally: f.close() plt.plot(_x, _y, "b-.", label="MHRW", linewidth=3.0) plt.plot(_x_, _y_, "r-", label="UD", linewidth=3.0) plt.set_ylim(0, 1) plt.set_ylabel("update rate", size=20) plt.set_xlabel("number of nodes", size=20) plt.text(100, 0.85, "Twitter", fontsize=20) plt.legend(loc="upper right")
def partf2(): all_data = setup() genuine, imposter = binary_distances(all_data) plot = roc_plot(genuine, imposter) plt.set_xlabel("TNR") plt.set_ylabel("TPR") plt.show()
def GC_coverage_plot(file_name, GC_list, coverage_list, cover_list_fit): """ Args: file_name: str; absolute path of "GC_coverage.txt" GC_list: list; a list contains the defined GC range (0-100%) coverage_list: list; a list contains the normalized read count corresonding to its GC content cover_list_fit: list; a list contains the fitted number of coverage """ import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages plt.style.use('ggplot') fig = plt.figure() fig.patch.set_alpha(0.5) plt = fig.add_subplot(111) plt.patch.set_alpha(0.5) plt.plot(GC_list, coverage_list, 'o', color='b') plt.plot(GC_list, cover_list_fit, color='r', lw=2) plt.set_xlabel("GC content %") plt.set_ylabel("Normalized read count") plt.set_title("GC content - Normalized read count") file_path = "" if '/' in file_name: file_path = '/'.join(file_name.split('/')[:-1]) + '/' else: file_path = "./" pdf_save_path = file_path + "GC_coverage.pdf" pdf_save = PdfPages(pdf_save_path) pdf_save.savefig() pdf_save.close() print "GC coverage bias relationship plot saved in %s." % pdf_save_path
def plot_line(self, plt, data, kind, title, xlabel, ylabel): plt.set_title(title) plt.set_xlabel(xlabel) plt.set_ylabel(ylabel) plt.plot(data["data"], kind, linewidth=1) return plt pass
def drawPRC(result, sp, methodlabel): ''' Accept a result dataframe whose 'cond' coulmn is binary series representing the ture condition and 'pred' column is the normalized score of predicton. ''' print("drawing prc curve...") sp.set_xlabel('Recall') sp.set_ylabel('Precision') sp.set_ylim([0.0, 1.0]) sp.set_xlim([0.0, 1.0]) sp.set_title('2-class Precision-Recall curve') precision, recall, threshold = precision_recall_curve( result['cond'], result['pred']) average_precision = average_precision_score(result['cond'], result['pred']) myauc = auc(recall, precision) step_kwargs = ({ 'step': 'post' } if 'step' in signature(sp.fill_between).parameters else {}) sp.step(recall, precision, alpha=0.2, where='post') sp.fill_between(recall, precision, alpha=0.2, label=methodlabel + " (AUC = %.3f)" % myauc, **step_kwargs) return myauc
def plotHistogram(graph_number, weight_range, optimizer, weight_decay): weights_histogram_small = small_batch_weights_by_graph_number[graph_number] weights_histogram_big = big_batch_weights_by_graph_number[graph_number] #plot a histogram of the weights fig, plt = subplots() plt.hist(weights_histogram_small, bins=number_bins, range=weight_range, facecolor='blue', alpha=0.5, label=str(small_batch_size)) plt.hist(weights_histogram_big, bins=number_bins, range=weight_range, facecolor='orange', alpha=0.5, label=str(big_batch_size)) #set axis labels and titles plt.set_xlabel('Weight Bins') plt.set_ylabel('Number of Weights') plt.set_title('Histogram of Weights for Configuration' + str(optimizer) + ', WD = ' + str(weight_decay)) #obtain min and max values of tuple mi, mx = weight_range #set axis limits plt.set_xlim([mi, mx]) plt.set_ylim([0, 5000000]) plt.legend(loc='upper right')
def makePlotData(scaffold, snp_list, scaf_len, scaffold_name): ''' :param scaffold: :param snp_list: :param scaf_len: :return: ''' print "Plotting function initiated (4)" position_list = [] # This list is a list of the number of snps in each 10kb bin bins = int(scaf_len/10000) for i in range(bins): pos_list = [] for pos in snp_list: if int(pos) >= i*10000 and int(pos) <= (i+1)*10000: pos_list.append(pos) else: pass #print (pos_list) position_list.append(len(pos_list)) print "Data prepped for matplot (5)" xlist = [i+1 for i in range(len(position_list))] plt.subplots(figsize=(8, 16)) plt.plot(position_list, xlist, 'r-') plt.axis([0, 8502, 0, 760]) plt.set_ylabel('Number of SNPs') plt.set_xlabel('10kb bin') plt.set_title(scaffold_name) plt.show()
def main(): """ Differentiable programming framework can be found in https://taichi.readthedocs.io/en/latest/syntax.html#kernels """ # read in figures img = cv2.imread('erythrocyte.png')[:, :, 0] # normalization img = img / 255.0 img -= img.mean() img = cv2.resize(img, (n, n)) for i in range(n): for j in range(n): u_hat[i, j] = float(img[i, j]) losses = [] for it in range(100): # encapsulate loss in taichi with ti.Tape(loss): forward() print('Iter {} Loss = {}'.format(it, loss[None])) losses.append(loss[None]) # update gradient apply_grad() # output loss curve plt.set_xlabel("Iteration") plt.set_ylabel("Loss") plt.plot(losses) plt.show()
def sample_plot(): """ Sample""" plt.style.use('seaborn') dev_x = [25, 26, 27, 28] dev_y = [1, 2, 3, 4] colors = [300, 315, 270, 305] plt.scatter(dev_x, dev_y, s=100, c=colors, cmap='Reds', edgecolor='k', linewidth=1, label="sample variables") cbar = plt.colorbar() cbar.set_label('Temperature') plt.set_title("Sample Plot") plt.set_xlabel("x") plt.set_ylabel("y") plt.legend() plt.tight_layout() # ============================================================================= # Για την center of mass ΜΟΝΟ: # # t_start = 2 # plt.fill_between(dev_x,dev_y, t_start, where = (dev_x > t_start), alpha = 0.25) # # Γιατί δεν λειτουργεί το where?? # ============================================================================= #ERRORS y_errormin = [0.1, 0.2, 0.5, 0.1] y_errormax = [0.2, 0.4, 0.1, 0.9] y_error = [y_errormin, y_errormax] x_error = 0.5 plt.errorbar(dev_x, dev_y, yerr=y_error, xerr=x_error, fmt=' ', elinewidth=1, capsize=5, errorevery=1, capthick=1) plt.show() # sample_plot()
def plot_lr_search(self, train_loss_list, test_loss_list): plt.plot(lr_list, train_loss_list, label='train loss') plt.plot(lr_list, test_loss_list, label='test loss') plt.set_xticks(lr_list) plt.set_xlabel('learning rate') plt.set_ylabel('loss') plt.legend() plt.show()
def label(plt, xlabel): rng = np.arange(122.7, 123.5, 0.1) plt.set_ylim(rng[0], rng[-1]) plt.set_yticks(rng, ["%.1f" for i in rng]) plt.set_xlabel(xlabel) plt.set_ylabel("Convertible Bond Price") plt.legend(["Binomial", "FDE - Implicit", "FDE - Crank-Nicolson", "FDE - Penalty"], prop={"size": "small"})
def plot_rd(eval_input_fn, model_fn, model_dir): keys = ['rate', 'distortion'] results = fetch(eval_input_fn, model_fn, model_dir, keys, 0) plt.scatter(results[0], results[1]) plt.set_xlabel('Rate') plt.set_ylabel('Distortion') plt.show()
def plotfigTimeSeriesThreetoOne(data): plt = data.plot(lw=2, title="wind predict before and after MOS ") plt.set_xlabel("time series") plt.set_ylabel("wind speed (m/s) ") fig = plt.get_figure() fig.savefig('./plot/' + PostObject + '/TimeSeriesThreetoOne.png') fig.clf()
def plot_accs_for_train_test(plt, train_acc, val_acc, xtick_num=2): n_iter = len(train_acc) iterations = [n for n in range(n_iter)] plt.plot(iterations, train_acc, label='train acc') plt.plot(iterations, val_acc, label='val acc') plt.set_xlabel('iterations') plt.set_xticks([n for n in range(0, len(iterations), xtick_num)]) plt.set_ylabel('acc') plt.legend()
def plot_losses_for_train_test(plt, train_loss, val_loss, xtick_num=2): n_iter = len(train_loss) iterations = [n for n in range(n_iter)] plt.plot(iterations, train_loss, label='train loss') plt.plot(iterations, val_loss, label='val loss') plt.set_xlabel('iterations') plt.set_xticks([n for n in range(0, len(iterations), xtick_num)]) plt.set_ylabel('losses') plt.legend()
def PCA(X): from sklearn.decomposition import PCA pca = PCA() pca.fit(X) plt.plot(pca.singular_values_) plt.set_title('Singular Values of X') plt.set_ylabel("features rank") plt.set_xlabel("Singular Values") plt.savefig(r'C:\Users\funrr\Desktop\ML project\plots' + '\\PCA' + '.jpg', dpi=600)
def barPlot(df, category, value, plt): names = list(df[category].unique()) x=[] for name in names: x.append(list(df[df[category]==name][value])) plt.hist(x, bins = 10, label=names) plt.legend(fontsize = 'x-small') plt.set_xlabel(value) plt.set_ylabel('Count') return plt
def plot_data_with_inset_two_figures(plt, title="", data=[], linestyles=[], labels=[], x_label="", y_label="", legend_loc="lower right", plot_from=0, plot_to=-1, axins_loc=None, axins_axis_visible=True, axins_zoom_factor=25, axins_x_y_lims=[0, 0, -1, -1], axins_aspect=1500, inset_loc1=1, inset_loc2=2, output_path=None): """ If inset plot is not to be drawn, set axins_loc to None. If the highest and lowest thresholds in the inset plot are to be automatically determined, set y1, y2 to -1, -1. """ plot_to = plot_to if plot_to != -1 else len(data[0]) # Create a new figure with a default 111 subplot # fig, ax = plt.subplots() ax = plt # Plot the entire data for i in range(len(data)): ax.plot(range(plot_from, plot_to), data[i][plot_from:plot_to], linestyle=linestyles[i], label=labels[i]) plt.legend(loc=legend_loc) plt.set_ylabel(y_label) plt.set_xlabel(x_label) plt.set_title(title.upper()) # Decide to plot the inset plot or not if axins_loc is not None: # Create a zoomed portion of the original plot axins = zoomed_inset_axes(ax, axins_zoom_factor, loc=axins_loc) for i in range(len(data)): axins.plot(range(plot_from, plot_to), data[i][plot_from:plot_to], linestyle=linestyles[i], label=labels[i]) # specify the limits (four bounding box corners of the inset plot) x1, x2, y1, y2 = axins_x_y_lims # Automatically set the highest and lowest thresholds in the inset plot if (y1 == -1): y1 = min([min(dataset[x1:x2]) for dataset in data]) - 0.0005 y2 = max([max(dataset[x1:x2]) for dataset in data]) + 0.0005 axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) axins.set_aspect(axins_aspect) # plt.set_yticks(visible=axins_axis_visible) # plt.set_xticks(visible=axins_axis_visible) # Choose which corners of the inset plot the inset markers are attachted to mark_inset(ax, axins, loc1=inset_loc1, loc2=inset_loc2, fc="none", ec="0.6") # Save the figure if output_path is not None: plt.savefig(output_path)
def plot_data(y, tx, feature): """plot the fitted curve.""" xval = tx[:, feature - 1] #Let first feature be numbered 1 plt.scatter(xval, y, color='b', s=12, facecolors='none', edgecolors='r') xvals = np.arange(min(xval) - 0.1, max(xval) + 0.1, 0.1) #tx = build_poly(xvals, degree) #f = tx.dot(weights) #ax.plot(xvals, f) plt.set_xlabel("x " + str(feature)) plt.set_ylabel("y") plt.set_title("y vs. feature # " + str(feature))
def histograms(data, xlabel=None, ylabel=None, title=None): """Return a div containing an histogram from the data.""" mpl_fig = plt.figure() plt.hist(data) if xlabel: plt.set_xlabel(xlabel) if ylabel: plt.set_ylabel(ylabel) if title: plt.set_title(title) return get_div_from_data(mpl_fig)
def plot_n(self): ns = np.ndarray(len(self.nsteps)) i=0 for fname in self.fname_list: data = fits.open(fname) ns[i] = len(data[1].data)-1 i+=1 ns = ns/self.init_particles plt.plot(ns) plt.set_xlabel('Timestep') plt.set_ylabel('\r$n_step/N$')
def plot_scatter(self, plt, data, kind, title, xlabel, ylabel, steps): plt.set_title(title) plt.set_xlabel(xlabel) plt.set_ylabel(ylabel) #plt.scatter(range(len(data["data"])),data["data"],s=2,c=steps,cmap=kind) plt.scatter(range(len(data["data"])), data["data"], s=2, edgecolor="none") return plt pass
def plot_boxplots(data): """ :param data: :return: """ all_data = data.values labels = data.columns plt.boxplot(all_data) plt.set_title('box plot') plt.yaxis.grid(True) plt.set_xticks([y + 1 for y in range(len(all_data))]) plt.set_xlabel('feature') plt.set_ylabel('ylabel') plt.setp(xticks=[y + 1 for y in range(len(all_data))], xticklabels=labels) plt.show()
def add_numbers(): import datetime import StringIO import random import urllib from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter value = request.args.get('wordlist') typegraph = request.args.get('wordlist2') danish =[1,2,3,4,5] #fin='/home/danish/Desktop/'+value; df=pd.read_csv(value) xx=df.Time.tolist() yy=df.Output.tolist() if typegraph=="matplotlib" : fig=Figure() plt=fig.add_subplot(111) plt.plot(xx,yy) #plt.show() plt.set_title('sample graph') plt.set_xlabel('time') plt.set_ylabel('output') #fig.autofmt_xdate() canvas=FigureCanvas(fig) png_output = StringIO.StringIO() canvas.print_png(png_output) data = png_output.getvalue().encode('base64') data_url = 'data:image/png;base64,{}'.format(urllib.quote(data.rstrip('\n'))) graph_data =data_url else: graph = pygal.Line() graph.title = '% OUTPUT' graph.x_labels= xx text=yy graph.add('Python', text) graph.x_labels = text graph_data = graph.render_data_uri() return jsonify(result=graph_data)
def fix_hplot(df, statistic, xlabel, ylabel, hue, fontsize): data = df.query('statistic == "{}"'.format(statistic)) pastel = ["#92C6FF", "#97F0AA", "#FF9F9A", "#D0BBFF", "#FFFEA3", "#B0E0E6"] pal = dict(Validation=pastel[0], Test=pastel[2]) plt = sns.barplot(x='data', y='label', data=data, hue=None, errwidth=1.0, capsize=0.15) [ticklabel.set_fontsize(fontsize) for ticklabel in (plt.get_yticklabels())] [ticklabel.set_fontsize(fontsize) for ticklabel in (plt.get_xticklabels())] plt.set_yticklabels([ticklabel._text.capitalize() for ticklabel in (plt.get_yticklabels())], ha='left') plt.get_yaxis().get_label().set_fontsize(fontsize) plt.get_xaxis().get_label().set_fontsize(fontsize) plt.get_yaxis().set_tick_params(pad=fontsize*10-10) plt.set_ylabel(ylabel) plt.set_xlabel(xlabel) plt.set_xlim(0, 1.05) return plt
def plot_clustering_coeff_ranked(ax, G, num_ranked=10): ''' Plot clustering coefficient ranked by maximum value Parameters ---------- G : networkx graph object graph to get clustering coefficients for num_ranked : int number of ranked brain areas to show Returns -------- fig : fig figure object of distribution histogram for plotting ''' # Get clustering coefficients ccoeff_dict = nx.clustering(G) # Graph params width = 0.5 xpos = np.arange(num_ranked) width = 0.8 # Constuct figure fig, ax = plt.subplot(1, 1) sorted_tups = sorted(zip(ccoeff_dict.values(), ccoeff_dict.keys()), key=lambda tup: tup[0], reverse=True)[:num_ranked] # Plot top ranked coefficients according to bins ax.bar(xpos, [w for w, _ in sorted_tups], fc='green', width=width, alpha=.8) ax.xticks(xpos + width / 2., [n for _, n in sorted_tups]) ax.set_title('Ranked Clustering Coefficients') plt.set_xlabel('Region') plt.set_ylabel('Clustering Coefficient')
def sbprofile(sim, band='v', diskheight='3 kpc', rmax='20 kpc', binning='equaln', center=True, clear=True, filename=None, axes=False, fit_exp=False, print_ylabel=True, fit_sersic=False, **kwargs): ''' surface brightness profile **Usage:** >>> import pynbody.plot as pp >>> h = s.halos() >>> pp.sbprofile(h[1],exp_fit=3,linestyle='dashed',color='k') **Options:** *band* ('v'): which Johnson band to use. available filters: U, B, V, R, I, J, H, K *fit_exp*(False): Fits straight exponential line outside radius specified. *fit_sersic*(False): Fits Sersic profile outside radius specified. *diskheight('3 kpc')* *rmax('20 kpc')*: Size of disk to be profiled *binning('equaln')*: How show bin sizes be determined? based on pynbody.analysis.profile *center(True)*: Automatically align face on and center? *axes(False)*: In which axes (subplot) should it be plotted? *filename* (None): name of file to which to save output **needs a description of all keywords** By default, sbprof will use the formation mass of the star. In tipsy, this will be taken from the starlog file. ''' if center: logger.info("Centering...") angmom.faceon(sim) logger.info("Selecting disk stars") diskstars = sim.star[filt.Disc(rmax, diskheight)] logger.info("Creating profile") ps = profile.Profile(diskstars, type=binning) logger.info("Plotting") r = ps['rbins'].in_units('kpc') if axes: plt = axes else: import matplotlib.pyplot as plt if clear: plt.clf() plt.plot(r, ps['sb,' + band], linewidth=2, **kwargs) if axes: plt.set_ylim(max(ps['sb,' + band]), min(ps['sb,' + band])) else: plt.ylim(max(ps['sb,' + band]), min(ps['sb,' + band])) if fit_exp: exp_inds = np.where(r.in_units('kpc') > fit_exp) expfit = np.polyfit(np.array(r[exp_inds]), np.array(ps['sb,' + band][exp_inds]), 1) # 1.0857 is how many magnitudes a 1/e decrease is print "h: ", 1.0857 / expfit[0], " u_0:", expfit[1] fit = np.poly1d(expfit) if 'label' in kwargs: del kwargs['label'] if 'linestyle' in kwargs: del kwargs['linestyle'] plt.plot(r, fit(r), linestyle='dashed', **kwargs) if fit_sersic: sersic_inds = np.where(r.in_units('kpc') < fit_sersic) sersicfit = np.polyfit(np.log10(np.array(r[sersic_inds])), np.array(ps['sb,' + band][sersic_inds]), 1) fit = np.poly1d(sersicfit) print "n: ", sersicfit[0], " other: ", sersicfit[1] if 'label' in kwargs: del kwargs['label'] if 'linestyle' in kwargs: del kwargs['linestyle'] plt.plot(r, fit(r), linestyle='dashed', **kwargs) #import pdb; pdb.set_trace() if axes: if print_ylabel: plt.set_ylabel(band + '-band Surface brightness [mag as$^{-2}$]') else: plt.xlabel('R [kpc]') plt.ylabel(band + '-band Surface brightness [mag as$^{-2}$]') if filename: logger.info("Saving %s", filename) plt.savefig(filename)
def make_contour_plot(arr, xs, ys, x_range=None, y_range=None, nlevels = 20, axbgclr = 'w', axfgclr = 'k', logscale=True, xlogrange=False, ylogrange=False, subplot=False, colorbar=False, ret_im=False, cmap=None, clear=True,legend=False, scalemin = None, clip=False, scalemax = None, filename = None, annotate = False, **kwargs) : """ Plot a contour plot of grid *arr* corresponding to bin centers specified by *xs* and *ys*. Labels the axes and colobar with proper units taken from x Called by :func:`~pynbody.plot.generic.hist2d` and :func:`~pynbody.plot.generic.gauss_density`. **Input**: *arr*: 2D array to plot *xs*: x-coordinates of bins *ys*: y-coordinates of bins **Optional Keywords**: *x_range*: list, array, or tuple (default = None) size(x_range) must be 2. Specifies the X range. *y_range*: tuple (default = None) size(y_range) must be 2. Specifies the Y range. *xlogrange*: boolean (default = False) whether the x-axis should have a log scale *ylogrange*: boolean (default = False) whether the y-axis should have a log scale *nlevels*: int (default = 20) number of levels to use for the contours *logscale*: boolean (default = True) whether to use log or linear spaced contours *colorbar*: boolean (default = False) draw a colorbar *scalemin*: float (default = arr.min()) minimum value to use for the color scale *scalemax*: float (default = arr.max()) maximum value to use for the color scale """ from matplotlib import ticker, colors arrows=kwargs.get('arrows',[]) if not subplot : import matplotlib.pyplot as plt else : plt = subplot if x_range is None: if subplot: x_range=plt.get_xlim() else : x_range = (np.min(xs),np.max(xs)) if y_range is None: if subplot: y_range=plt.get_ylim() else : y_range = (np.min(ys),np.max(ys)) if scalemin is None: scalemin = np.min(arr[arr>0]) if scalemax is None: scalemax = np.max(arr[arr>0]) if 'norm' in kwargs: del(kwargs['norm']) # Adjust colormap if cmap: from mmlutils.mmlplot import get_cmaparray cmap_colors=get_cmaparray(cmap) axbgclr=cmap_colors[0] axfgclr=cmap_colors[-1] if logscale: cmap=colors.ListedColormap(cmap_colors[int(0.01*len(cmap_colors)):]) cmap.set_under(color=axbgclr) cmap.set_over(color=axfgclr) cmap.set_bad(color=axbgclr) #no effect levelmin=scalemin/100. levelmax=scalemax*100. if logscale: try: levels = np.logspace(np.log10(scalemin),np.log10(scalemax),nlevels) cont_color=colors.LogNorm(clip=False) except ValueError: raise ValueError('crazy contour levels -- try specifying the *levels* keyword or use a linear scale') return if arr.units != NoUnit() and arr.units != 1 : cb_label = '$log_{10}('+arr.units.latex()+')$' else : cb_label = '$log_{10}(N)$' else: levels = np.linspace(scalemin,scalemax,nlevels) cont_color=None if arr.units != NoUnit() and arr.units != 1 : cb_label = '$'+arr.units.latex()+'$' else : cb_label = '$N$' if not subplot and clear : plt.clf() if logscale: arr=np.ma.masked_less_equal(arr,0).filled(scalemin/100.) if ret_im : if logscale: arr = np.log10(arr) return plt.imshow(arr, origin='down', vmin=scalemin, vmax=scalemax, aspect = 'auto',cmap=cmap, #aspect = np.diff(x_range)/np.diff(y_range),cmap=cmap, extent=[x_range[0],x_range[1],y_range[0],y_range[1]]) # Adjust to log then plot if logscale: linarr=np.log10(arr) ; linlvl=np.log10(levels) else : linarr=arr ; linlvl=levels cs = plt.contourf(xs,ys,linarr, linlvl, norm=None,cmap=cmap,extend='both',**kwargs) #cs = plt.contourf(xs,ys,arr, levels, norm=cont_color,cmap=cmap,**kwargs) plt.gca().set_axis_bgcolor(axbgclr) if kwargs.has_key('xlabel'): xlabel = kwargs['xlabel'] else : try: if xlogrange: xlabel=r''+'$log_{10}('+xs.units.latex()+')$' else : xlabel = r''+'$x/' + xs.units.latex() +'$' except AttributeError: xlabel = None if xlabel : try: if subplot : plt.set_xlabel(xlabel) else: plt.xlabel(xlabel) except: pass if kwargs.has_key('ylabel'): ylabel = kwargs['ylabel'] else : try: if ylogrange: ylabel='$log_{10}('+ys.units.latex()+')$' else : ylabel = r''+'$y/' + ys.units.latex() +'$' except AttributeError: ylabel=None if ylabel : try: if subplot : plt.set_ylabel(ylabel) else: plt.ylabel(ylabel) except: pass # if not subplot: # plt.xlim((x_range[0],x_range[1])) # plt.ylim((y_range[0],y_range[1])) if colorbar : cbfmt="%.2f" if logscale else "%.2e" cb = plt.colorbar(cs, format = cbfmt).set_label(r''+cb_label) #cb = plt.colorbar(cs, format = "%.2e").set_label(r''+cb_label) if legend : plt.legend(loc=2) # Annotate if annotate: imgsiz = (x_range[1]-x_range[0],y_range[1]-y_range[0]) # Arrow from mmlutils.mmlmath import polar_square dx=imgsiz[0]/40. dy=imgsiz[1]/40. for iarrow in arrows: iphi=np.arctan((iarrow[1]/imgsiz[1])/(iarrow[0]/imgsiz[0])) idir=polar_square(iphi) ix=(idir[0]+0.5)*(imgsiz[0]-dx)+x_range[0] iy=(idir[1]+0.5)*(imgsiz[1]-dy)+y_range[0] plt.scatter(ix,iy,c=axfgclr,marker=(3,0,-90+iphi*180./np.pi),s=arr.shape[0]) plt.xlim((x_range[0],x_range[1])) plt.ylim((y_range[0],y_range[1])) # Strings # imgsiz = (array.SimArray(x_range[1]-x_range[0],units=xs.units), # array.SimArray(y_range[1]-y_range[0],units=ys.units)) xlocpad=imgsiz[0]/20. ylocpad=imgsiz[1]/20. for locstr in ['ul','ur','dl','dr']: iloc=[0.,0.] if locstr[1]=='l': iloc[0]=x_range[0]+xlocpad ; ha='left' elif locstr[1]=='r': iloc[0]=x_range[1]-xlocpad ; ha='right' if locstr[0]=='u': iloc[1]=y_range[1]-ylocpad ; va='top' elif locstr[0]=='d': iloc[1]=y_range[0]+ylocpad ; va='bottom' plt.text(iloc[0],iloc[1],kwargs.get(locstr+'str',''),color=axfgclr, horizontalalignment=ha, verticalalignment=va) # Save if (filename): if config['verbose']: print "Saving "+filename plt.savefig(filename)
plt.loglog(wlams,wflam_star,\ color='red',marker='o',linestyle='None',markersize=3) plt.loglog(slams,sflam_star,\ color='white',marker='o',linestyle='None',markersize=3) # label='IRAS F16544$-$1604') #plt.figtext(0.4,0.83,'WISE') #print plt.gca() axes=fig1.gca() for label in axes.get_xticklabels() + axes.get_yticklabels(): label.set_fontsize('x-small') if (i < nx): plt.set_xlabel(r'$\lambda$ ($\mu$m)',size='x-small') if (np.mod(i,nx)==0): plt.set_ylabel(r'$\lambda F_\lambda$ (erg/s/cm$^{2}$)',size='x-small') else: plt.set_yticklabels('',visible='False',size='x-small') plt.axis([0.4,150,1e-14,1e-6]) # print 'i = ', i plt.text(0.7,5e-8,'M%d'%(i+1),size='small') print "%12s &%15s &\$%4.1f\pm%4.1f\$ &\$%4.1f\pm%4.1f\$ &\$%4.1f\pm%4.1f\$ &\$%4.1f\pm%4.1f\$ &\$%4.1f\pm%4.1f\$ &\$%4.2f\pm%4.2f\$ &\$%4.2f\pm%4.2f\$ &\$%4.2f\pm%4.2f\$ &\$%4.2f\pm%4.2f\$(%s%s) &\$%4.2f\pm%4.2f\$(%s%s)\\\\"%\ (scat['2MASS_name'][sstar],scat['object_type'][sstar],\ scat['J_flux_c'][sstar],scat['J_D_flux_c'][sstar],\ scat['H_flux_c'][sstar],scat['H_D_flux_c'][sstar],\ scat['Ks_flux_c'][sstar],scat['Ks_D_flux_c'][sstar],\ w1f[wstar],w1df[wstar],\ w2f[wstar],w2df[wstar],\ w3f[wstar],w3df[wstar],\ w4f[wstar],w4df[wstar],\ scat['MP1_flux_c'][sstar],scat['MP1_D_flux_c'][sstar],\
print "No data file name given. Please enter" datafile = raw_input("-> ") if len(glob.glob(datafile))==0: print "Data file %s not found. Exiting" % datafile sys.exit() for x in range(1,len(sys.argv)): datafile=sys.argv[x] if len(glob.glob(datafile))==0: print "Data file %s not found. Exiting" % datafile sys.exit() data=np.loadtxt(datafile) pl.plot(data[:,0], data[:,1],marker='o',markersize=3,label= datafile) plotname = 'plot.png' xmin =1e-18 xmax = 1 ymin = 1e-18 ymax = 1 pl.axis([xmin, xmax, ymin, ymax]) pl.set_ylabel(r'$P \ (\Delta x) $', fontsize=15) pl.set_xlabel(r'$\frac{\Delta x}{\sigma} $', fontsize=15) #ax1.set_xlim(-4, 4) #ax1.set_ylim(0, 1) #plt.savefig(plotname, dpi=100) plt.show()
# Create function to plot figures def plot_qob(yvar, ax, title, ylabel): values = birth_means['educ'].values ax.plot(values) ax.title('A. Average education by quarter of birth (first stage)') ax.set_ylabel(ylabel) ax.set_xlabel("Quarter of birth") fig, ax = plt.subplots() plot_qob(birth_means['educ'], ax, 'A. Average education by quarter of birth (first stage)', 'Years of education') # Panel A plt.subplot(2, 1, 1) plt.title("A. Average education by quarter of birth (first stage)") plt.set_ylabel("Years of education") birth_means.plot(y = 'educ', marker = 'o') # Panel B plt.subplot(2, 1, 2) plt.title("B. Average weekly wage by quarter of birth (reduced form)") plt.set_ylabel("Log weekly earnings") birth_means.plot(y = 'lwklywge', marker = 'o') # Format overall figure and export to PDF plt.legend().set_visible(False) plt.tight_layout() # http://matplotlib.org/users/tight_layout_guide.html plt.savefig('Figure 4-1-1-Python.pdf', format = 'pdf') plt.close('all') # End of file
def make_contour_plot(arr, xs, ys, x_range=None, y_range=None, nlevels = 20, logscale=True, xlogrange=False, ylogrange=False, subplot=False, colorbar=False, ret_im=False, cmap=None, clear=True,legend=False, scalemin = None, scalemax = None, filename = None, **kwargs) : """ Plot a contour plot of grid *arr* corresponding to bin centers specified by *xs* and *ys*. Labels the axes and colobar with proper units taken from x Called by :func:`~pynbody.plot.generic.hist2d` and :func:`~pynbody.plot.generic.gauss_density`. **Input**: *arr*: 2D array to plot *xs*: x-coordinates of bins *ys*: y-coordinates of bins **Optional Keywords**: *x_range*: list, array, or tuple (default = None) size(x_range) must be 2. Specifies the X range. *y_range*: tuple (default = None) size(y_range) must be 2. Specifies the Y range. *xlogrange*: boolean (default = False) whether the x-axis should have a log scale *ylogrange*: boolean (default = False) whether the y-axis should have a log scale *nlevels*: int (default = 20) number of levels to use for the contours *logscale*: boolean (default = True) whether to use log or linear spaced contours *colorbar*: boolean (default = False) draw a colorbar *scalemin*: float (default = arr.min()) minimum value to use for the color scale *scalemax*: float (default = arr.max()) maximum value to use for the color scale """ from matplotlib import ticker, colors if not subplot : import matplotlib.pyplot as plt else : plt = subplot if scalemin is None: scalemin = np.min(arr[arr>0]) if scalemax is None: scalemax = np.max(arr[arr>0]) if 'norm' in kwargs: del(kwargs['norm']) if logscale: try: levels = np.logspace(np.log10(scalemin), np.log10(scalemax),nlevels) cont_color=colors.LogNorm() except ValueError: raise ValueError('crazy contour levels -- try specifying the *levels* keyword or use a linear scale') return if arr.units != NoUnit() and arr.units != 1 : cb_label = '$log_{10}('+arr.units.latex()+')$' else : cb_label = '$log_{10}(N)$' else: levels = np.linspace(scalemin, scalemax,nlevels) cont_color=None if arr.units != NoUnit() and arr.units != 1 : cb_label = '$'+arr.units.latex()+'$' else : cb_label = '$N$' if not subplot and clear : plt.clf() if ret_im : if logscale: arr = np.log10(arr) return plt.imshow(arr, origin='down', vmin=scalemin, vmax=scalemax, aspect = 'auto',cmap=cmap, #aspect = np.diff(x_range)/np.diff(y_range),cmap=cmap, extent=[x_range[0],x_range[1],y_range[0],y_range[1]]) cs = plt.contourf(xs,ys,arr, levels, norm=cont_color,cmap=cmap,**kwargs) if kwargs.has_key('xlabel'): xlabel = kwargs['xlabel'] else : try: if xlogrange: xlabel=r''+'$log_{10}('+xs.units.latex()+')$' else : xlabel = r''+'$x/' + xs.units.latex() +'$' except AttributeError: xlabel = None if xlabel : try: if subplot : plt.set_xlabel(xlabel) else: plt.xlabel(xlabel) except: pass if kwargs.has_key('ylabel'): ylabel = kwargs['ylabel'] else : try: if ylogrange: ylabel='$log_{10}('+ys.units.latex()+')$' else : ylabel = r''+'$y/' + ys.units.latex() +'$' except AttributeError: ylabel=None if ylabel : try: if subplot : plt.set_ylabel(ylabel) else: plt.ylabel(ylabel) except: pass # if not subplot: # plt.xlim((x_range[0],x_range[1])) # plt.ylim((y_range[0],y_range[1])) if colorbar : cb = plt.colorbar(cs, format = "%.2e").set_label(r''+cb_label) if legend : plt.legend(loc=2) if (filename): if config['verbose']: print "Saving "+filename plt.savefig(filename)
def density_profile(sim, linestyle=False, center=True, clear=True, fit=False,in_units=None, filename=None, fit_factor=0.02, axes=False, **kwargs): ''' 3d density profile **Options:** *filename* (None): name of file to which to save output **Usage:** >>> import pynbody.plot as pp >>> h = s.halos() >>> pp.density_profile(h[1],linestyle='dashed',color='k') ''' if axes: plt = axes else: import matplotlib.pyplot as plt global config logger.info("Centering...") if center: halo.center(sim, mode='ssc') logger.info("Creating profile...") if 'min' in kwargs: ps = profile.Profile( sim, ndim=3, type='log', nbins=40, min=kwargs['min']) del kwargs['min'] else: ps = profile.Profile(sim, ndim=3, type='log', nbins=40) if clear and not axes: plt.clf() critden = (units.Unit('100 km s^-1 Mpc^-1') * sim.properties['h']) ** 2 / 8.0 / np.pi / units.G r = ps['rbins'].in_units('kpc') if in_units is None: den = ps['density'].in_units(critden) else: den = ps['density'].in_units(in_units) if linestyle: plt.errorbar(r, den, yerr=den / np.sqrt(ps['n']), linestyle=linestyle, **kwargs) else: plt.errorbar(r, den, yerr=den / np.sqrt(ps['n']), fmt='o', **kwargs) if in_units is None: ylabel=r'$\rho / \rho_{cr}$' # +den.units.latex()+'$]') else: ylabel=r'$\rho / '+den.units.latex()+'$' if axes: plt.set_yscale('log') plt.set_xscale('log') plt.set_xlabel('r [kpc]') plt.set_ylabel(ylabel) #r'$\rho / \rho_{cr}$') # +den.units.latex()+'$]') else: plt.yscale('log') plt.xscale('log') plt.xlabel('r [kpc]') plt.ylabel(ylabel) #r'$\rho / \rho_{cr}$') # +den.units.latex()+'$]') if (filename): logger.info("Saving %s", filename) plt.savefig(filename) if fit: fit_inds = np.where(r < fit_factor*sim['r'].max()) alphfit = np.polyfit(np.log10(r[fit_inds]), np.log10(den[fit_inds]), 1) # print "alpha: ", alphfit[0], " norm:", alphfit[1] fit = np.poly1d(alphfit) plt.plot(r[fit_inds], 10**fit(np.log10(r[fit_inds])), color='k',linestyle='dashed', label=r'$\alpha$=%.1f'%alphfit[0]) plt.legend(loc=3) return alphfit[0]
import matplotlib.pyplot as plt these_times = times[times.team == team] plt.plot(these_times.time.as_matrix(), np.ones(len(these_times)), 'o') plt.set_ylabel(team, rotation='horizontal', labelpad=30) plt.set_ybound(0.5, 1.5) plt.set_position([0.1, 0.1, 8.0, 1.0]) plt.set_yticks([])
fig1.clf() i = 0 j = 0 for i in range(len(files)): plt = fig1.add_subplot(ny,nx,j+1) histogram = hist(files[i]) bin_edges=histogram[0] x = histogram[1] C = colour plt.scatter(bin_edges[:-1],x,c=u'r') axes=fig1.gca() plt.set_xticklabels('',visible='False',size='small') plt.set_yticklabels('',visible='True',size='small') if (j==4): plt.set_xlabel(r'Temperature (K)',size='small') plt.set_xticklabels('',visible='True',size='small') plt.axis([5,60,0,1.1E-3]) plt.set_ylabel('Normalised Number of pixels',size='small') j = j + 1 fig1.show()
axes=fig1.gca() #axes=fig2.gca() cores = [1,2,3,4,7,11,12,17,19,30] for label in axes.get_xticklabels() + axes.get_yticklabels(): label.set_fontsize('x-small') plt.set_xticklabels('',visible='False',size='x-small') if (j == 9): plt.set_xlabel(r'$\lambda$ (${\mathrm{\mu m}}$)',size='x-small') plt.set_xticklabels('',visible='True',size='x-small') if (j == 8): plt.set_xlabel(r'$\lambda$ (${\mathrm{\mu m}}$)',size='x-small') plt.set_xticklabels('',visible='True',size='x-small') if (j % 2): plt.set_yticklabels('',visible='True',size='x-small') else: plt.set_ylabel(r'$\nu$ $S_\nu$ (${\mathrm{Wm^{-1}}}$)',size='x-small') plt.axis([1e0,2e3,5e-18,5e-10]) #Large Axis plt.text(5e2,5e-11,'FW%s'%(cores[j]),size='x-small') print 'SED %d plotted'%(cores[j]) j = j + 1 fig1.savefig('plots/20140327_MWC297_SEDs.eps', format='eps')
# Need to remove 0 values in time_to_city and time_to_extinction. time_to_city = time_to_city[time_to_city != 0] time_to_extinction = time_to_extinction[time_to_extinction != 0] # Computing desired values and inserting into appropriate arrays. avg_time_to_city[i-1] = np.mean(time_to_city) avg_time_to_city[i-1] = np.mean(time_to_extinction) prob_inf_city[i-1] = infections/len(filenames) prob_extinct_city[i-1] = extinctions/len(filenames) # Create appropriate plots and save them # Plotting avg time for infection to reach city vs movement rate fig = plt.figure(figsize=(10, 7)) plt.set_title('Average Time for Infection to Reach City') plt.set_ylabel('Time') plt.set_xlabel('Mu') plt.scatter(mu_vals, avg_time_to_city) fig.saveas('timetoinf_vs_mu.png') # Plotting avg time to extinction vs movement rate fig = plt.figure(figsize=(10, 7)) plt.set_title('Average Time to Extinction') plt.set_ylabel('Time') plt.set_xlabel('Mu') plt.scatter(mu_vals, avg_time_to_extinction) fig.saveas('timetoextinct_vs_mu.png') # Plotting p(infection) in city vs movement rate fig = plt.figure(figsize=(10, 7)) plt.set_title('P(Inf in City) vs movement rate, mu')