Python matplotlib.pylab.legend() Examples
The following are 30
code examples of matplotlib.pylab.legend().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib.pylab
, or try the search function
.
Example #1
Source File: PlotK.py From refinery with MIT License | 6 votes |
def parse_args(): ''' Returns Namespace of parsed arguments retrieved from command line ''' parser = argparse.ArgumentParser() BNPYArgParser.addRequiredVizArgsToParser(parser) BNPYArgParser.addStandardVizArgsToParser(parser) parser.add_argument('--xvar', type=str, default='laps', help="name of x axis variable to plot. one of {iters,laps,times}") parser.add_argument('--traceEvery', type=str, default=None, help="Specifies how often to plot data points. For example, traceEvery=10 only plots data points associated with laps divisible by 10.") parser.add_argument('--legendnames', type=str, default=None, help="optional names to show on legend in place of jobnames") args = parser.parse_args() args.algNames = args.algNames.split(',') args.jobnames = args.jobnames.split(',') if args.legendnames is not None: args.legendnames = args.legendnames.split(',') return args
Example #2
Source File: interfacemethod.py From pyiron with BSD 3-Clause "New" or "Revised" License | 6 votes |
def check_for_holes(temperature_next, strain_value_lst, nve_run_time_steps, project_parameter, debug_plot=True): max_lst, mean_lst = get_voronoi_volume( temperature_next=temperature_next, strain_lst=strain_value_lst, nve_run_time_steps=nve_run_time_steps, project_parameter=project_parameter ) if debug_plot: plt.plot(strain_value_lst, mean_lst, label='mean') plt.plot(strain_value_lst, max_lst, label='max') plt.axhline(np.mean(mean_lst) * 2, color='black', linestyle='--') plt.legend() plt.xlabel('Strain') plt.ylabel('Voronoi Volume') plt.show() return np.array(max_lst) < np.mean(mean_lst) * 2
Example #3
Source File: interfacemethod.py From pyiron with BSD 3-Clause "New" or "Revised" License | 6 votes |
def plot_equilibration(temperature_next, strain_lst, nve_run_time_steps, project_parameter, debug_plot=True): if debug_plot: for strain in strain_lst: job_name = get_nve_job_name( temperature_next=temperature_next, strain=strain, steps_lst=project_parameter['nve_run_time_steps_lst'], nve_run_time_steps=nve_run_time_steps ) ham_nve = project_parameter['project'].load(job_name) plt.plot(ham_nve['output/generic/temperature'], label='strain: ' + str(strain)) plt.axhline(np.mean(ham_nve['output/generic/temperature'][-20:]), linestyle='--', color='red') plt.axvline(range(len(ham_nve['output/generic/temperature']))[-20], linestyle='--', color='black') plt.legend() plt.xlabel('timestep') plt.ylabel('Temperature K') plt.legend() plt.show()
Example #4
Source File: efficient_frontier.py From FinQuant with MIT License | 6 votes |
def plot_efrontier(self): """Plots the Efficient Frontier.""" if self.efrontier is None: # compute efficient frontier first self.efficient_frontier() plt.plot( self.efrontier[:, 0], self.efrontier[:, 1], linestyle="-.", color="black", lw=2, label="Efficient Frontier", ) plt.title("Efficient Frontier") plt.xlabel("Volatility") plt.ylabel("Expected Return") plt.legend()
Example #5
Source File: benchmark.py From osqp_benchmarks with Apache License 2.0 | 6 votes |
def plot_performance_profiles(problems, solvers): """ Plot performance profiles in matplotlib for specified problems and solvers """ # Remove OSQP polish solver solvers = solvers.copy() for s in solvers: if "polish" in s: solvers.remove(s) df = pd.read_csv('./results/%s/performance_profiles.csv' % problems) plt.figure(0) for solver in solvers: plt.plot(df["tau"], df[solver], label=solver) plt.xlim(1., 10000.) plt.ylim(0., 1.) plt.xlabel(r'Performance ratio $\tau$') plt.ylabel('Ratio of problems solved') plt.xscale('log') plt.legend() plt.grid() plt.show(block=False) results_file = './results/%s/%s.png' % (problems, problems) print("Saving plots to %s" % results_file) plt.savefig(results_file)
Example #6
Source File: portfolio.py From FinQuant with MIT License | 6 votes |
def plot_stocks(self, freq=252): """Plots the Expected annual Returns over annual Volatility of the stocks of the portfolio. :Input: :freq: ``int`` (default: ``252``), number of trading days, default value corresponds to trading days in a year. """ # annual mean returns of all stocks stock_returns = self.comp_mean_returns(freq=freq) stock_volatility = self.comp_stock_volatility(freq=freq) # adding stocks of the portfolio to the plot # plot stocks individually: plt.scatter(stock_volatility, stock_returns, marker="o", s=100, label="Stocks") # adding text to stocks in plot: for i, txt in enumerate(stock_returns.index): plt.annotate( txt, (stock_volatility[i], stock_returns[i]), xytext=(10, 0), textcoords="offset points", label=i, ) plt.legend()
Example #7
Source File: PlotELBO.py From refinery with MIT License | 6 votes |
def parse_args(): ''' Returns Namespace of parsed arguments retrieved from command line ''' parser = argparse.ArgumentParser() BNPYArgParser.addRequiredVizArgsToParser(parser) BNPYArgParser.addStandardVizArgsToParser(parser) parser.add_argument('--xvar', type=str, default='laps', help="name of x axis variable to plot. one of {iters,laps,times}") parser.add_argument('--traceEvery', type=str, default=None, help="Specifies how often to plot data points. For example, traceEvery=10 only plots data points associated with laps divisible by 10.") parser.add_argument('--legendnames', type=str, default=None, help="optional names to show on legend in place of jobnames") args = parser.parse_args() args.algNames = args.algNames.split(',') args.jobnames = args.jobnames.split(',') if args.legendnames is not None: args.legendnames = args.legendnames.split(',') #assert len(args.legendnames) == len(args.jobnames) * len(args.algNames) return args
Example #8
Source File: utils.py From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License | 6 votes |
def plot_roc(auc_score, name, tpr, fpr, label=None): pylab.clf() pylab.figure(num=None, figsize=(5, 4)) pylab.grid(True) pylab.plot([0, 1], [0, 1], 'k--') pylab.plot(fpr, tpr) pylab.fill_between(fpr, tpr, alpha=0.5) pylab.xlim([0.0, 1.0]) pylab.ylim([0.0, 1.0]) pylab.xlabel('False Positive Rate') pylab.ylabel('True Positive Rate') pylab.title('ROC curve (AUC = %0.2f) / %s' % (auc_score, label), verticalalignment="bottom") pylab.legend(loc="lower right") filename = name.replace(" ", "_") pylab.savefig( os.path.join(CHART_DIR, "roc_" + filename + ".png"), bbox_inches="tight")
Example #9
Source File: kNN.py From statistical-learning-methods-note with Apache License 2.0 | 6 votes |
def plotKChart(self, misClassDict, saveFigPath): kList = [] misRateList = [] for k, misClassNum in misClassDict.iteritems(): kList.append(k) misRateList.append(1.0 - 1.0/k*misClassNum) fig = plt.figure(saveFigPath) plt.plot(kList, misRateList, 'r--') plt.title(saveFigPath) plt.xlabel('k Num.') plt.ylabel('Misclassified Rate') plt.legend(saveFigPath) plt.grid(True) plt.savefig(saveFigPath) plt.show() ################################### PART3 TEST ######################################## # 例子
Example #10
Source File: mediator_utils.py From whynot with MIT License | 6 votes |
def error_bar_plot(experiment_data, results, title="", ylabel=""): true_effect = experiment_data.true_effects.mean() estimators = list(results.keys()) x = list(estimators) y = [results[estimator].ate for estimator in estimators] cis = [ np.array(results[estimator].ci) - results[estimator].ate if results[estimator].ci is not None else [0, 0] for estimator in estimators ] err = [[abs(ci[0]) for ci in cis], [abs(ci[1]) for ci in cis]] plt.figure(figsize=(12, 5)) (_, caps, _) = plt.errorbar(x, y, yerr=err, fmt="o", markersize=8, capsize=5) for cap in caps: cap.set_markeredgewidth(2) plt.plot(x, [true_effect] * len(x), label="True Effect") plt.legend(fontsize=12, loc="lower right") plt.ylabel(ylabel) plt.title(title)
Example #11
Source File: texttiling.py From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International | 6 votes |
def demo(text=None): from nltk.corpus import brown from matplotlib import pylab tt = TextTilingTokenizer(demo_mode=True) if text is None: text = brown.raw()[:10000] s, ss, d, b = tt.tokenize(text) pylab.xlabel("Sentence Gap index") pylab.ylabel("Gap Scores") pylab.plot(range(len(s)), s, label="Gap Scores") pylab.plot(range(len(ss)), ss, label="Smoothed Gap scores") pylab.plot(range(len(d)), d, label="Depth scores") pylab.stem(range(len(b)), b) pylab.legend() pylab.show()
Example #12
Source File: equality and segregation.py From python-urbanPlanning with MIT License | 6 votes |
def showVector(df,columnName): # print(df.columns) #可以显示vecter(polygon,point)数据。show vector multi=2 fig, ax = plt.subplots(figsize=(14*multi, 8*multi)) df.plot(column=columnName, categorical=True, legend=True, scheme='QUANTILES', cmap='RdBu', #'OrRd' ax=ax) # df.plot() # adjust legend location leg = ax.get_legend() # leg.set_bbox_to_anchor((1.15,0.5)) ax.set_axis_off() plt.show() # As provided in the answer by Divakar https://stackoverflow.com/questions/41190852/most-efficient-way-to-forward-fill-nan-values-in-numpy-array
Example #13
Source File: util.py From Azimuth with BSD 3-Clause "New" or "Revised" License | 6 votes |
def addqqplotinfo(qnull,M,xl='-log10(P) observed',yl='-log10(P) expected',xlim=None,ylim=None,alphalevel=0.05,legendlist=None,fixaxes=False): distr='log10' pl.plot([0,qnull.max()], [0,qnull.max()],'k') pl.ylabel(xl) pl.xlabel(yl) if xlim is not None: pl.xlim(xlim) if ylim is not None: pl.ylim(ylim) if alphalevel is not None: if distr == 'log10': betaUp, betaDown, theoreticalPvals = _qqplot_bar(M=M,alphalevel=alphalevel,distr=distr) lower = -sp.log10(theoreticalPvals-betaDown) upper = -sp.log10(theoreticalPvals+betaUp) pl.fill_between(-sp.log10(theoreticalPvals),lower,upper,color="grey",alpha=0.5) #pl.plot(-sp.log10(theoreticalPvals),lower,'g-.') #pl.plot(-sp.log10(theoreticalPvals),upper,'g-.') if legendlist is not None: leg = pl.legend(legendlist, loc=4, numpoints=1) # set the markersize for the legend for lo in leg.legendHandles: lo.set_markersize(10) if fixaxes: fix_axes()
Example #14
Source File: gspv.py From CO2MPAS-TA with European Union Public License 1.1 | 6 votes |
def plot(self): import matplotlib.pylab as plt for k, v in self.limits.items(): kv = {} for (s, l), (x, y) in zip((('down', '--'), ('up', '-')), v): if x[0] < dfl.INF: kv['label'] = 'Gear %d:%s-shift' % (k, s) kv['linestyle'] = l # noinspection PyProtectedMember kv['color'] = plt.plot(x, y, **kv)[0]._color cy, cx = self.cloud[k][1] if cx[0] < dfl.INF: kv.pop('label') kv['linestyle'] = '' kv['marker'] = 'o' plt.plot(cx, cy, **kv) plt.legend(loc='best') plt.xlabel('Velocity [km/h]') plt.ylabel('Power [kW]')
Example #15
Source File: eval.py From DeepLearningImplementations with MIT License | 5 votes |
def plot_results(list_log, to_plot="losses"): list_color = [u'#E24A33', u'#348ABD', u'#FBC15E', u'#777777', u'#988ED5', u'#8EBA42', u'#FFB5B8'] plt.figure() for idx, log in enumerate(list_log): with open(log, "r") as f: d = json.load(f) experiment_name = d["experiment_name"] color = list_color[idx] plt.plot(d["train_%s" % to_plot], color=color, linewidth=3, label="Train %s" % experiment_name) plt.plot(d["val_%s" % to_plot], color=color, linestyle="--", linewidth=3,) plt.ylabel(to_plot, fontsize=20) if to_plot == "losses": plt.yscale("log") if to_plot == "accs": plt.ylim([0, 1.1]) plt.xlabel("Number of epochs", fontsize=20) plt.title("%s experiment" % dataset, fontsize=22) plt.legend(loc="best") plt.tight_layout() plt.savefig("./figures/%s_results_%s.png" % (dataset, to_plot)) plt.show()
Example #16
Source File: optimization.py From angler with MIT License | 5 votes |
def plot_transmissions(self, transmissions, legend=None): """ Plots the results of the power scan """ for p in transmissions: plt.plot(p) plt.xscale('log') plt.xlabel('input source amplitude') plt.ylabel('power transmission') if legend is not None: plt.legend(legend) plt.show()
Example #17
Source File: Time Series Analysis.py From python-urbanPlanning with MIT License | 5 votes |
def plotModelResults(model, X_train, X_test,y_train,y_test, plot_intervals=False, plot_anomalies=False, scale=1.96): """ Plots modelled vs fact values, prediction intervals and anomalies """ prediction = model.predict(X_test) plt.figure(figsize=(15, 7)) plt.plot(prediction, "g", label="prediction", linewidth=2.0) plt.plot(y_test.values, label="actual", linewidth=2.0) if plot_intervals: cv = cross_val_score(model, X_train, y_train, cv=tscv, scoring="neg_mean_squared_error") #mae = cv.mean() * (-1) deviation = np.sqrt(cv.std()) lower = prediction - (scale * deviation) upper = prediction + (scale * deviation) plt.plot(lower, "r--", label="upper bond / lower bond", alpha=0.5) plt.plot(upper, "r--", alpha=0.5) if plot_anomalies: anomalies = np.array([np.NaN]*len(y_test)) anomalies[y_test<lower] = y_test[y_test<lower] anomalies[y_test>upper] = y_test[y_test>upper] plt.plot(anomalies, "o", markersize=10, label = "Anomalies") error = mean_absolute_percentage_error(prediction, y_test) plt.title("Mean absolute percentage error {0:.2f}%".format(error)) plt.legend(loc="best") plt.tight_layout() plt.grid(True);
Example #18
Source File: param_scheduler.py From ignite with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot_values(cls, num_events, **scheduler_kwargs): """Method to plot simulated scheduled values during `num_events` events. This class requires `matplotlib package <https://matplotlib.org/>`_ to be installed: .. code-block:: bash pip install matplotlib Args: num_events (int): number of events during the simulation. **scheduler_kwargs : parameter scheduler configuration kwargs. Returns: matplotlib.lines.Line2D Examples: .. code-block:: python import matplotlib.pylab as plt plt.figure(figsize=(10, 7)) LinearCyclicalScheduler.plot_values(num_events=50, param_name='lr', start_value=1e-1, end_value=1e-3, cycle_size=10)) """ try: import matplotlib.pylab as plt except ImportError: raise RuntimeError( "This method requires matplotlib to be installed. " "Please install it with command: \n pip install matplotlib" ) values = cls.simulate_values(num_events=num_events, **scheduler_kwargs) label = scheduler_kwargs.get("param_name", "learning rate") ax = plt.plot([e for e, _ in values], [v for _, v in values], label=label) plt.legend() plt.grid(which="both") return ax
Example #19
Source File: cmv.py From CO2MPAS-TA with European Union Public License 1.1 | 5 votes |
def plot(self): import matplotlib.pylab as plt for k, v in self.items(): kv = {} for (s, l), x in zip((('down', '--'), ('up', '-')), v): if x < dfl.INF: kv['label'] = 'Gear %d:%s-shift' % (k, s) kv['linestyle'] = l # noinspection PyProtectedMember kv['color'] = plt.plot([x] * 2, [0, 1], **kv)[0]._color plt.legend(loc='best') plt.xlabel('Velocity [km/h]')
Example #20
Source File: param_scheduler.py From ignite with BSD 3-Clause "New" or "Revised" License | 5 votes |
def simulate_values(cls, num_events, **scheduler_kwargs): """Method to simulate scheduled values during `num_events` events. Args: num_events (int): number of events during the simulation. **scheduler_kwargs : parameter scheduler configuration kwargs. Returns: list of pairs: [event_index, value] Examples: .. code-block:: python lr_values = np.array(LinearCyclicalScheduler.simulate_values(num_events=50, param_name='lr', start_value=1e-1, end_value=1e-3, cycle_size=10)) plt.plot(lr_values[:, 0], lr_values[:, 1], label="learning rate") plt.xlabel("events") plt.ylabel("values") plt.legend() """ keys_to_remove = ["optimizer", "save_history"] for key in keys_to_remove: if key in scheduler_kwargs: del scheduler_kwargs[key] values = [] scheduler = cls(optimizer=_get_fake_optimizer(), save_history=False, **scheduler_kwargs) for i in range(num_events): scheduler(engine=None) values.append([i, scheduler.optimizer_param_groups[0][scheduler.param_name]]) return values
Example #21
Source File: classif_and_ktst.py From jstsp2015 with MIT License | 5 votes |
def plot_null_distribution(stats, stats_null, p_value, data_name='', stats_name='$MMD^2_u$', save_figure=True): """Plot the observed value for the test statistic, its null distribution and p-value. """ fig = plt.figure() ax = fig.add_subplot(111) prob, bins, patches = plt.hist(stats_null, bins=50, normed=True) ax.plot(stats, prob.max()/30, 'w*', markersize=15, markeredgecolor='k', markeredgewidth=2, label="%s = %s" % (stats_name, stats)) ax.annotate('p-value: %s' % (p_value), xy=(float(stats), prob.max()/9.), xycoords='data', xytext=(-105, 30), textcoords='offset points', bbox=dict(boxstyle="round", fc="1."), arrowprops={"arrowstyle": "->", "connectionstyle": "angle,angleA=0,angleB=90,rad=10"}, ) plt.xlabel(stats_name) plt.ylabel('p(%s)' % stats_name) plt.legend(numpoints=1) plt.title('Data: %s' % data_name) if save_figure: save_dir = 'figures' if not os.path.exists(save_dir): os.makedirs(save_dir) stn = 'ktst' if stats_name == '$MMD^2_u$' else 'clf' fig_name = os.path.join(save_dir, '%s_%s.pdf' % (data_name, stn)) fig.savefig(fig_name)
Example #22
Source File: generate_plots.py From hand_eye_calibration with BSD 3-Clause "New" or "Revised" License | 5 votes |
def generate_time_plot(methods, datasets, runtimes_per_method, colors): num_methods = len(methods) num_datasets = len(datasets) x_ticks = np.linspace(0., 1., num_methods) width = 0.6 / num_methods / num_datasets spacing = 0.4 / num_methods / num_datasets fig, ax1 = plt.subplots() ax1.set_ylabel('Time [s]', color='b') ax1.tick_params('y', colors='b') ax1.set_yscale('log') fig.suptitle("Hand-Eye Calibration Method Timings", fontsize='24') handles = [] for i, dataset in enumerate(datasets): runtimes = [runtimes_per_method[dataset][method] for method in methods] bp = ax1.boxplot( runtimes, 0, '', positions=(x_ticks + (i - num_datasets / 2. + 0.5) * spacing * 2), widths=width) plt.setp(bp['boxes'], color=colors[i], linewidth=line_width) plt.setp(bp['whiskers'], color=colors[i], linewidth=line_width) plt.setp(bp['fliers'], color=colors[i], marker='+', linewidth=line_width) plt.setp(bp['medians'], color=colors[i], marker='+', linewidth=line_width) plt.setp(bp['caps'], color=colors[i], linewidth=line_width) handles.append(mpatches.Patch(color=colors[i], label=dataset)) plt.legend(handles=handles, loc=2) plt.xticks(x_ticks, methods) plt.xlim(x_ticks[0] - 2.5 * spacing * num_datasets, x_ticks[-1] + 2.5 * spacing * num_datasets) plt.show()
Example #23
Source File: kde_subclass.py From altanalyze with Apache License 2.0 | 5 votes |
def plotkde(covfact): gkde.reset_covfact(covfact) kdepdf = gkde.evaluate(ind) plt.figure() # plot histgram of sample plt.hist(xn, bins=20, normed=1) # plot estimated density plt.plot(ind, kdepdf, label='kde', color="g") # plot data generating density plt.plot(ind, alpha * stats.norm.pdf(ind, loc=mlow) + (1-alpha) * stats.norm.pdf(ind, loc=mhigh), color="r", label='DGP: normal mix') plt.title('Kernel Density Estimation - ' + str(gkde.covfact)) plt.legend()
Example #24
Source File: plotlib.py From incubator-sdap-nexus with Apache License 2.0 | 5 votes |
def plotColumnsSimple(specs, outFile=None, rmsDiffFrom=None, floatFormat=None, colors='bgrcmyk', markers='+x^svD<4>3', **options): """Plot olumns of numbers from one or more data files. Each plot spec. contains a filename and a list of labelled columns: e.g., ('file1', 'xlabel:1,ylabel1:4,ylabel2:2,ylabel3:13) Bug: For the moment, only have 7 different colors and 10 different markers. """ ensureItems(options, {'legend': True}) ydataMaster = None for spec in specs: file, columns = spec # each spec is a (file, columnList) pair columns = columns.split(',') # each columnList is a comma-separated list of named columns # Each named column is a colon-separated pair or triple 'label:integer[:style]' # Column indices are one-based. # Styles are concatenated one-char flags like 'go' for green circles or # 'kx-' for black X's with a line. fields = N.array([map(floatOrMiss, line.split()) for line in open(file, 'r')]) xcol = columns.pop(0) # first column in list is the x axis xlabel, xcol, xstyle = splitColumnSpec(xcol) xdata = fields[:,xcol-1] markIndex = 0 for ycol in columns: ylabel, ycol, ystyle = splitColumnSpec(ycol) if ystyle is None: ystyle = colors[markIndex] + markers[markIndex] ydata = fields[:,ycol-1] # all other columns are multiple y plots if rmsDiffFrom: if ydataMaster is None: ydataMaster = ydata # kludge: must be first ycol in first file ylabelMaster = ylabel else: s = diffStats(ylabelMaster, ydataMaster, ylabel, ydata) print >>sys.stderr, s.format(floatFormat) n, mean, sigma, min, max, rms = s.calc() ylabel = ylabel + ' ' + floatFormat % rms M.plot(xdata, ydata, ystyle, label=ylabel) markIndex += 1 evalKeywordCmds(options) if outFile: M.savefig(outFile)
Example #25
Source File: kdecovclass.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def plotkde(covfact): gkde.reset_covfact(covfact) kdepdf = gkde.evaluate(ind) plt.figure() # plot histgram of sample plt.hist(xn, bins=20, normed=1) # plot estimated density plt.plot(ind, kdepdf, label='kde', color="g") # plot data generating density plt.plot(ind, alpha * stats.norm.pdf(ind, loc=mlow) + (1-alpha) * stats.norm.pdf(ind, loc=mhigh), color="r", label='DGP: normal mix') plt.title('Kernel Density Estimation - ' + str(gkde.covfact)) plt.legend()
Example #26
Source File: PlotELBO.py From refinery with MIT License | 5 votes |
def main(): args = parse_args() for (jobpath, jobname, color) in job_to_plot_generator(args): plot_all_tasks_for_job(jobpath, args, jobname, color) pylab.legend(loc='best') if args.savefilename is not None: pylab.show(block=False) pylab.savefig(args.savefilename) else: pylab.show(block=True)
Example #27
Source File: PlotK.py From refinery with MIT License | 5 votes |
def main(): args = parse_args() for (jobpath, jobname, color) in job_to_plot_generator(args): plot_all_tasks_for_job(jobpath, args, jobname, color) pylab.legend(loc='best') if args.savefilename is not None: pylab.show(block=False) pylab.savefig(args.savefilename) else: pylab.show(block=True)
Example #28
Source File: octopus_plot.py From PyChemia with MIT License | 5 votes |
def plot_energy(path): import matplotlib.pylab as plt if not os.path.isdir(path): print('ERROR: No such dir ', path) return None if not os.path.isfile(path + '/td.general/energy'): print('ERROR: No energy file ', path + '/td.general/energy') return None data = np.loadtxt(path + '/td.general/energy') if len(data) == 0: print('No data on ', path + '/td.general/energy') return None plt.clf() fig = plt.figure(num=None, figsize=(16, 12), dpi=80, facecolor='w', edgecolor='k') labels = ['Total', 'Kinetic (ions)', 'Ion-Ion', 'Electronic', 'Eigenvalues', 'Hartree', 'Int[n v_xc]', 'Exchange', 'Correlation'] # For some columns the energy is only computed each # certain steps, this will identify the number of # steps to get a new non-zero value nstep = 0 for i in range(len(data)): if i == 0 and data[i, -3] != 0.0: nstep += 1 if data[i, -3] == 0.0: nstep += 1 if i != 0 and data[i, -3] != 0.0: break print('Complete data each', nstep, ' steps') for i in range(9): plt.subplot(330 + i + 1) plt.plot(data[::nstep, 1], data[::nstep, i + 2], label=labels[i]) plt.xlabel('Time [hbar/H]') plt.legend(loc=4) return fig
Example #29
Source File: util.py From Azimuth with BSD 3-Clause "New" or "Revised" License | 5 votes |
def qqplotp(pv,fileout = None, alphalevel = 0.05,legend=None,xlim=None,ylim=None,ycoord=10,plotsize="652x526",title=None,dohist=True, numbins=50, figsize=[5,5], markersize=2): ''' Read in p-values from filein and make a qqplot adn histogram. If fileout is provided, saves the qqplot only at present. Searches through p until one is found. ''' import pylab as pl pl.ion() fs=8 h1=qqplot(pv, fileout, alphalevel,legend,xlim,ylim,addlambda=True, figsize=figsize, markersize=markersize) #lambda_gc=estimate_lambda(pv) #pl.legend(["gc="+ '%1.3f' % lambda_gc],loc=2) pl.title(title,fontsize=fs) wm=pl.get_current_fig_manager() #e.g. "652x526+100+10 xcoord=100 #wm.window.wm_geometry(plotsize + "+" + str(xcoord) + "+" + str(ycoord)) if dohist: h2=pvalhist(pv, numbins=numbins, figsize=figsize) pl.title(title,fontsize=fs) #wm=pl.get_current_fig_manager() width_height=plotsize.split("x") buffer=10 xcoord=int(xcoord + float(width_height[0])+buffer) #wm.window.wm_geometry(plotsize + "+" + str(xcoord) + "+" + str(ycoord)) else: h2=None return h1,h2
Example #30
Source File: PybacktestChef.py From OpenTrader with GNU Lesser General Public License v3.0 | 5 votes |
def vPlotEquity(rEquityDiff, mOhlc, sPeriod='W', subset=None, sTitle="Equity", close_label='C', ): if subset is None: subset = slice(None, None) else: assert isinstance(subset, slice) rEquitySum = rEquityDiff[subset].cumsum() rEquitySum.plot(color='red', label='strategy') ix = mOhlc.ix[rEquitySum.index[0]:rEquitySum.index[-1]].index price = getattr(mOhlc, close_label) (price[ix] - price[ix][0]).resample(sPeriod, how='first').dropna() \ .plot(color='black', alpha=0.5, label='underlying') import matplotlib.pylab as pylab pylab.legend(loc='best') pylab.title(sTitle) # pylint: disable=W0110,C0103,R0903,E1136,E1101 # C0103 invalid-name 39,54,66,179,180,180,182,214,216,217,273,284,285,286,287,288,300,301,321 # E1101 no-member 179,214,215,218,284,300 # E1136 unsubscriptable-object 181,182 # R0903 too-few-public-methods 28 # W0110 deprecated-lambda 61 # the end