我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用matplotlib.pyplot.locator_params()。
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 _show_plot(x_values, y_values, x_labels=None, y_labels=None): try: import matplotlib.pyplot as plt except ImportError: raise ImportError('The plot function requires matplotlib to be installed.' 'See http://matplotlib.org/') plt.locator_params(axis='y', nbins=3) axes = plt.axes() axes.yaxis.grid() plt.plot(x_values, y_values, 'ro', color='red') plt.ylim(ymin=-1.2, ymax=1.2) plt.tight_layout(pad=5) if x_labels: plt.xticks(x_values, x_labels, rotation='vertical') if y_labels: plt.yticks([-1, 0, 1], y_labels, rotation='horizontal') # Pad margins so that markers are not clipped by the axes plt.margins(0.2) plt.show() #//////////////////////////////////////////////////////////// #{ Parsing and conversion functions #////////////////////////////////////////////////////////////
def multi_datapoint_line_graph(jruby_metrics_series, config): plt.clf() x_pos = np.arange(len(jruby_metrics_series)) img_file = config['img_file'] x_labels = map(lambda x: time.strftime('%H:%M:%S', time.localtime(x)), jruby_metrics_series.get_timestamps()) metrics = config['metrics'] for metric in metrics: data_points = jruby_metrics_series.get_data_points(metric) plt.plot(x_pos, data_points, label=metric) plt.xlabel('Data points') plt.xticks(x_pos, x_labels) plt.locator_params(axis='x', nbins=10) plt.ylabel(config['y-label']) plt.title(config['title']) plt.legend(loc='upper left') plt.tight_layout() plt.savefig(img_file)
def user_distance_difference_graphs(community): ''' user to internal against user to external distance graphs, puts plotted data into community directories ''' comm_doc_vecs = open_community_document_vectors_file(os.path.join(community, 'community_doc_vecs.json')) if(len(comm_doc_vecs) <= 1): return out_path = os.path.join(community, 'distance_difference_graphs/jensen_shannon/') if not os.path.exists(os.path.dirname(out_path)): os.makedirs(os.path.dirname(out_path), 0o755) int_dists = os.path.join(community, 'calculated_distances/jensen_shannon') ext_dists = os.path.join(community, 'calculated_distances/jensen_shannon_ext') int_df = pd.read_csv(int_dists, sep='\t', header=None, names=['user_a', 'user_b', 'distance']) ext_df = pd.read_csv(ext_dists, sep='\t', header=None, names=['user_a', 'user_b', 'distance']) for user in comm_doc_vecs: if not os.path.exists(os.path.join(out_path, user + '.png')): df = int_df[(int_df.user_a == int(user)) | (int_df.user_b == int(user))] y_axis = df['distance'].tolist() plt.plot(np.arange(0, len(y_axis)), y_axis, 'b') df = ext_df[ext_df.user_a == int(user)] y_axis = df['distance'].tolist() plt.plot(np.arange(0, len(y_axis)), y_axis, 'g') plt.ylabel('Divergence') plt.title('Divergence from ' + user + ' to Internal & External Users') plt.ylim([0, np.log(2)]) plt.xlabel('Users') plt.xlim([0, len(y_axis) - 1]) plt.legend(['Internal', 'External'], loc='center', bbox_to_anchor=(0.5, -0.18), ncol=2) plt.locator_params(nbins=25) plt.subplots_adjust(bottom=0.2) plt.savefig(out_path + user) plt.savefig(out_path + user + '.eps', format='eps') plt.close()
def multi_datapoint_line_graph(http_metrics_series, config): plt.clf() x_pos = np.arange(len(http_metrics_series)) data_field = config['data_field'] data_label = config['data_label'] img_file = config['img_file'] x_labels = map(lambda x: time.strftime('%H:%M:%S', time.localtime(x)), http_metrics_series.get_timestamps()) catalog = http_metrics_series.get_data_points('puppet-v3-catalog-/*/', data_field) plt.plot(x_pos, catalog, label='catalog') node = http_metrics_series.get_data_points('puppet-v3-node-/*/', data_field) plt.plot(x_pos, node, label='node') report = http_metrics_series.get_data_points('puppet-v3-report-/*/', data_field) plt.plot(x_pos, report, label='report') file_metadatas = http_metrics_series.get_data_points('puppet-v3-file_metadatas-/*/', data_field) plt.plot(x_pos, file_metadatas, label='file_metadatas') file_metadata = http_metrics_series.get_data_points('puppet-v3-file_metadata-/*/', data_field) plt.plot(x_pos, file_metadata, label='file_metadata') plt.xlabel('Data points') plt.xticks(x_pos, x_labels) plt.locator_params(axis='x', nbins=10) plt.ylabel('{0} Response Time (ms)'.format(data_label)) plt.title('{0} Request Response Time'.format(data_label)) plt.legend(loc='upper left') plt.tight_layout() plt.savefig(img_file)
def multi_datapoint_line_graph(memory_metrics_series, config): plt.clf() x_pos = np.arange(len(memory_metrics_series)) img_file = config['img_file'] x_labels = map(lambda x: time.strftime('%H:%M:%S', time.localtime(x)), memory_metrics_series.get_timestamps()) heap_max = memory_metrics_series.get_data_points('heap', 'max') plt.plot(x_pos, heap_max, label='Heap - Max') heap_init = memory_metrics_series.get_data_points('heap', 'init') plt.plot(x_pos, heap_init, label='Heap - Init') heap_committed = memory_metrics_series.get_data_points('heap', 'committed') plt.plot(x_pos, heap_committed, label='Heap - Committed') heap_used = memory_metrics_series.get_data_points('heap', 'used') plt.plot(x_pos, heap_used, label='Heap - Used') nonheap_max = memory_metrics_series.get_data_points('nonheap', 'max') plt.plot(x_pos, nonheap_max, label='Non-Heap - Max') nonheap_init = memory_metrics_series.get_data_points('nonheap', 'init') plt.plot(x_pos, nonheap_init, label='Non-Heap - Init') nonheap_committed = memory_metrics_series.get_data_points('nonheap', 'committed') plt.plot(x_pos, nonheap_committed, label='Non-Heap - Committed') nonheap_used = memory_metrics_series.get_data_points('nonheap', 'used') plt.plot(x_pos, nonheap_used, label='Non-Heap - Used') plt.xlabel('Data points') plt.xticks(x_pos, x_labels) plt.locator_params(axis='x', nbins=10) plt.ylabel('Memory Usage (MB)') plt.title('Memory Usage') plt.legend(loc='upper left') plt.tight_layout() plt.savefig(img_file)
def plotPopulationSize(popSize): # Population size plot plt.figure(3) plt.xlabel('Number of beads') plt.locator_params(axis='x',nbins=4) plt.xlim([0,c.nBeads]) if(c.PERM): plt.ylabel('Population') plt.plot(popSize, linewidth=2) else: plt.ylabel('Fraction alive') plt.plot(popSize/c.nPolymers, linewidth=2) plt.ylim(0,1)
def plot_backtest_result_curve(log_file): data_dict = read_result_from_log(log_file) #benchmark_dates, benchmark_value = sort_dict_buy_key(data_dict) portfolio_history_data = pd.DataFrame(data_dict).T portfolio_history_data.columns = ['total_value', 'cash', 'stock_value', 'bench_value'] dates_ = list(portfolio_history_data.index) dates_.pop() dates = [] for d in dates_: if d == None: d = config.start_date date = datetime.datetime.strptime(d, '%Y-%m-%d').date() dates.append(date) #dates = [datetime.datetime.strptime(d, '%Y-%m-%d').date() for d in dates if d != None else config.start_date] total_value = list(portfolio_history_data["total_value"].values) cash = list(portfolio_history_data["cash"].values) cash_value = list(portfolio_history_data["stock_value"].values) bench_value = list(portfolio_history_data["bench_value"].values) total_value.pop() bench_value.pop() # xaxis tick formatter plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) # xaxis ticks #plt.gca().xaxis.set_major_locator(mdates.MonthLocator()) # figure title and legend plt.gca().legend() plt.gca().set(title="event factor backtesting porfolio value", ylabel = "porfolio total value", xlabel = "backtesting time") plt.locator_params(axis='x', nticks=10) plt.plot(dates, total_value) plt.plot(dates, bench_value) plt.gcf().autofmt_xdate() plt.show() #data = read_result_from_log(sys.argv[1]) #plot_backtest_result_curve(data)
def try_plot_molecule_hist(args): try: import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import json import numpy as np from statsmodels.nonparametric.smoothers_lowess import lowess ## final plot name plot_name = os.path.join( args.parent_dir, "stats", "molecule_lengths.pdf" ) mol_fn = os.path.join( args.parent_dir, "stats", "histogram_molecules.json" ) mol_dict = json.loads(open( mol_fn, "r" ).read()) if mol_dict["numbins"] > 0: xmin = 0 ## min length kb xmax = 300 ## max length kb binsize=1 ## bin size of hist in kb ## compute length-weighted histogram lwhist = [] for x, v in enumerate( mol_dict["vals"] ): lwhist.append( (x + 0.5)* v ) ## truncate lwhist = lwhist[:xmax] ## normalize norm = sum(lwhist) lwhist = np.array([100*x/norm for x in lwhist]) ## lowess smoothing xvalues = np.arange(0, xmax, 1) + 0.5 newhist = lowess(lwhist, xvalues, frac=0.1, return_sorted=False) ## do the plotting fig, ax = plt.subplots() ## set up axis, grid ax.grid(True) plt.locator_params( 'x', nbins=10 ) plt.locator_params( 'y', nbins=10 ) plt.plot ( newhist, **{"lw": 2, "ls": "-", "color": "blue"} ) plt.xlim( xmin, xmax ) plt.ylim( 0, None ) plt.xlabel ( "Inferred molecule length (kb)") plt.ylabel ( "Percent of total DNA mass (1 kb bins)") plt.title ("Length-weighted histogram (LOWESS-smoothed)") plt.savefig( plot_name ) plt.close() except ImportError, e: martian.log_info( "Error importing libraries for plotting" ) martian.log_info( str(e) ) except KeyError, e: martian.log_info( "Invalid key in json while plotting" ) martian.log_info( str(e) ) except IOError, e: martian.log_info( "Could not find the molecule json for plotting" ) martian.log_info( str(e) ) except Exception as e: martian.log_info( "Unexpected error while plotting molecule length") martian.log_info( str(e) ) ## take a set of (distinct) numbers and format them into a list of strings ## where we have an integer followed by a suffix ## picks out the representation that has the shortest length
def try_plot_kmer_spectrum(args): try: import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import json ## final plot name plot_name = os.path.join( args.parent_dir, "stats", "kmer_spectrum.pdf" ) kmer_fn = os.path.join( args.parent_dir, "stats", "histogram_kmer_count.json" ) data = json.loads(open( kmer_fn, "r" ).read()) ## max k-mer multiplicity MAX = 100 if len( data["vals"] ) == 0: martian.log_info ("No kmer data to plot.") return elif len( data["vals"] ) < MAX: martian.log_info ("Warning: no kmers with multiplicity >= %d"%MAX ) MAX = len( data["vals"] ) fig, ax = plt.subplots() #plt.setp(ax.get_yticklabels(), visible=False) ## set mode to 1.0 xvals = range(MAX) yvals = data["vals"][:MAX] ax.plot (xvals, yvals, lw = 2.0, color="blue" ) ## plot tail tail_height = float(sum(data["vals"][MAX:])) _, ymax = plt.ylim() plt.axvspan (xmin=MAX-1, xmax=MAX, ymin=0, ymax=tail_height/ymax, ls=None, color="blue") ## set up axis, grid ax.grid(True) plt.locator_params( 'x', nbins=10 ) plt.locator_params( 'y', nbins=10 ) plt.xlim(0, MAX) yt = ax.get_yticks() ylabels, yexp = nice_labels( yt ) plt.yticks ( yt, ylabels, rotation=45 ) plt.xlabel ( "filtered kmer multiplicity" ) plt.ylabel ( "counts" ) plt.savefig (plot_name) plt.close() except ImportError, e: martian.log_info( "Error importing libraries for plotting" ) martian.log_info( str(e) ) except KeyError, e: martian.log_info( "Invalid key in json while plotting" ) martian.log_info( str(e) ) except IOError, e: martian.log_info( "Could not find the molecule json for plotting" ) martian.log_info( str(e) ) except Exception as e: martian.log_info( "Unexpected error while plotting molecule length") martian.log_info( str(e) )
def plot_hexbin(sol, var1, var2, save=False, save_as_png=True, fig_dpi=144): if save_as_png: save_as = 'png' else: save_as = 'pdf' MDL = sol.MDL filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0] model = sol.get_model_type() if var1 == "R0": stoc1 = "R0" else: stoc1 = ''.join([i for i in var1 if not i.isdigit()]) stoc_num1 = [int(i) for i in var1 if i.isdigit()] try: x = MDL.trace(stoc1)[:,stoc_num1[0]-1] except: x = MDL.trace(stoc1)[:] if var2 == "R0": stoc2 = "R0" else: stoc2 = ''.join([i for i in var2 if not i.isdigit()]) stoc_num2 = [int(i) for i in var2 if i.isdigit()] try: y = MDL.trace(stoc2)[:,stoc_num2[0]-1] except: y = MDL.trace(stoc2)[:] xmin, xmax = min(x), max(x) ymin, ymax = min(y), max(y) fig, ax = plt.subplots(figsize=(4,4)) plt.grid(None) ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) # plt.scatter(x, y) plt.hexbin(x, y, gridsize=20, cmap=plt.cm.Blues) plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.xticks(rotation=90) plt.locator_params(axis = 'y', nbins = 5) plt.locator_params(axis = 'x', nbins = 5) cb = plt.colorbar() cb.set_label('Number of observations') plt.yticks(fontsize=14) plt.xticks(fontsize=14) plt.ylabel("%s" %var2, fontsize=14) plt.xlabel("%s" %var1, fontsize=14) if save: save_where = '/Figures/Hexbins/%s/' %filename working_path = getcwd().replace("\\", "/")+"/" save_path = working_path+save_where print("\nSaving hexbin figure in:\n", save_path) if not path.exists(save_path): makedirs(save_path) fig.savefig(save_path+'Bivar-%s-%s_%s_%s.%s'%(model,filename,var1,var2,save_as), dpi=fig_dpi, bbox_inches='tight') plt.close(fig) return fig
def plot_errors(sol, ax, noise): MDL = sol["pymc_model"] # model = get_model_type(sol) filename = sol["path"].replace("\\", "/").split("/")[-1].split(".")[0] keys = sorted([x.__name__ for x in MDL.deterministics]) + sorted([x.__name__ for x in MDL.stochastics]) sampler = MDL.get_state()["sampler"] try: keys.remove("zmod") keys.remove("m_") except: pass for (i, k) in enumerate(keys): vect = old_div((MDL.trace(k)[:].size),(len(MDL.trace(k)[:]))) if vect > 1: keys[i] = [k+"%d"%n for n in range(0,vect)] keys = list(flatten(keys)) labels = [r"$log_{10}\bar{\tau}$", "$\Sigma m$", "$R_0$", "$a_0$", "$a_1$", "$a_2$", "$a_3$", "$a_4$"] ncols = 2 nrows = int(ceil(len(keys)*1.0 / ncols)) for c, (a, k) in enumerate(zip(ax.flat, keys)): if k == "R0": stoc = "R0" else: stoc = ''.join([i for i in k if not i.isdigit()]) stoc_num = [int(i) for i in k if i.isdigit()] try: mean = np.mean(MDL.trace(stoc)[:][:,stoc_num[0]-1]) SD = np.std(MDL.trace(stoc)[:][:,stoc_num[0]-1]) except: mean = np.mean(MDL.trace(stoc)[:]) SD = np.std(MDL.trace(stoc)[:]) # x = np.arange(sampler["_burn"]+1, sampler["_iter"]+1, sampler["_thin"]) plt.axes(a) a.grid(False) plt.ticklabel_format(style='sci', axis='y', scilimits=(0,2)) plt.locator_params(axis = 'y', nbins = 6) plt.yticks(fontsize=14) plt.xticks(list(range(0,12)),["","1","2","3","4","5","6","7","8","9","10"], fontsize=14) plt.ylabel(labels[c], fontsize=14) ty = a.yaxis.get_offset_text() ty.set_size(12) tx = a.xaxis.get_offset_text() tx.set_size(12) plt.xlim([0.5, 10.5]) plt.errorbar(noise+1, mean, SD, None, 'ob', label=filename, linewidth=1.0) # plt.xticks()
def plot_pr(precision, recall, title='', r=[0.67, 1.01], legend_labels=None, save_path=None, nbins=5, colorVals=None, xlabel='Recall', ylabel='Precision', l_pos="lower left", legend=True, r_x=[0.67, 1.01], ls=22): from matplotlib import pyplot as plt fig, ax = plt.subplots() fig.patch.set_facecolor('white') ax.tick_params(axis='x', which='major', labelsize=ls, direction='out', length=4, width=3, right="off", top="off", pad=10) ax.tick_params(axis='y', which='major', labelsize=ls, direction='out', length=4, width=3, right="off", top="off", pad=10) ax.tick_params(axis='x', which='minor', labelsize=ls, direction='out', length=4, width=3, right="off", top="off", pad=10) ax.tick_params(axis='y', which='minor', labelsize=ls, direction='out', length=4, width=3, right="off", top="off", pad=10) ax.spines['left'].set_linewidth(3) ax.spines['bottom'].set_linewidth(3) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) plt.locator_params(axis='x', nbins=nbins) plt.locator_params(axis='y', nbins=nbins) plt.title(title) if not -1 in r: plt.xlim(r_x) plt.ylim(r) plt.xlabel(xlabel, fontsize=ls) plt.ylabel(ylabel, fontsize=ls) plt.tight_layout() if isinstance(recall, list): if colorVals is None: colorVals = [[0.171, 0.485, 0.731, 1.], [0.175, 0.585, 0.301, 1.], [0.841, 0.138, 0.133, 1.]] if len(colorVals) < len(recall): colorVals += ["0.35"] * (len(recall) - len(colorVals)) if len(colorVals) > len(recall): colorVals = ["0.35", "0.7"] if legend_labels is None: legend_labels = ["Mitochondria", "Vesicle Clouds", "Synaptic Junctions"] handles = [] for ii in range(len(recall)): handles.append(patches.Patch(color=colorVals[ii], label=legend_labels[ii])) plt.plot(recall[ii], precision[ii], lw=4, c=colorVals[ii]) if legend: plt.legend(handles=handles, loc=l_pos, frameon=False, prop={'size': ls}) else: plt.plot(recall, precision, lw=4, c="0.35") if save_path is None: plt.show(block=False) else: plt.savefig(save_path, dpi=300)
def S_eta(L_vec, c2_val): c2 = c2_val traj = np.zeros([x_ang.shape[0]*2+1,L_vec.shape[0]]) n=0 for L in L_vec: slope = (m*(m+1)+c2-L)/(m+1)/2. z0 = [1+step*slope,slope] z = odeint(f,z0,x_ang,args=(c2,L,m)) temp=1-pow(x_ang,2.0) temp=pow(temp,m/2.) zz=temp*z[:,0] first_zz = np.array([1]) zz=np.append(first_zz, zz) sloper = -(m*(m+1)+c2-L)/(m+1)/2. z0r = [1-step*sloper,sloper] zr = odeint(f,z0r,x_angr,args=(c2,L,m)) zzr=temp*zr[:,0] zzr=np.append(first_zz, zzr) traj[:,n] = np.append(zz,zzr[::-1][1:]) n += 1 x_tot = np.arange(-1,1.+step,step) figure = plt.figure(figsize=(12, 11)) plt.plot(x_tot,traj, linewidth=2.0, label = '') plt.ylabel('S($\\eta$)')#, fontdict=font) plt.xlabel('$\\eta$')#, fontdict=font) #plt.xlim(-1.0,1.0) #plt.ylim(0.3,1.0) plt.locator_params(axis='x', nbins=10) plt.locator_params(axis='y', nbins=10) plt.tick_params(axis='x', pad=15) #plt.legend(loc=1) plt.show() plt.close()
def R_xi(E_vec,L0): traj = np.zeros([x_rad.shape[0]+1,E_vec.shape[0]]) n=0 for E in E_vec: c2 = D*D*E/4. L = newton(newton_ang_func,L0,args=(c2,m),tol=1e-8,maxiter=200) slope = -(-L+m*(m+1.)+2.*D+c2)/(2.*(m+1.)) z0 = [1+step*slope,slope] z = odeint(g,z0,x_rad,args=(c2,L,D,m)) temp=pow(x_rad,2.0)-1. temp=pow(temp,m/2.) zz=temp*z[:,0] first_zz = np.array([1]) zz=np.append(first_zz, zz) traj[:,n] = zz n += 1 xt = np.append(np.array([1]),x_rad) figure = plt.figure(figsize=(12, 11)) plt.plot(xt,traj, linewidth=2.0, label = '') plt.ylabel('R($\\xi$)')#, fontdict=font) plt.xlabel('$\\xi$')#, fontdict=font) #plt.xlim(1.0,10.0) #plt.ylim(-1.0,1.0) plt.locator_params(axis='x', nbins=10) plt.locator_params(axis='y', nbins=10) plt.tick_params(axis='x', pad=15) #plt.legend(loc=1) plt.show() plt.close()