def set_nice_params():
fsize=18
params = {'axes.labelsize': fsize,
# 'font.family': 'serif',
'font.family': 'Times New Roman',
'figure.facecolor': 'white',
'text.fontsize': fsize,
'legend.fontsize': fsize,
'xtick.labelsize': fsize*0.8,
'ytick.labelsize': fsize*0.8,
'ytick.minor.pad': 8,
'ytick.major.pad': 8,
'xtick.minor.pad': 8,
'xtick.major.pad': 8,
'text.usetex': False,
'lines.markeredgewidth': 0}
pl.rcParams.update(params)
python类legend()的实例源码
def hrd_key(self, key_str):
"""
plot an HR diagram
Parameters
----------
key_str : string
A label string
"""
pyl.plot(self.data[:,self.cols['log_Teff']-1],\
self.data[:,self.cols['log_L']-1],label = key_str)
pyl.legend()
pyl.xlabel('log Teff')
pyl.ylabel('log L')
x1,x2=pl.xlim()
if x2 > x1:
self._xlimrev()
def plot_prof_2(self, mod, species, xlim1, xlim2):
"""
Plot one species for cycle between xlim1 and xlim2
Parameters
----------
mod : string or integer
Model to plot, same as cycle number.
species : list
Which species to plot.
xlim1, xlim2 : float
Mass coordinate range.
"""
mass=self.se.get(mod,'mass')
Xspecies=self.se.get(mod,'yps',species)
pyl.plot(mass,Xspecies,'-',label=str(mod)+', '+species)
pyl.xlim(xlim1,xlim2)
pyl.legend()
def plotRes(pre, real, test_x,l):
s = set(pre)
col = ['r','b','g','y','m']
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(0, len(s)):
index1 = pre == i
index2 = real == i
x1 = test_x[index1, :]
x2 = test_x[index2, :]
ax.scatter(x1[:,0],x1[:,1],color=col[i],marker='v',linewidths=0.5)
ax.scatter(x2[:,0],x2[:,1],color=col[i],marker='.',linewidths=12)
plt.title('learning rating='+str(l))
plt.legend(('c1:predict','c1:true',\
'c2:predict','c2:true',
'c3:predict','c3:true',
'c4:predict','c4:true',
'c5:predict','c5:true'), shadow = True, loc = (0.01, 0.4))
plt.show()
def plot_position(self, pos_true, pos_est):
N = pos_est.shape[1]
pos_true = pos_true[:, :N]
pos_est = pos_est[:, :N]
# Figure
plt.figure()
plt.suptitle("Position")
# Ground truth
plt.plot(pos_true[0, :], pos_true[1, :],
color="red", marker="o", label="Grouth truth")
# Estimated
plt.plot(pos_est[0, :], pos_est[1, :],
color="blue", marker="o", label="Estimated")
# Plot labels and legends
plt.xlabel("East (m)")
plt.ylabel("North (m)")
plt.axis("equal")
plt.legend(loc=0)
def plot(self, track, track_cam_states, estimates):
plt.figure()
# Feature
feature = T_global_camera * track.ground_truth
plt.plot(feature[0], feature[1],
marker="o", color="red", label="feature")
# Camera states
for cam_state in track_cam_states:
pos = T_global_camera * cam_state.p_G
plt.plot(pos[0], pos[1],
marker="o", color="blue", label="camera")
# Estimates
for i in range(len(estimates)):
cam_state = track_cam_states[i]
cam_pos = T_global_camera * cam_state.p_G
estimate = (T_global_camera * estimates[i]) + cam_pos
plt.plot(estimate[0], estimate[1],
marker="o", color="green")
plt.legend(loc=0)
plt.show()
def plot_1d(dataset, nbins, data):
with sns.axes_style('white'):
plt.rc('font', weight='bold')
plt.rc('grid', lw=2)
plt.rc('lines', lw=3)
plt.figure(1)
plt.hist(data, bins=np.arange(nbins+1), color='blue')
plt.ylabel('Count', weight='bold', fontsize=24)
xticks = list(plt.gca().get_xticks())
while (nbins-1) / float(xticks[-1]) < 1.1:
xticks = xticks[:-1]
while xticks[0] < 0:
xticks = xticks[1:]
xticks.append(nbins-1)
xticks = list(sorted(xticks))
plt.gca().set_xticks(xticks)
plt.xlim([int(np.ceil(-0.05*nbins)),int(np.ceil(nbins*1.05))])
plt.legend(loc='upper right')
plt.savefig('plots/marginals-{0}.pdf'.format(dataset.replace('_','-')), bbox_inches='tight')
plt.clf()
plt.close()
def plot_1d(dataset, nbins):
data = np.loadtxt('experiments/uci/data/splits/{0}_all.csv'.format(dataset), skiprows=1, delimiter=',')[:,-1]
with sns.axes_style('white'):
plt.rc('font', weight='bold')
plt.rc('grid', lw=2)
plt.rc('lines', lw=3)
plt.figure(1)
plt.hist(data, bins=np.arange(nbins+1), color='blue')
plt.ylabel('Count', weight='bold', fontsize=24)
xticks = list(plt.gca().get_xticks())
while (nbins-1) / float(xticks[-1]) < 1.1:
xticks = xticks[:-1]
while xticks[0] < 0:
xticks = xticks[1:]
xticks.append(nbins-1)
xticks = list(sorted(xticks))
plt.gca().set_xticks(xticks)
plt.xlim([int(np.ceil(-0.05*nbins)),int(np.ceil(nbins*1.05))])
plt.legend(loc='upper right')
plt.savefig('plots/marginals-{0}.pdf'.format(dataset.replace('_','-')), bbox_inches='tight')
plt.clf()
plt.close()
utils.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
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")
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 ########################################
# ??
def backtest(config_file, day_trade):
cfg = config.Config(config_file)
cfg.day_trade = day_trade
dfs = load_data(config_file)
trender = strategies[cfg.strategy](**cfg.strategy_parameters)
res = []
for df in dfs:
res.append(trender.backtest(data_frame=df))
final_panel = pd.Panel({os.path.basename(p['path']): df for p, df in
zip(cfg.data_path, res)})
profit_series = final_panel.sum(axis=0)['total_profit'].cumsum()
final_panel.to_excel(cfg.output_file)
if cfg.show:
profit_series.plot()
plt.xlabel('Time')
plt.ylabel('Profit')
plt.legend('Profit')
plt.show()
def fit_data():
data=np.loadtxt('data.dat')
print(data)
params = dict()
params["c"] = {"min" : -np.inf,"max" : np.inf}
result = qudi_fitting.make_lorentzian_fit(axis=data[:,0], data=data[:,3], add_parameters=params)
print(result.fit_report())
plt.plot(data[:,0],-data[:,3]+2,"b-o",label="data mean")
# plt.plot(data[:,0],data[:,1],label="data")
# plt.plot(data[:,0],data[:,2],label="data")
plt.plot(data[:,0],-result.best_fit+2,"r-",linewidth=2.,label="fit")
# plt.plot(data[:,0],result.init_fit,label="init")
plt.xlabel("time (ns)")
plt.ylabel("polarization transfer (arb. u.)")
plt.legend(loc=1)
# plt.savefig("pol20_24repetition_pol.pdf")
# plt.savefig("pol20_24repetition_pol.png")
plt.show()
savedata=[[data[ii,0],-data[ii,3]+2,-result.best_fit[ii]+2] for ii in range(len(data[:,0]))]
np.savetxt("pol_data_fit.csv",savedata)
# print(result.params)
print(result.params)
def plot_classes(y, cord, names, test_error, message=""):
plt.close("all")
cord = np.array(cord)
colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k')
un = np.unique(y)
fig, ax = plt.subplots()
for u, col in zip(un, colors):
ind = np.argwhere(y == u)
x = cord[ind, :]
x = x.reshape(x.shape[0], cord.shape[1])
ax.scatter(x[:, 0], x[:, 1], label="class:" + str(u),
color=col)
plt.legend(loc='upper right', fancybox=True, shadow=True, prop={'size': 8})
fig.suptitle(
"Output prediction. Test error:" + str(test_error*100) + "%. " +
message, fontsize=8)
return fig
def plot_penalty_vl(debug, tag, fold_exp):
plt.close("all")
vl = np.array(debug["penalty"])
fig = plt.figure(figsize=(15, 10.8), dpi=300)
names = debug["names"]
for i in range(vl.shape[1]):
if vl.shape[1] > 1:
plt.plot(vl[:, i], label="layer_"+str(names[i]))
else:
plt.plot(vl[:], label="layer_"+str(names[i]))
plt.xlabel("mini-batchs")
plt.ylabel("value of penlaty")
plt.title(
"Penalty value over layers:" + "_".join([str(k) for k in names]) +
". tag:" + tag)
plt.legend(loc='upper right', fancybox=True, shadow=True, prop={'size': 8})
plt.grid(True)
fig.savefig(fold_exp+"/penalty.png", bbox_inches='tight')
plt.close('all')
del fig
def plot_roc(y_test, y_pred, label=''):
"""Compute ROC curve and ROC area"""
fpr, tpr, _ = roc_curve(y_test, y_pred)
roc_auc = auc(fpr, tpr)
# Plot of a ROC curve for a specific class
plt.figure()
plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic' + label)
plt.legend(loc="lower right")
plt.show()
def plotSpeedupFigure(AllInfo, maxWorker=1, **kwargs):
pylab.figure(2)
xs = AllInfo['nWorker']
ts_mono = AllInfo['t_monolithic']
xgrid = np.linspace(0, maxWorker + 0.1, 100)
pylab.plot(xgrid, xgrid, 'y--', label='ideal parallel')
for method in getMethodNames(**kwargs):
speedupRatio = ts_mono / AllInfo['t_' + method]
pylab.plot(xs, speedupRatio, 'o-',
label=method,
color=ColorMap[method],
markeredgecolor=ColorMap[method])
pylab.xlim([-0.2, maxWorker + 0.5])
pylab.ylim([0, maxWorker + 0.5])
pylab.legend(loc='upper left')
pylab.xlabel('Number of Workers')
pylab.ylabel('Speedup over Monolithic')
def plotBoundVsAlph(alphaVals=np.linspace(.001, 3, 1000),
beta1=0.5):
exactVals = cD_exact(alphaVals, beta1)
boundVals = cD_bound(alphaVals, beta1)
assert np.all(exactVals >= boundVals)
pylab.plot(alphaVals, exactVals, 'k-', linewidth=LINEWIDTH)
pylab.plot(alphaVals, boundVals, 'r--', linewidth=LINEWIDTH)
pylab.xlabel("alpha", fontsize=FONTSIZE)
pylab.ylabel(" ", fontsize=FONTSIZE)
pylab.xlim([np.min(alphaVals) - 0.1, np.max(alphaVals) + 0.1])
pylab.ylim([np.min(exactVals) - 0.05, np.max(exactVals) + 0.05])
pylab.xticks(np.arange(np.max(alphaVals) + 1))
pylab.legend(['c_D exact',
'c_D surrogate'],
fontsize=LEGENDSIZE,
loc='lower right')
pylab.tick_params(axis='both', which='major', labelsize=TICKSIZE)
def plot_tree_data(data, indicies_x, indicies_y, model):
plt.subplot(3, 1, 1)
data, indicies_x, indicies_y, model = load_tree_data()
data_line, = plt.plot(data, color="blue", label="data")
data_indicies_line, = plt.plot(
indicies_x,
indicies_y,
"o",
color="green",
label="fitness predictors"
)
model_line, = plt.plot(model, color="red", label="model")
plt.title("Data and Model Output")
plt.legend()
return data_line, data_indicies_line, model_line
def plot_tree_data(data, indicies_x, indicies_y, model, plot_indicies=False):
plt.subplot(3, 1, 1)
plt.plot(data, "o", color="blue", label="data")
plt.plot(model, color="red", label="model")
plt.ylim([-10, 10])
if plot_indicies:
plt.plot(
indicies_x,
indicies_y,
"o",
color="green",
label="fitness predictors"
)
plt.title("Data and Model Output")
plt.legend()
def energy_profile(self,ixaxis):
"""
Plot radial profile of key energy generations eps_nuc,
eps_neu etc.
Parameters
----------
ixaxis : 'mass' or 'radius'
"""
mass = self.get('mass')
radius = self.get('radius') * ast.rsun_cm
eps_nuc = self.get('eps_nuc')
eps_neu = self.get('non_nuc_neu')
if ixaxis == 'mass':
xaxis = mass
xlab = 'Mass / M$_\odot$'
else:
xaxis = old_div(radius, 1.e8) # Mm
xlab = 'radius / Mm'
pl.plot(xaxis, np.log10(eps_nuc),
'k-',
label='$\epsilon_\mathrm{nuc}>0$')
pl.plot(xaxis, np.log10(-eps_nuc),
'k--',
label='$\epsilon_\mathrm{nuc}<0$')
pl.plot(xaxis, np.log10(eps_neu),
'r-',
label='$\epsilon_\\nu$')
pl.xlabel(xlab)
pl.ylabel('$\log(\epsilon_\mathrm{nuc},\epsilon_\\nu)$')
pl.legend(loc='best').draw_frame(False)
def hrd_new(self, input_label="", skip=0):
"""
plot an HR diagram with options to skip the first N lines and
add a label string
Parameters
----------
input_label : string, optional
Diagram label. The default is "".
skip : integer, optional
Skip the first n lines. The default is 0.
"""
xl_old=pyl.gca().get_xlim()
if input_label == "":
my_label="M="+str(self.header_attr['initial_mass'])+", Z="+str(self.header_attr['initial_z'])
else:
my_label="M="+str(self.header_attr['initial_mass'])+", Z="+str(self.header_attr['initial_z'])+"; "+str(input_label)
pyl.plot(self.data[skip:,self.cols['log_Teff']-1],self.data[skip:,self.cols['log_L']-1],label = my_label)
pyl.legend(loc=0)
xl_new=pyl.gca().get_xlim()
pyl.xlabel('log Teff')
pyl.ylabel('log L')
if any(array(xl_old)==0):
pyl.gca().set_xlim(max(xl_new),min(xl_new))
elif any(array(xl_new)==0):
pyl.gca().set_xlim(max(xl_old),min(xl_old))
else:
pyl.gca().set_xlim([max(xl_old+xl_new),min(xl_old+xl_new)])
def t_lumi(self,num_frame,xax):
"""
Luminosity evolution as a function of time or model.
Parameters
----------
num_frame : integer
Number of frame to plot this plot into.
xax : string
Either model or time to indicate what is to be used on the
x-axis
"""
pyl.figure(num_frame)
if xax == 'time':
xaxisarray = self.get('star_age')
elif xax == 'model':
xaxisarray = self.get('model_number')
else:
print('kippenhahn_error: invalid string for x-axis selction. needs to be "time" or "model"')
logLH = self.get('log_LH')
logLHe = self.get('log_LHe')
pyl.plot(xaxisarray,logLH,label='L_(H)')
pyl.plot(xaxisarray,logLHe,label='L(He)')
pyl.ylabel('log L')
pyl.legend(loc=2)
if xax == 'time':
pyl.xlabel('t / yrs')
elif xax == 'model':
pyl.xlabel('model number')
def test_abu_evolution(self):
from nugridpy import ppn, utils
import matplotlib
matplotlib.use('agg')
import matplotlib.pylab as mpy
import os
# Perform tests within temporary directory
with TemporaryDirectory() as tdir:
# wget the data for a ppn run from the CADC VOspace
os.system("wget -q --content-disposition --directory '" + tdir + "' "\
+ "'http://www.canfar.phys.uvic.ca/vospace/synctrans?TARGET="\
+ "vos%3A%2F%2Fcadc.nrc.ca%21vospace%2Fnugrid%2Fdata%2Fprojects%2Fppn%2Fexamples%2F"\
+ "ppn_Hburn_simple%2Fx-time.dat&DIRECTION=pullFromVoSpace&PROTOCOL"\
+ "=ivo%3A%2F%2Fivoa.net%2Fvospace%2Fcore%23httpget'")
#nugrid_dir= os.path.dirname(os.path.dirname(ppn.__file__))
#NuPPN_dir= nugrid_dir + "/NuPPN"
#test_data_dir= NuPPN_dir + "/examples/ppn_Hburn_simple/RUN_MASTER"
symbs=utils.symbol_list('lines2')
x=ppn.xtime(tdir)
specs=['PROT','HE 4','C 12','N 14','O 16']
i=0
for spec in specs:
x.plot('time',spec,logy=True,logx=True,shape=utils.linestyle(i)[0],show=False,title='')
i += 1
mpy.ylim(-5,0.2)
mpy.legend(loc=0)
mpy.xlabel('$\log t / \mathrm{min}$')
mpy.ylabel('$\log X \mathrm{[mass fraction]}$')
abu_evol_file = 'abu_evolution.png'
mpy.savefig(abu_evol_file)
self.assertTrue(os.path.exists(abu_evol_file))
def set_nice_params():
fsize=18
params = {'axes.labelsize': fsize,
# 'font.family': 'serif',
'font.family': 'Times New Roman',
'figure.facecolor': 'white',
'text.fontsize': fsize,
'legend.fontsize': fsize,
'xtick.labelsize': fsize*0.8,
'ytick.labelsize': fsize*0.8,
'text.usetex': False}
pl.rcParams.update(params)
def plot_prof_1(self, mod, species, xlim1, xlim2, ylim1, ylim2,
symbol=None):
"""
plot one species for cycle between xlim1 and xlim2
Parameters
----------
mod : string or integer
Model to plot, same as cycle number.
species : list
Which species to plot.
xlim1, xlim2 : float
Mass coordinate range.
ylim1, ylim2 : float
Mass fraction coordinate range.
symbol : string, optional
Which symbol you want to use. If None symbol is set to '-'.
The default is None.
"""
DataPlot.plot_prof_1(self,species,mod,xlim1,xlim2,ylim1,ylim2,symbol)
"""
tot_mass=self.se.get(mod,'total_mass')
age=self.se.get(mod,'age')
mass=self.se.get(mod,'mass')
Xspecies=self.se.get(mod,'iso_massf',species)
pyl.plot(mass,np.log10(Xspecies),'-',label=species)
pyl.xlim(xlim1,xlim2)
pyl.ylim(ylim1,ylim2)
pyl.legend()
pl.xlabel('$Mass$ $coordinate$', fontsize=20)
pl.ylabel('$X_{i}$', fontsize=20)
pl.title('Mass='+str(tot_mass)+', Time='+str(age)+' years, cycle='+str(mod))
"""
def plot4(self, num):
"""
Plots the abundances of H-1, He-4, C-12 and O-16.
"""
self.plot_prof_1(num,'H-1',0.,5.,-5,0.)
self.plot_prof_1(num,'He-4',0.,5.,-5,0.)
self.plot_prof_1(num,'C-12',0.,5.,-5,0.)
self.plot_prof_1(num,'O-16',0.,5.,-5,0.)
pyl.legend(loc=3)
def plot_prof_sparse(self, mod, species, xlim1, xlim2, ylim1, ylim2,
sparse, symbol):
"""
plot one species for cycle between xlim1 and xlim2.
Parameters
----------
species : list
which species to plot.
mod : string or integer
Model (cycle) to plot.
xlim1, xlim2 : float
Mass coordinate range.
ylim1, ylim2 : float
Mass fraction coordinate range.
sparse : integer
Sparsity factor for points.
symbol : string
which symbol you want to use?
"""
mass=self.se.get(mod,'mass')
Xspecies=self.se.get(mod,'yps',species)
pyl.plot(mass[0:len(mass):sparse],np.log10(Xspecies[0:len(Xspecies):sparse]),symbol)
pyl.xlim(xlim1,xlim2)
pyl.ylim(ylim1,ylim2)
pyl.legend()
def abup_se_plot(mod,species):
"""
plot species from one ABUPP file and the se file.
You must use this function in the directory where the ABP files
are and an ABUP file for model mod must exist.
Parameters
----------
mod : integer
Model to plot, you need to have an ABUPP file for that
model.
species : string
The species to plot.
Notes
-----
The species is set to 'C-12'.
"""
# Marco, you have already implemented finding headers and columns in
# ABUP files. You may want to transplant that into here?
species='C-12'
filename = 'ABUPP%07d0000.DAT' % mod
print(filename)
mass,c12=np.loadtxt(filename,skiprows=4,usecols=[1,18],unpack=True)
c12_se=self.se.get(mod,'iso_massf','C-12')
mass_se=self.se.get(mod,'mass')
pyl.plot(mass,c12)
pyl.plot(mass_se,c12_se,'o',label='cycle '+str(mod))
pyl.legend()
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()
def onehist(x,xlabel='',fontsize=12):
"""
Script that plots the histogram of x with the corresponding xlabel.
"""
pylab.clf()
pylab.rcParams.update({'font.size': fontsize})
pylab.hist(x,histtype='stepfilled')
pylab.legend()
#### Change the X-axis appropriately ####
pylab.xlabel(xlabel)
pylab.ylabel('Number')
pylab.draw()
pylab.show()