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 plot_horizontal_bar_from_cm(confusion_matrix = None, classes = []): # plt.rcdefaults() # plt.subplots(figsize = (10, 30)) width = 0.30 # Example data y_lables = 12 * ['a', 'b', 'c', 'd'] y_pos = list(range(len(y_lables))) print(y_pos) true_positives = 12 * [8.84036186, 12.94095337, 11.19919226, 10.64395389] false_negatives = 12 * [1, 1, 1, 1] false_positives = 12 * [2, 13, 13, 3] TP = plt.barh(y_pos, true_positives, width, color = 'green', label = 'TP') FN = plt.barh(y_pos, false_negatives, width, label = 'FN', left = TP) plt.barh(y_pos, false_positives, width, label = 'FP', left = FN) # ax.barh([p + width for p in y_pos], false_negatives, width, label = 'FN') # ax.barh([p + width * 2 for p in y_pos], false_positives, width, label = 'FP') plt.set_yticks([p + 1.5 * width for p in y_pos]) plt.set_yticklabels(y_lables) plt.invert_yaxis() # labels read top-to-bottom plt.set_xlabel('Performance') plt.set_title('How fast do you want to go today?') plt.legend(['TP', 'FN', 'FP'], loc = 'upper right') plt.show()
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 DensityHistogram(self, bins=20, Plot = True, Log = True): """ radiusbins, density = snap.DensityHistogram() Separate the system in radial bins, then compute the volumic stellar density inside each. bins : if integer, sets the number of bins if array, sets bins edges Plot : True will display density=f(radius) in linear scale Log : True will change the plot to log-log scale. """ R=self.R() if type(bins) is int: radiusbins=np.logspace( np.log10(np.min(R)) , np.log10(np.max(R)) , bins) else: radiusbins = bins volumebins= SphVol(radiusbins[1:]) - SphVol(radiusbins[:-1]) Mbins=[] for i in range(len(radiusbins)-1): ind= np.logical_and(R>radiusbins[i], R<radiusbins[i+1]) Mbins.append(sum(self.m[ind])) density = np.array(Mbins) / volumebins if Plot: if Log: plt.plot(np.log10(radiusbins[0:len(radiusbins)-1]), np.log10(density)) else: plt.plot(radiusbins[0:len(radiusbins)-1], density) plt.show() plt.set_xlabel("Radius") plt.set_xlabel("Density") return radiusbins[0:len(radiusbins)-1], density
def plot_gene_tfs_scatter(tf, small_peaks, datastore): time = 120.0 # select orfs with the tf bound selected_peaks = small_peaks.all_motifs[small_peaks.all_motifs.tf == tf] selected_orfs = small_peaks.all_motifs[small_peaks.all_motifs.tf == tf].orf.values # load the transcription data xrate = datastore.transcript_rate_logfold[[time]]\ .loc[selected_orfs] # load the linked peaks peaks = small_peaks.linked_peaks_normalized peaks = peaks.loc[selected_peaks.peak.values] peaks_diff = difference(peaks) plot_data = peaks_diff.join(selected_peaks.set_index('peak')[['orf']]).reset_index() plot_data = plot_data.groupby('orf').mean() plot_data = plot_data[[time]].join(xrate[[time]], rsuffix='_logfold_TPM', lsuffix='_sm_occ') plot_data = plot_data.sort_values('120.0_sm_occ', ascending=False) names = plot_data.join(small_peaks.all_orfs[['name']]) plt.figure(figsize=(4, 4)) plt.scatter(plot_data['120.0_sm_occ'], plot_data['120.0_logfold_TPM']) plt.plot([-1, 1], [0, 0], color='gray', linestyle='dotted') plt.plot([0, 0], [-100, 100], color='gray', linestyle='dotted') plt.xlim(-0.05, 0.05) plt.ylim(-10, 10) plt.set_xlabel() plt.set_xlabel()
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 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 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 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 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 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 MassFunction(self, bins=25, Plot=False, **kwargs): """ bins, N_arr = snap.MassFunction( bins = 15, linewidth = 2 ) Return the mass function. bins : if integer, sets the number of bins from min to max if array, sets bins edges Plot : True will display the mass function histogram All normal plot keywords can be passed. """ m = self.m if type(bins) is int: massbins=np.logspace( np.log10(np.min(m)) , np.log10(np.max(m)) , bins) else: massbins = bins Nstar = np.zeros(len(massbins)-1) for i in range(len(massbins)-1): Nstar[i] = len(m[ (massbins[i] < m) & ( m < massbins[i+1] ) ]) massbins = (massbins[1:] + massbins[:-1])/2 if Plot: plt.plot(np.log10(massbins), np.log10(Nstar),**kwargs) plt.show() plt.set_xlabel("Mass") plt.set_xlabel("N") return massbins, Nstar
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 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 SurfaceDensity(self, bins=20, Plot = True, Log = True ): """ radiusbins, sigma = snap.SurfaceDensity() Return the stellar projected surface density in logarithmic radial bins bins : if integer, sets the number of bins if array, sets bins edges Plot : True will display density=f(radius) in linear scale Log : True will change the plot to log-log scale. """ self.CorrectionCenterOfMass() Rproj=np.sqrt(self.x**2+self.y**2) if type(bins) is int: radiusbins=np.logspace( np.log10(np.min(Rproj)) , np.log10(np.max(Rproj)) , bins) else: radiusbins = bins nbins = len(radiusbins) sigma=[] for i in range(nbins-1): ind= np.logical_and(Rproj>radiusbins[i], Rproj<radiusbins[i+1]) sigma.append(sum(self.m[ind]) / \ ( np.pi * (radiusbins[i+1]**2-radiusbins[i]**2) )) if Plot: if Log: plt.plot(np.log10(radiusbins[0:len(radiusbins)-1]), np.log10(np.array(sigma))) else: plt.plot(radiusbins[0:len(radiusbins)-1], sigma) plt.show() plt.set_xlabel("Radius") plt.set_xlabel("Surface Density") return radiusbins[0:len(radiusbins)-1], np.array(sigma)
def eb1(): fig = Figure() plt=fig.subplots() #plt = fig.add_subplot(1, 1, 1) plt.set_title("Expenditure - allocation") plt.set_xlabel("Worth") a=session['e'] c=session['nc'] a=np.arange(len(a)) w=0.25 c=[x + w for x in a] print(c) print(a) b=['raw goods', 'hr', 'tax', 'marketing', 'techn-cost'] b1=np.arange(len(a)) b2=[x + w for x in b1] plt.bar(b1,a, color="yellow", width=0.25, label="allocation") plt.bar(b2,c, color="green", width=0.25, label="expenditure") canvas = FigureCanvas(fig) output = io.BytesIO() canvas.print_png(output) response = make_response(output.getvalue()) response.mimetype = 'image/png' return response
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 CumulatedMass(self, bins=25, Plot=False, Logr= False): """ radiusbins, cumM = snap.SurfaceDensity() Return the cumulated mass starting from the center in logarithmic radial bins bins : if integer, sets the number of bins if array, sets bins edges Plot : True will display density=f(radius) in linear scale Logr : True will create logarithmic radius bins """ R=self.R() if type(bins) is int: if Logr: radiusbins=np.logspace( np.log10(np.min(R)) , np.log10(np.max(R)) , bins) else: radiusbins=np.linspace( np.min(R) , np.max(R) , bins) else: radiusbins = bins nbins = len(radiusbins) massbins = np.zeros(nbins) for i in range(nbins): massbins[i] = sum(self.m[R < radiusbins[i+1]]) if Plot: plt.plot(radiusbins[1:], massbins) plt.show() plt.set_xlabel("Radius") plt.set_xlabel("Cumulated mass") return radiusbins[1:], massbins
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_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 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 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 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 show_sample(self, img, target, invert=True): img = self.denorm(img).clamp(0, 1) if invert: plt.set_xlabel(self.classes[target]) plt.imshow(1 - img.permute((1, 2, 0))) else: plt.title(f"{self.classes[target]}") plt.imshow(img.permute(1, 2, 0))
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 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_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_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 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 bifurcationPhi(tmax=50, tsteps=0.01, phiMax=10, phiMin=1, massSteps=0.1, filename="bifurcationAngle"): tpoints = int(tmax/tsteps) phipoints = int((phiMax-phiMin)/phiSteps) phiPointsArray = np.arange(phiMin, phiMax, phiSteps) Phi = np.zeros([phipoints, tpoints]) for i, phi0 in enumerate(massPointsArray): Phi[i] = pd.rk4DobPend(0.5, 0.5, 0.5, 0.5, phi0, 0, 0, 0, tsteps, tmax, purpose="bifurcation angle") plt.plot(phiPointsArray[::2], np.abs(Mass[::2, 4500::]),'r.', ms=1, alpha=.1) plt.set_xlabel("Initial angle of upper pendulum") plt.set_xlabel("angular velocity of lower pendulum") plt.savefig(filename) plt.show() return
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')
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()
#VLA plt.loglog(VLA[:,0],VLA[:,i]*v(VLA[:,0]),color='black',marker='o',linestyle='None',markersize=2) plt.errorbar(VLA[:,0],VLA[:,i]*v(VLA[:,0]), yerr=VLA[:,i]*v(VLA[:,0]),fmt='b.', ecolor='blue') 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])
plt.clf() plt.hist2d(max_magn_ica[:,0], max_magn_ica[:,1], bins=256, cmap='gray') plt.hist2d(max_magn_ica[:,0], max_magn_ica[:,1], bins=256, cmap='viridis') plt.hist2d(max_magn_ica[:,0], max_magn_ica[:,1], bins=256, cmap='plasma') plt.hist2d(max_magn_ica[:,0], max_magn_ica[:,1], bins=256, cmap='magma') plt.hist2d(max_magn_ica[:,0], max_magn_ica[:,1], bins=256, cmap='Blues') plt.hist2d(max_magn_ica[:,0], max_magn_ica[:,1], bins=128, cmap='Blues') plt.clf() plt.hist2d(max_magn_ica[:,0], max_magn_ica[:,1], bins=128, cmap='Blues') plt.colorbar() plt.clf() plt.hist2d(max_magn_ica[:,0], max_magn_ica[:,1], bins=128, cmap='Blues', density=True) plt.hist2d(max_magn_ica[:,0], max_magn_ica[:,1], bins=128, cmap='Blues', normed=True) plt.colorbar() plt.tight_layout() plt.set_xlabel('ICA 1') plt.xlabel('ICA 1') plt.ylabel('ICA 2') plt.tight_layout() mean = scipy.ndimage.mean(colourlabels, labels=cq['cleanqueen'].value, index=np.arange(1, cq['cleanqueen'].value.max() + 1)) mean_0 = scipy.ndimage.mean(colourlabels[...,0], labels=cq['cleanqueen'].value, index=np.arange(1, cq['cleanqueen'].value.max() + 1)) mean_1 = scipy.ndimage.mean(colourlabels[...,1], labels=cq['cleanqueen'].value, index=np.arange(1, cq['cleanqueen'].value.max() + 1)) plt.cls() plt.close() plt.hist2d(mean_0,mean_1, bins=128, cmap='Blues', normed=True) plt.imshow(m) get_ipython().magic(u'whos') plt.scatter(max_pos[:,1], max_pos[:,0]) centre_of_mass = scipy.ndimage.center_of_mass(cq['cleanqueen'].value != 0, labels=cq['cleanqueen'].value, index=np.arange(1, cq['cleanqueen'].value.max() + 1)) centre_of_mass = np.array(centre_of_mass, int) com_ica = colourlabels[centre_of_mass[:,0], centre_of_mass[:,1]]
plt = fig1.add_subplot(ny,nx,i+1) 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],\
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') plt.set_ylabel('P(inf)')
import numpy as np import matplotlib.pyplot as plt from pandas import DataFrame, Series fig, img = plt.subplots(1, 1) # img.plot(np.random.randn(100),color='red', # linestyle='dashed',marker='o') plt.plot(np.random.randn(100), color="red", label="Red One") plt.plot(np.random.randn(100), color="green", label="Green One") plt.plot(np.random.randn(100), color="blue", label="Blue One") plt.set_title("Colorful Lines", fontsize=20) plt.set_xlabel("Frequency Level", fontsize=18) plt.legend(loc="best") # img[0,2].plot([30,100,20,80,120],'ko--',color='purple') # img.scatter(np.random.randn(100),np.random.randn(100)*2,color='red')
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)
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()
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]
def plot(x_multi=[[1, 11, 21], [2, 12, 22], [3, 13, 23], [4, 14, 24], [5, 15, 25], [6, 16, 26]], label=['a', 'b', 'c', 'd', 'e']): plt.hist(x_multi, histtype='bar', label=label) plt.legend(prop={'size': 10}) plt.show() plt.set_xlabel()
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)