本文整理汇总了Python中matplotlib.pylab.legend方法的典型用法代码示例。如果您正苦于以下问题:Python pylab.legend方法的具体用法?Python pylab.legend怎么用?Python pylab.legend使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.pylab
的用法示例。
在下文中一共展示了pylab.legend方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: vPlotEquityCurves
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
def vPlotEquityCurves(oBt, mOhlc, oChefModule,
sPeriod='W',
close_label='C',):
import matplotlib
import matplotlib.pylab as pylab
# FixMe:
matplotlib.rcParams['figure.figsize'] = (10, 5)
# FixMe: derive the period from the sTimeFrame
oChefModule.vPlotEquity(oBt.equity, mOhlc, sTitle="%s\nEquity" % repr(oBt),
sPeriod=sPeriod,
close_label=close_label,
)
pylab.show()
oBt.vPlotTrades()
pylab.legend(loc='lower left')
pylab.show()
## oBt.vPlotTrades(subset=slice(sYear+'-05-01', sYear+'-09-01'))
## pylab.legend(loc='lower left')
## pylab.show()
示例2: error_bar_plot
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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)
示例3: plot_roc
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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")
开发者ID:PacktPublishing,项目名称:Building-Machine-Learning-Systems-With-Python-Second-Edition,代码行数:19,代码来源:utils.py
示例4: plot_equilibration
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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()
示例5: check_for_holes
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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
示例6: plot_efrontier
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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()
示例7: plot_stocks
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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()
示例8: plotKChart
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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 ########################################
# 例子
示例9: addqqplotinfo
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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()
示例10: parse_args
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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
示例11: parse_args
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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
示例12: plot_performance_profiles
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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)
示例13: demo
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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()
示例14: showVector
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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
示例15: plot
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import legend [as 别名]
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]')