我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.tick_params()。
def plot_gold(g1, g2, lc, p = 0): """ plot sen/spe of g1 against g2 only consider workers in lc """ mv = crowd_model.mv_model(lc) s1 = []; s2 = [] for w in g1.keys(): if w in g2 and g1[w][p] != None and g2[w][p] != None and w in mv.dic_ss: s1.append(g1[w][p]) s2.append(g2[w][p]) plt.xticks((0, 0.5, 1), ("0", "0.5", "1")) plt.tick_params(labelsize = 25) plt.yticks((0, 0.5, 1), ("0", "0.5", "1")) plt.xlim(0,1) plt.ylim(0,1) plt.scatter(s1, s2, marker = '.', s=50, c = 'black') plt.xlabel('task 1 sen.', fontsize = 25) plt.ylabel('task 2 sen.', fontsize = 25)
def Energy_Flow(Time_Series): Energy_Flow = {'Energy_Demand':0, 'Lost Load':0, 'Energy PV':0,'Curtailment':0, 'Energy Diesel':0, 'Discharge energy from the Battery':0, 'Charge energy to the Battery':0} for v in Energy_Flow.keys(): if v == 'Energy PV': Energy_Flow[v] = round((Time_Series[v].sum() - Time_Series['Curtailment'].sum()- Time_Series['Charge energy to the Battery'].sum())/1000000, 2) else: Energy_Flow[v] = round((Time_Series[v].sum())/1000000, 2) c = ['From Generator', 'To Battery', 'Demand', 'From PV', 'From Battery', 'Curtailment', 'Lost Load'] plt.figure() plt.bar((1,2,3,4,5,6,7), Energy_Flow.values(), color= 'b', alpha=0.3, align='center') plt.xticks((1.2,2.2,3.2,4.2,5.2,6.2,7.2), c) plt.xlabel('Technology') plt.ylabel('Energy Flow (MWh)') plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='on') plt.xticks(rotation=-30) plt.savefig('Results/Energy_Flow.png', bbox_inches='tight') plt.show() return Energy_Flow
def paramagg(data): ''' USE: paramagg(df) Provides an overview in one plot for a parameter scan. Useful to understand rough distribution of accuracacy and loss for both test and train. data = a pandas dataframe from hyperscan() ''' plt.figure(num=None, figsize=(8, 8), dpi=80, facecolor='w', edgecolor='k') plt.scatter(data.train_loss, data.train_acc, label='train') plt.scatter(data.test_loss, data.test_acc, label='test') plt.legend(loc='upper right') plt.tick_params(axis='both', which='major', pad=15) plt.xlabel('loss', fontsize=18, labelpad=15, color="gray") plt.ylabel('accuracy', fontsize=18, labelpad=15, color="gray") plt.show()
def finalize_plot(allticks,handles): plt.locator_params(axis='x', nticks=Noracles,nbins=Noracles) plt.yticks([x[0] for x in allticks], [x[1] for x in allticks]) plt.tick_params( axis='y', # changes apply to the x-axis which='both', # both major and minor ticks are affected left='off', # ticks along the bottom edge are off right='off' # ticks along the top edge are off ) if LEGEND: plt.legend([h[0] for h in handles],seriesnames, loc='upper right',borderaxespad=0., ncol=1,fontsize=10,numpoints=1) plt.gcf().tight_layout() ###################################################### # Data processing
def draw_dual_line_graph(title, x_label, y_label, y_axis_1, y_axis_2, line_1_label, line_2_label, output_path): x_axis = np.arange(0, len(y_axis_1)) fig = plt.figure() fig.suptitle(title, fontsize=14, fontweight='bold') ax = fig.add_subplot(111) ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.plot(x_axis, y_axis_1, 'b') ax.plot(x_axis, y_axis_2, 'g', alpha=0.7) ax.legend([line_1_label, line_2_label], loc='center', bbox_to_anchor=(0.5, -0.18), ncol=2) ax.axis([0, np.amax(x_axis), 0, np.log(2) + .001]) plt.margins(0.2) plt.tick_params(labelsize=10) fig.subplots_adjust(bottom=0.2) plt.savefig(output_path + '.eps', format='eps') plt.savefig(output_path) plt.close(fig)
def plot_shot(data): plt.figure(figsize=(12,11)) plt.scatter(data.LOC_X, data.LOC_Y, c=data.shot_zone_range_area, s=30) draw_court() # Adjust plot limits to just fit in half court plt.xlim(-250,250) # Descending values along th y axis from bottom to top # in order to place the hoop by the top of plot plt.ylim(422.5, -47.5) # get rid of axis tick labels # plt.tick_params(labelbottom=False, labelleft=False) plt.savefig('./data/img/half/fully_converted_with_range_areas.jpg') plt.close() ########################################################################### # Visualization of court: http://savvastjortjoglou.com/nba-shot-sharts.html ###########################################################################
def plot_half_court_movement(data): plt.figure(figsize=(12,11)) plt.scatter(data.x_loc, data.y_loc, c=data.game_clock, cmap=plt.cm.Blues, s=250, zorder=1) draw_half_court() # Adjust plot limits to just fit in half court plt.xlim(-250,250) # Descending values along th y axis from bottom to top # in order to place the hoop by the top of plot plt.ylim(422.5, -47.5) # get rid of axis tick labels # plt.tick_params(labelbottom=False, labelleft=False) plt.savefig('./data/img/half/event_movement_convert_half.jpg') plt.close() ######################################################################## # Convert all full court coordinates in data to half court coordinates ########################################################################
def visualizeFeatures(Features, Files, Names): y_eig, coeff = pcaDimRed(Features, 2) plt.close("all") print y_eig plt.subplot(2,1,1); ax = plt.gca() for i in range(len(Files)): im = cv2.imread(Files[i], cv2.CV_LOAD_IMAGE_COLOR) Width = 0.2; Height = 0.2; startX = y_eig[i][0]; startY = y_eig[i][1]; print startX, startY myaximage = ax.imshow(cv2.cvtColor(im, cv2.cv.CV_RGB2BGR), extent=(startX-Width/2.0, startX+Width/2.0, startY-Height/2.0, startY+Height/2.0), alpha=1.0, zorder=-1) plt.axis((-3,3,-3,3)) # Plot feaures plt.subplot(2,1,2) ax = plt.gca() for i in range(len(Files)): plt.plot(numpy.array(Features[i,:].T)); plt.xticks(range(len(Names))) plt.legend(Files) ax.set_xticklabels(Names) plt.setp(plt.xticks()[1], rotation=90) plt.tick_params(axis='both', which='major', labelsize=8) plt.tick_params(axis='both', which='minor', labelsize=8) plt.show()
def plot_positions(df, img_path, frame, cam): color_dict = {'car': '#fc8d59', 'bus': '#ffffbf', 'person': '#91cf60'} frame_pos = df[(df['frame'] == frame) & (df['cam'] == cam)] fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') im = plt.imread(img_path) ax.imshow(im) for i, f in frame_pos.iterrows(): add_rect(ax, f['x'], f['y'], f['w'], f['h'], color=color_dict[f['class_name']], name=f['id']) legend_handles = [] for k, v in color_dict.iteritems(): handle = patches.Patch(color=v, label=k) legend_handles.append(handle) plt.legend(loc=0, handles=legend_handles) plt.xlim((0, 360)) plt.ylim((0, 288)) plt.ylim(plt.ylim()[::-1]) plt.tight_layout() plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off') plt.show()
def plot_image(): std = np.std(stamp[stamp==stamp]) plt.imshow(stamp, interpolation='nearest', origin = 'lower', vmin = -1.*std, vmax = 3.*std, cmap='bone') plt.tick_params(axis='both', which='major', labelsize=8) circle0 = plt.Circle((dx,dy),0.1) x1, y1 = centroid_com(stamp) circle1 = plt.Circle((x1,y1),0.1,color='r') ax.add_artist(circle1) x2, y2 = centroid_1dg(stamp) circle2 = plt.Circle((x2,y2),0.1,color='b') ax.add_artist(circle2) x3, y3 = centroid_2dg(stamp) circle3 = plt.Circle((x3,y3),0.1,color='g') ax.add_artist(circle3) print(x1, x2, x3) print(y1, y2, y3) # define the directory that contains the images
def plot_image(): std = np.std(stamp[stamp==stamp]) plt.imshow(stamp, interpolation='nearest', origin = 'lower', vmin = -1.*std, vmax = 3.*std, cmap='bone') plt.tick_params(axis='both', which='major', labelsize=8) circle0 = plt.Circle((dx,dy),0.1) x1, y1 = centroid_com(stamp) circle1 = plt.Circle((x1,y1),0.1,color='r') ax.add_artist(circle1) x2, y2 = centroid_1dg(stamp) circle2 = plt.Circle((x2,y2),0.1,color='b') ax.add_artist(circle2) x3, y3 = centroid_2dg(stamp) circle3 = plt.Circle((x3,y3),0.1,color='g') ax.add_artist(circle3) return ((x1, y1),(x2, y2),(x3, y3)) #print(x1, x2, x3) #print('now some y values') #print(y1, y2, y3) # define the directory that contains the images
def swarm(data,x,y,xscale='linear',yscale='linear'): # set default pretty settings from Seaborn sns.set(style="white", palette="muted") sns.set_context("notebook", font_scale=1, rc={"lines.linewidth": 0.2}) # createthe plot g = sns.swarmplot(x=x, y=y, data=data, palette='RdYlGn') plt.tick_params(axis='both', which='major', pad=10) g.set(xscale=xscale) g.set(yscale=yscale) # Setting plot limits start = data[y].min().min() plt.ylim(start,); sns.despine()
def correlation(data,title=''): corr = data.corr(method='spearman') mask = np.zeros_like(corr) mask[np.triu_indices_from(mask)] = True sns.set(style="white") sns.set_context("notebook", font_scale=2, rc={"lines.linewidth": 0.3}) rcParams['figure.figsize'] = 25, 12 rcParams['font.family'] = 'Verdana' rcParams['figure.dpi'] = 300 g = sns.heatmap(corr, mask=mask, linewidths=1, cmap="RdYlGn", annot=False) g.set_xticklabels(data,rotation=25,ha="right"); plt.tick_params(axis='both', which='major', pad=15);
def plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=plt.cm.Blues): plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.tick_params(labelsize=6) plt.title(title) plt.colorbar() tick_marks = np.arange(len(target_names)) plt.xticks(tick_marks, target_names, rotation=90) plt.yticks(tick_marks, target_names) thresh = cm.max() / 2. for i, j in product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, round(cm[i, j], 2), horizontalalignment='center', color='white' if cm[i, j] > thresh else 'black', fontsize=5) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')
def plot(L): xlim = [-2.0, +2.0] x = numpy.linspace(xlim[0], xlim[1], 500) vals = tree(L, x) for val in vals: plt.plot(x, val) plt.xlim(*xlim) # plt.ylim(-2, +2) plt.tick_params( axis='both', which='both', bottom='off', top='off', left='off', right='off', labelbottom='off', labelleft='off' ) plt.grid() return
def plot_bar_chart(values, labels): fig, ax = plt.subplots(figsize=(6,4.5)) N = len(values) ind = np.arange(N) width = 0.75 ax.bar(ind, values, width, color='#FFB7AA', edgecolor='none') ax.set_xticks(ind + width) ax.set_xticklabels(labels) # make plot prettier ax.spines["top"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) plt.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="on", left="off", right="off", labelleft="on") plt.xticks(rotation=35, ha='right') plt.title('The 20 Most Common Taylor Swift Words') plt.xlabel('Word (excl stop words)') plt.ylabel('Uses per song') plt.savefig('top_words.png', bbox_inches='tight')
def show(self, idx=0, time=None, wavelet=None): """ Plot the wavelet of the specified source. :param idx: Index of the source point for which to plot wavelet :param wavelet: Prescribed wavelet instead of one from this symbol :param time: Prescribed time instead of time from this symbol """ wavelet = wavelet or self.data[:, idx] time = time or self.time plt.figure() plt.plot(time, wavelet) plt.xlabel('Time (ms)') plt.ylabel('Amplitude') plt.tick_params() plt.show()
def draw_diam_plot(orig_g, mG): df = pd.DataFrame(mG) gD = bfs_eff_diam(orig_g, 20, .9) ori_degree_seq = [] for i in range(0, len(max(mG))): ori_degree_seq.append(gD) plt.fill_between(df.columns, df.mean() - df.sem(), df.mean() + df.sem(), color='blue', alpha=0.2, label="se") h, = plt.plot(df.mean(), color='blue', aa=True, linewidth=4, ls='--', label="H*") orig, = plt.plot(ori_degree_seq, color='black', linewidth=2, ls='-', label="H") plt.title('Diameter Plot') plt.ylabel('Diameter') plt.xlabel('Growth') plt.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='off', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='off') # labels along the bottom edge are off plt.legend([orig, h], ['$H$', 'HRG $H^*$'], loc=4) # fig = plt.gcf() # fig.set_size_inches(5, 4, forward=True) plt.show()
def plot_sen_spe(dic_sen, dic_spe, vals = None): """ """ label = {'single': 'Single', 'accum': 'Accum', 'multi': 'Multi'} marker = {'single': '.', 'accum': 'x', 'multi': 's'} algo = ['single', 'accum', 'multi'] if vals == None: vals = [64, 323, 1295, 6476] plt.xlim(0,3) plt.ylim(0, 0.3) for a in algo: y = [] for v in vals: x = np.mean(dic_sen[(v, a)]) y.append(x) print a, y plt.plot([0, 1, 2, 3], y, label = label[a], marker = marker[a], markersize = 15, linewidth = 5) plt.xlabel('Percentage of target task labels', fontsize = 25) plt.ylabel('RMSE', fontsize = 30) plt.legend(loc = 'upper right', fontsize = 30) plt.tick_params(labelsize = 25) plt.xticks([0,1,2,3], [1, 5, 20, 100]) plt.yticks((0, 0.15, 0.3), ("0", "0.15", "0.3")) #plt.set_xticklabels(['1','','5','','20','','100'])
def Percentage_Of_Use(Time_Series): ''' This model creates a plot with the percentage of the time that each technologies is activate during the analized time. :param Time_series: The results of the optimization model that depend of the periods. ''' # Creation of the technolgy dictonary PercentageOfUse= {'Lost Load':0, 'Energy PV':0,'Curtailment':0, 'Energy Diesel':0, 'Discharge energy from the Battery':0, 'Charge energy to the Battery':0} # Count the quantity of times each technology has energy production for v in PercentageOfUse.keys(): foo = 0 for i in range(len(Time_Series)): if Time_Series[v][i]>0: foo = foo + 1 PercentageOfUse[v] = (round((foo/float(len(Time_Series))), 3))*100 # Create the names in the plot c = ['From Generator', 'Curtailment', 'To Battery', 'From PV', 'From Battery', 'Lost Load'] # Create the bar plot plt.figure() plt.bar((1,2,3,4,5,6), PercentageOfUse.values(), color= 'b', alpha=0.5, align='center') plt.xticks((1.2,2.2,3.2,4.2,5.2,6.2), c) # Put the names and position for the ticks in the x axis plt.xticks(rotation=-30) # Rotate the ticks plt.xlabel('Technology') # Create a label for the x axis plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='on') plt.ylabel('Percentage of use (%)') # Create a label for the y axis plt.savefig('Results/Percentge_of_Use.png', bbox_inches='tight') # Save the plot plt.show() return PercentageOfUse
def create_summary_graph(title, y_axis_label, labels, values): """Create summary (column) graph for any measurement.""" N = len(values) indexes = np.arange(N) fig = plt.figure() plt.xlabel("call #") plt.ylabel(y_axis_label) plt.grid(True) plt.xticks(indexes, labels) locs, plt_labels = plt.xticks() plt.setp(plt_labels, rotation=90) plt.bar(indexes, values, 0.80, color='yellow', edgecolor='black', label=title) # plt.legend(loc='lower right') for tick in plt_labels: tick.set_horizontalalignment("left") tick.set_verticalalignment("top") tick.set_visible(False) for tick in plt_labels[::5]: tick.set_visible(True) plt.tick_params(axis='x', which='major', labelsize=10) fig.subplots_adjust(bottom=0.4) fig.suptitle(title) return fig
def create_statistic_graph(title, y_axis_label, labels, min_values, max_values, avg_values, x_axis_label="pause time (seconds)", width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, dpi=DPI): """Create summary (column) graph with min, average, and max values.""" N = len(labels) indexes = np.arange(N) fig = plt.figure(figsize=(1.0 * width / dpi, 1.0 * height / dpi), dpi=dpi) plt.xlabel(x_axis_label) plt.ylabel(y_axis_label) plt.grid(True) plt.xticks(indexes, labels) locs, plt_labels = plt.xticks() plt.setp(plt_labels, rotation=90) plt.bar(indexes - 0.27, min_values, 0.25, color='red', edgecolor='black', label='min values') plt.bar(indexes, avg_values, 0.25, color='yellow', edgecolor='black', label='avg values') plt.bar(indexes + 0.27, max_values, 0.25, color='green', edgecolor='black', label='max values') plt.legend(loc='upper left') for tick in plt_labels: tick.set_horizontalalignment("left") tick.set_verticalalignment("top") plt.tick_params(axis='x', which='major', labelsize=10) # fig.subplots_adjust(bottom=0.4) fig.suptitle(title) return fig
def lstm_plot(predicted_data, true_data, prediction_len=None): fig = plt.figure(facecolor='white', figsize=(16, 4)) ax = fig.add_subplot(111) ax.plot(true_data, label='True Data') plt.tick_params(axis='both', which='major', pad=15) plt.plot(predicted_data, label='Prediction') plt.legend() plt.show()
def histplot(x, y, bins=50): plt.figure(num=None, figsize=(16, 4), dpi=80, facecolor='w', edgecolor='k') plt.hist(y, bins=bins, label='actual') plt.hist(x, bins=bins, label='prediction', alpha=.8) plt.grid(b=False) plt.tick_params(axis='both', which='major', pad=15) plt.legend() plt.show()
def prediction_distribution(x, bins): plt.figure(num=None, figsize=(16, 4), dpi=80, facecolor='w', edgecolor='k') plt.hist(x, bins=bins, label='prediction') plt.grid(b=False) plt.tick_params(axis='both', which='major', pad=15) plt.legend() plt.show()
def _ticks_off(): plt.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='off', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='off') # labels along the bottom edge are off plt.tick_params( axis='y', # changes apply to the x-axis which='both', # both major and minor ticks are affected left='off', # ticks along the bottom edge are off right='off', # ticks along the top edge are off labelleft='off') # labels along the bottom edge are off
def plot_validate(data_true, data_predicted, xlab, ylab, name, n_bins, x_range, y_range, font = 15, legend = False, bar_width = 0.4): hist_true, bin_edges = np.histogram(data_true, bins=n_bins, range=x_range) hist_predicted, bin_edges = np.histogram(data_predicted, bins=n_bins, range=x_range) hist_true = hist_true / float(sum(hist_true)) hist_predicted = hist_predicted / float(sum(hist_predicted)) plt.figure(num=None, figsize=(8, 6), dpi=150, facecolor='w', edgecolor='w') plt.bar(bin_edges[:-1],hist_true, bar_width,color="#60BD68",label='Actual Data') plt.bar(bin_edges[:-1]+bar_width,hist_predicted,bar_width,color="#FAA43A",alpha=1,label='Simulated Data') plt.xlabel(xlab, fontsize=font, labelpad=15) if ylab: plt.ylabel(ylab, fontsize=font, labelpad=15) plt.xlim(x_range[0], x_range[1]) plt.ylim(y_range[0], y_range[1]) xt_val = list(set([int(e) for e in bin_edges[:-1]])) xt_pos = [float(e) + bar_width for e in xt_val] plt.tick_params(axis='both', which='major', labelsize=15) plt.tick_params(axis='both', which='minor', labelsize=15) plt.xticks(xt_pos, xt_val) if legend: plt.legend(fontsize=font) plt.savefig(name, bbox_inches='tight') plt.close() # PERCENTILE KL DIVERGENCE BOOTSTRAP TEST
def roc(y_label,y_score,name): fpr = dict() tpr = dict() thresholds = dict() roc_auc = dict() for i in range(2): fpr[i], tpr[i], thresholds[i] = roc_curve(y_label[:, i], y_score[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) ind_max = np.argmax(1 - fpr[1] + tpr[1]) # Compute micro-average ROC curve and ROC area fpr["micro"], tpr["micro"], _ = roc_curve(y_label.ravel(), y_score.ravel()) roc_auc["micro"] = auc(fpr["micro"], tpr["micro"]) # Plot of a ROC curve for a specific class plt.figure(num=None, figsize=(8, 6), dpi=150, facecolor='w', edgecolor='w') plt.plot(fpr[1], tpr[1], label='ROC Curve (Area = %0.2f)' % roc_auc[1],color="g") plt.plot([fpr[1][ind_max], fpr[1][ind_max]], [fpr[1][ind_max], tpr[1][ind_max]], 'k:') plt.annotate(r'$\bf J$', xy=(fpr[1][ind_max]-0.04, (fpr[1][ind_max] + tpr[1][ind_max])/2), color='black', fontsize=20) plt.plot(fpr[1][ind_max], tpr[1][ind_max], marker ='v', markersize=10, linestyle='None', color='brown', label="Decision Threshold (DT),\nMax. Youden's J Statistic") plt.annotate('DT: %0.2f\nTPR: %0.2f\nFPR: %0.2f' % (thresholds[1][ind_max], tpr[1][ind_max], fpr[1][ind_max]), xy=(fpr[1][ind_max]+0.015, tpr[1][ind_max]-0.175), color='black', fontsize=20) plt.plot([0, 1], [0, 1], 'k--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.tick_params(axis='both', which='major', labelsize=15) plt.tick_params(axis='both', which='minor', labelsize=15) plt.xlabel('False Positive Rate (1 - Specificity)',fontsize=20, labelpad=15) plt.ylabel('True Positive Rate (Sensitivity)',fontsize=20, labelpad=15) plt.legend(loc="lower right",fontsize=20,numpoints=1) plt.savefig(name, bbox_inches='tight') plt.close()
def get_system_size_plot(self): """ Returns a plot of the system size versus the number of energy calculations, as a matplotlib plot object. """ # set the font to Times, rendered with Latex plt.rc('font', **{'family': 'serif', 'serif': ['Times']}) plt.rc('text', usetex=True) # parse the compositions and numbers of energy calculations compositions = [] num_calcs = [] for i in range(4, len(self.lines)): line = self.lines[i].split() compositions.append(line[1]) num_calcs.append(int(line[4])) # get the numbers of atoms from the compositions nums_atoms = [] for composition in compositions: comp = Composition(composition) nums_atoms.append(comp.num_atoms) # make the plot plt.plot(num_calcs, nums_atoms, 'D', markersize=5, markeredgecolor='blue', markerfacecolor='blue') plt.xlabel(r'Number of energy calculations', fontsize=22) plt.ylabel(r'Number of atoms in the cell', fontsize=22) plt.tick_params(which='both', width=1, labelsize=18) plt.tick_params(which='major', length=8) plt.tick_params(which='minor', length=4) plt.xlim(xmin=0) plt.ylim(ymin=0) plt.tight_layout() return plt
def draw_scatter_graph(title, x_label, y_label, x_axis, y_axis, min_x, max_x, min_y, max_y, output_path): fig = plt.figure() fig.suptitle(title, fontsize=14, fontweight='bold') ax = fig.add_subplot(111) ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.plot(x_axis, y_axis, 'o') ax.axis([min_x, max_x, min_y, max_y]) plt.margins(0.2) plt.tick_params(labelsize=10) fig.subplots_adjust(bottom=0.2) plt.savefig(output_path) plt.close(fig)
def plot_variance_cuve(): ################# plot for variance ########################## K = 5 alpha = a = 0.3 all_num = 1000 b = np.linspace(0, 20, num=all_num) # print upper_incomplete_gamma_function(0.1, 1) # print uppergamma(0.1, 1) # a = uppergamma(0.1, 1) # print float(a) # print compute_gdir_variance(K, a, 1) symmetric_dir_var = [compute_symmetric_dir_variance(K, alpha)] * all_num gdir_var = [compute_gdir_variance(K, a, local_b) for local_b in b] # print gdir_var save_path = os.path.dirname(__file__) + '/res_gdir/res_variance' plt.figure(1) plt.rc('xtick', labelsize=20) plt.rc('ytick', labelsize=20) plt.tick_params(axis='both', which='major', labelsize=20) plt.plot(b, gdir_var) plt.plot(b, symmetric_dir_var) plt.plot((a, a), (0, 1./K), 'k-') plt.savefig(save_path + '/gdir_K{}_a{}.png'.format(K, a)) plt.savefig(save_path + '/gdir_K{}_a{}.pdf'.format(K, a)) plt.show()
def plot_error_histogram(df): ''' Input: DataFrame that contains a 'error_in_miles' column Output: Histogram of errors ''' plt.figure(figsize=(11,7)) plt.hist(df['error_in_miles'], bins=20, normed=1) plt.xlabel('Error in miles', fontsize=20) plt.ylabel('Percentage', fontsize=22) plt.tick_params(labelsize=14) plt.show()
def create_plot(self): 'create the plot' if self.settings.plot_mode != PlotSettings.PLOT_NONE and self.settings.plot_mode != PlotSettings.PLOT_MATLAB: self.fig, self.axes = plt.subplots(nrows=1, figsize=self.settings.plot_size) ha = self.engine.hybrid_automaton title = self.settings.label.title title = title if title is not None else ha.name x_label = self.settings.label.x_label x_label = x_label if x_label is not None else ha.variables[self.settings.xdim].capitalize() y_label = self.settings.label.y_label y_label = y_label if y_label is not None else ha.variables[self.settings.ydim].capitalize() self.axes.set_xlabel(x_label, fontsize=self.settings.label.label_size) self.axes.set_ylabel(y_label, fontsize=self.settings.label.label_size) self.axes.set_title(title, fontsize=self.settings.label.title_size) if self.settings.label.axes_limits is not None: # hardcoded axes limits xmin, xmax, ymin, ymax = self.settings.label.axes_limits self.axes.set_xlim(xmin, xmax) self.axes.set_ylim(ymin, ymax) if self.settings.grid: self.axes.grid(True) # make the x and y axis animated in case of rescaling self.axes.xaxis.set_animated(True) self.axes.yaxis.set_animated(True) plt.tick_params(axis='both', which='major', labelsize=self.settings.label.tick_label_size) plt.tight_layout() self.shapes = DrawnShapes(self)
def TriAndPaint(img, points, outputIMG): tri = Delaunay(points) triList = points[tri.simplices] cMap = ListedColormap( np.array([ChooseColor(img, tr) for tr in triList])) # use core rgb # center = np.sum(points[tri.simplices], axis=1) / 3 # print(center) # cMap = ListedColormap( # np.array([img.getpixel((x, y)) for x, y in center]) / 256) color = np.array(range(len(triList))) # print(color) width, height = img.size plt.figure(figsize=(width, height), dpi=1) plt.tripcolor(points[:, 0], points[:, 1], tri.simplices.copy(), facecolors=color, cmap=cMap) # plt.tick_params(labelbottom='off', labelleft='off', # left='off', right='off', bottom='off', top='off') # plt.tight_layout(pad=0) plt.axis('off') plt.subplots_adjust(left=0, right=1, top=1, bottom=0) plt.xlim(0, width) plt.ylim(0, height) plt.gca().invert_yaxis() plt.savefig(outputIMG) # uncomment show() if you want to view when it's done # plt.show()
def scat_plot(): f = plt.figure() # filename = 'MLP5_dap_multi_' + str(plate) + '_quicklook.pdf' mpl5_dir = os.environ['MANGADIR_MPL5'] drp = fits.open(mpl5_dir + 'drpall-v2_0_1.fits') drpdata = drp[1].data absmag = drpdata.field('nsa_elpetro_absmag') plt.xlim(-16,-24) plt.ylim(1,7) plt.scatter(absmag[:,5], absmag[:,1]-absmag[:,5], marker='.',color=['blue'], s=0.5) plt.xlabel('i-band absolute magnitude', fontsize=16) plt.ylabel('NUV - i', fontsize=16) plt.tick_params(axis='both', labelsize=14) ifu_list = drpdata.field('plateifu') for i in good_galaxies: ithname = str(i[0]) + str(i[1]) for e in range(0, len(ifu_list)): ethname = ifu_list[e] ethname = ethname.replace("-","") if ithname == ethname: plt.scatter(absmag[e, 5], absmag[e, 1] - absmag[e, 5], marker='*',color=['red']) f.savefig("scatter.pdf", bbox_inches='tight') # pp = PdfPages('scatter.pdf') # pp.savefig(plot_1) plt.close() os.system("open %s &" % 'scatter.pdf')
def plot_image(): std = np.std(stamp[stamp==stamp]) plt.imshow(stamp, interpolation='nearest', origin = 'lower', vmin = -1.*std, vmax = 3.*std, cmap='bone') plt.tick_params(axis='both', which='major', labelsize=8) # define the directory that contains the images
def plot_image(stamp): std = np.std(stamp[stamp==stamp]) plt.imshow(stamp, interpolation='nearest', origin = 'lower', vmin = -1.*std, vmax = 3.*std, cmap='bone') plt.tick_params(axis='both', which='major', labelsize=8) # define the directory that contains the images
def plot_image(): std = np.std(stamp[stamp==stamp]) plt.imshow(stamp, interpolation='nearest', origin = 'lower', vmin = -1.*std, vmax = 3.*std, cmap='bone') plt.tick_params(axis='both', which='major', labelsize=8) # define a function for the gaussian model
def plot_image(): std = np.std(stamp[stamp==stamp]) plt.imshow(stamp, interpolation='nearest', origin = 'lower', vmin = -1.*std, vmax = 3.*std, cmap='Greys') plt.tick_params(axis='both', which='major', labelsize=8)
def draw_digit(data, n, row, col, title): import matplotlib.pyplot as plt size = 28 plt.subplot(row, col, n) Z = data.reshape(size,size) # convert from vector to 28x28 matrix Z = Z[::-1,:] # flip vertical plt.xlim(0,28) plt.ylim(0,28) plt.pcolor(Z) plt.title("title=%s"%(title), size=8) plt.gray() plt.tick_params(labelbottom="off") plt.tick_params(labelleft="off")
def kde(x,y,title='',color='YlGnBu',xscale='linear',yscale='linear'): sns.set_style('white') sns.set_context('notebook', font_scale=1, rc={"lines.linewidth": 0.5}) g = sns.kdeplot(x,y,shade=True, cut=2, cmap=color, shade_lowest=False, legend=True, set_title="test") plt.tick_params(axis='both', which='major', pad=10) sns.plt.title(title) g.set(xscale=xscale) g.set(yscale=yscale) sns.despine()