def threehistsx(x1,x2,x3,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',fig=1,fontsize=12,bins1=10,bins2=10,bins3=10):
"""
Script that pretty-plots three histograms of quantities x1, x2 and x3.
Arguments:
:param x1,x2,x3: arrays with data to be plotted
:param x1leg, x2leg, x3leg: legends for each histogram
:param fig: which plot window should I use?
Example:
x1=Lbol(AD), x2=Lbol(JD), x3=Lbol(EHF10)
>>> threehists(x1,x2,x3,38,44,'AD','JD','EHF10','$\log L_{\\rm bol}$ (erg s$^{-1}$)')
Inspired by http://www.scipy.org/Cookbook/Matplotlib/Multiple_Subplots_with_One_Axis_Label.
"""
pylab.rcParams.update({'font.size': fontsize})
pylab.figure(fig)
pylab.clf()
pylab.subplot(3,1,1)
pylab.hist(x1,label=x1leg,color='b',bins=bins1)
pylab.legend(loc='best',frameon=False)
pylab.subplot(3,1,2)
pylab.hist(x2,label=x2leg,color='r',bins=bins2)
pylab.legend(loc='best',frameon=False)
pylab.subplot(3,1,3)
pylab.hist(x3,label=x3leg,color='y',bins=bins3)
pylab.legend(loc='best',frameon=False)
pylab.minorticks_on()
pylab.subplots_adjust(hspace=0.15)
pylab.draw()
pylab.show()
python类legend()的实例源码
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()
def plot_position(self, pos_true, pos_est, cam_states):
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", label="Grouth truth")
# color="red", marker="x", label="Grouth truth")
# Estimated
plt.plot(pos_est[0, :], pos_est[1, :],
color="blue", label="Estimated")
# color="blue", marker="o", label="Estimated")
# Sliding window
cam_pos = []
for cam_state in cam_states:
cam_pos.append(cam_state.p_G)
cam_pos = np.array(cam_pos).reshape((len(cam_pos), 3)).T
plt.plot(cam_pos[0, :], cam_pos[1, :],
color="green", label="Camera Poses")
# color="green", marker="o", label="Camera Poses")
# Plot labels and legends
plt.xlabel("East (m)")
plt.ylabel("North (m)")
plt.axis("equal")
plt.legend(loc=0)
def plot_velocity(self, timestamps, vel_true, vel_est):
N = vel_est.shape[1]
t = timestamps[:N]
vel_true = vel_true[:, :N]
vel_est = vel_est[:, :N]
# Figure
plt.figure()
plt.suptitle("Velocity")
# X axis
plt.subplot(311)
plt.plot(t, vel_true[0, :], color="red", label="Ground_truth")
plt.plot(t, vel_est[0, :], color="blue", label="Estimate")
plt.title("x-axis")
plt.xlabel("Date Time")
plt.ylabel("ms^-1")
plt.legend(loc=0)
# Y axis
plt.subplot(312)
plt.plot(t, vel_true[1, :], color="red", label="Ground_truth")
plt.plot(t, vel_est[1, :], color="blue", label="Estimate")
plt.title("y-axis")
plt.xlabel("Date Time")
plt.ylabel("ms^-1")
plt.legend(loc=0)
# Z axis
plt.subplot(313)
plt.plot(t, vel_true[2, :], color="red", label="Ground_truth")
plt.plot(t, vel_est[2, :], color="blue", label="Estimate")
plt.title("z-axis")
plt.xlabel("Date Time")
plt.ylabel("ms^-1")
plt.legend(loc=0)
def plot_attitude(self, timestamps, att_true, att_est):
# Setup
N = att_est.shape[1]
t = timestamps[:N]
att_true = att_true[:, :N]
att_est = att_est[:, :N]
# Figure
plt.figure()
plt.suptitle("Attitude")
# X axis
plt.subplot(311)
plt.plot(t, att_true[0, :], color="red", label="Ground_truth")
plt.plot(t, att_est[0, :], color="blue", label="Estimate")
plt.title("x-axis")
plt.legend(loc=0)
plt.xlabel("Date Time")
plt.ylabel("rad s^-1")
# Y axis
plt.subplot(312)
plt.plot(t, att_true[1, :], color="red", label="Ground_truth")
plt.plot(t, att_est[1, :], color="blue", label="Estimate")
plt.title("y-axis")
plt.legend(loc=0)
plt.xlabel("Date Time")
plt.ylabel("rad s^-1")
# Z axis
plt.subplot(313)
plt.plot(t, att_true[2, :], color="red", label="Ground_truth")
plt.plot(t, att_est[2, :], color="blue", label="Estimate")
plt.title("z-axis")
plt.legend(loc=0)
plt.xlabel("Date Time")
plt.ylabel("rad s^-1")
def plot_velocity(self, timestamps, vel_true, vel_est):
N = vel_est.shape[1]
t = timestamps[:N]
vel_true = vel_true[:, :N]
vel_est = vel_est[:, :N]
# Figure
plt.figure()
plt.suptitle("Velocity")
# X axis
plt.subplot(311)
plt.plot(t, vel_true[0, :], color="red", label="Ground_truth")
plt.plot(t, vel_est[0, :], color="blue", label="Estimate")
plt.title("x-axis")
plt.xlabel("Date Time")
plt.ylabel("ms^-1")
plt.legend(loc=0)
# Y axis
plt.subplot(312)
plt.plot(t, vel_true[1, :], color="red", label="Ground_truth")
plt.plot(t, vel_est[1, :], color="blue", label="Estimate")
plt.title("y-axis")
plt.xlabel("Date Time")
plt.ylabel("ms^-1")
plt.legend(loc=0)
# Z axis
plt.subplot(313)
plt.plot(t, vel_true[2, :], color="red", label="Ground_truth")
plt.plot(t, vel_est[2, :], color="blue", label="Estimate")
plt.title("z-axis")
plt.xlabel("Date Time")
plt.ylabel("ms^-1")
plt.legend(loc=0)
def test_step(self):
# Step
a_B_history = self.dataset.a_B
w_B_history = self.dataset.w_B
for i in range(30):
(a_B, w_B) = self.dataset.step()
a_B_history = np.hstack((a_B_history, a_B))
w_B_history = np.hstack((w_B_history, w_B))
# Plot
debug = False
# debug = True
if debug:
plt.subplot(211)
plt.plot(self.dataset.time_true, a_B_history[0, :], label="ax")
plt.plot(self.dataset.time_true, a_B_history[1, :], label="ay")
plt.plot(self.dataset.time_true, a_B_history[2, :], label="az")
plt.legend(loc=0)
plt.subplot(212)
plt.plot(self.dataset.time_true, w_B_history[0, :], label="wx")
plt.plot(self.dataset.time_true, w_B_history[1, :], label="wy")
plt.plot(self.dataset.time_true, w_B_history[2, :], label="wz")
plt.legend(loc=0)
plt.show()
utils.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def plot_bias_variance(data_sizes, train_errors, test_errors, name):
pylab.clf()
pylab.ylim([0.0, 1.0])
pylab.xlabel('Data set size')
pylab.ylabel('Error')
pylab.title("Bias-Variance for '%s'" % name)
pylab.plot(
data_sizes, train_errors, "-", data_sizes, test_errors, "--", lw=1)
pylab.legend(["train error", "test error"], loc="upper right")
pylab.grid()
pylab.savefig(os.path.join(CHART_DIR, "bv_" + name + ".png"))
utils.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def plot_roc(auc_score, name, fpr, tpr):
pylab.figure(num=None, figsize=(6, 5))
pylab.plot([0, 1], [0, 1], 'k--')
pylab.xlim([0.0, 1.0])
pylab.ylim([0.0, 1.0])
pylab.xlabel('False Positive Rate')
pylab.ylabel('True Positive Rate')
pylab.title('Receiver operating characteristic (AUC=%0.2f)\n%s' % (
auc_score, name))
pylab.legend(loc="lower right")
pylab.grid(True, linestyle='-', color='0.75')
pylab.fill_between(tpr, fpr, alpha=0.5)
pylab.plot(fpr, tpr, lw=1)
pylab.savefig(
os.path.join(CHART_DIR, "roc_" + name.replace(" ", "_") + ".png"))
utils.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def plot_bias_variance(data_sizes, train_errors, test_errors, name, title):
pylab.figure(num=None, figsize=(6, 5))
pylab.ylim([0.0, 1.0])
pylab.xlabel('Data set size')
pylab.ylabel('Error')
pylab.title("Bias-Variance for '%s'" % name)
pylab.plot(
data_sizes, test_errors, "--", data_sizes, train_errors, "b-", lw=1)
pylab.legend(["test error", "train error"], loc="upper right")
pylab.grid(True, linestyle='-', color='0.75')
pylab.savefig(
os.path.join(CHART_DIR, "bv_" + name.replace(" ", "_") + ".png"), bbox_inches="tight")
utils.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def plot_k_complexity(ks, train_errors, test_errors):
pylab.figure(num=None, figsize=(6, 5))
pylab.ylim([0.0, 1.0])
pylab.xlabel('k')
pylab.ylabel('Error')
pylab.title('Errors for for different values of $k$')
pylab.plot(
ks, test_errors, "--", ks, train_errors, "-", lw=1)
pylab.legend(["test error", "train error"], loc="upper right")
pylab.grid(True, linestyle='-', color='0.75')
pylab.savefig(
os.path.join(CHART_DIR, "kcomplexity.png"), bbox_inches="tight")
def print_graph(X_all, X_test, y_all, y_pred1, y_pred2):
training_size = X_all.shape[0] - X_test.shape[0]
x_full_limit = np.linspace(1, X_all.shape[0], X_all.shape[0])
y_pred_limit = np.linspace(training_size+1, training_size + 1 + X_test.shape[0], X_test.shape[0])
plt.plot(x_full_limit, y_all, label='actual', color='b', linewidth=1)
plt.plot(y_pred_limit, y_pred1, '--', color='r', linewidth=2, label='prediction1')
plt.plot(y_pred_limit, y_pred2, '--', color='g', linewidth=2, label='prediction2')
plt.legend(loc=0)
plt.show()
def print_graph_test(y_test, y_pred1, y_pred2, maxEntries=50):
#y_pred_limit = min(maxEntries, len(y_test))
length = min(maxEntries,len(y_test))
y_pred_limit = np.linspace(1, length, length)
plt.plot(y_pred_limit, y_test, label='actual', color='b', linewidth=1)
plt.plot(y_pred_limit, y_pred1, '--', color='r', linewidth=2, label='prediction1')
plt.plot(y_pred_limit, y_pred2, '--', color='g', linewidth=2, label='prediction2')
plt.legend(loc=0)
plt.show()
texttiling.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
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()
def display(pklfile, request=['train_data_accuracy', 'train_sample_accuracy']) :
for key in request :
plt.plot(pklfile[key], label=key)
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=len(request), mode="expand", borderaxespad=0.)
plt.show()
def N15_testing2():
""" Test direkt the implemented fit method with simulated data."""
x_axis = np.linspace(2850, 2860, 101)*1e6
mod,params = qudi_fitting.make_multiplelorentzian_model(no_of_functions=2)
# print('Parameters of the model',mod.param_names)
p=Parameters()
p.add('l0_amplitude',value=-3e4)
p.add('l0_center',value=2850*1e6+abs(np.random.random(1)*8)*1e6)
# p.add('lorentz0_sigma',value=abs(np.random.random(1)*1)*1e6+0.5*1e6)
p.add('l0_sigma',value=0.5*1e6)
p.add('l1_amplitude',value=p['l0_amplitude'].value)
p.add('l1_center',value=p['l0_center'].value+3.03*1e6)
p.add('l1_sigma',value=p['l0_sigma'].value)
p.add('offset',value=100.)
data_nice = mod.eval(x=x_axis, params=p)
data_noisy=(data_nice + 14000*np.random.normal(size=x_axis.shape))
result = qudi_fitting.make_lorentziandouble_fit(x_axis, data_noisy,
estimator=qudi_fitting.estimate_lorentziandouble_N15)
plt.figure()
plt.plot(x_axis, data_noisy,'-b', label='data')
plt.plot(x_axis, result.init_fit,'-y', label='initial values')
plt.plot(x_axis, result.best_fit,'-r', label='actual fit')
plt.plot(x_axis, data_nice,'-g', label='actual fit')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Counts (#)')
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.show()
def N14_testing_data2():
""" Test the N14 fit with data from file. """
# get the model of the three lorentzian peak, this gives you the
# ability to get the used parameter container for the fit.
mod, params = qudi_fitting.make_multiplelorentzian_model(no_of_functions=3)
# you can insert the whole path with the windows separator
# symbol \ just use the r in front of the string to indicated
# that this is a raw input. The os package will do the rest.
path = os.path.abspath(r'C:\Users\astark\Dropbox\Doctorwork\Software\QuDi-Git\qudi\pulsedODMRdata.csv')
data = np.genfromtxt(path,delimiter=',')
# data = np.loadtxt(path, delimiter=',')
# print(data)
# The data for the fit:
x_axis = data[:,0]*1e8
data_noisy = data[:,1]
result = qudi_fitting.make_N14_fit(x_axis, data_noisy)
print(result.fit_report())
plt.plot(x_axis, data_noisy,'-b', label='data')
plt.plot(x_axis,result.best_fit,'-r', label='best fit result')
plt.plot(x_axis,result.init_fit,'-g',label='initial fit')
# plt.plot(x_axis, data_test,'-k', label='test data')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Counts (#)')
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.show()
def gaussianpeak_testing2():
""" Test the implemented Gaussian peak fit. """
x_axis = np.linspace(0, 5, 11)
ampl = 10000
center = 3
sigma = 1
offset = 10000
mod_final, params = qudi_fitting.make_gaussoffset_model()
data_noisy = mod_final.eval(x=x_axis, amplitude=ampl, center=center,
sigma=sigma, offset=offset) + \
2000*abs(np.random.normal(size=x_axis.shape))
result = qudi_fitting.make_gaussoffsetpeak_fit(x_axis=x_axis, data=data_noisy)
plt.figure()
plt.plot(x_axis, data_noisy,'-b', label='data')
plt.plot(x_axis, result.best_fit,'-r', label='best fit result')
plt.plot(x_axis, result.init_fit,'-g',label='initial fit')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Counts (#)')
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.show()
print(result.fit_report())
def gaussiandip_testing2():
""" Test the implemented Gaussian dip fit. """
x_axis = np.linspace(0, 5, 11)
ampl = -10000
center = 3
sigma = 1
offset = 10000
mod_final, params = qudi_fitting.make_gaussoffset_model()
data_noisy = mod_final.eval(x=x_axis, amplitude=ampl, center=center,
sigma=sigma, offset=offset) + \
5000*abs(np.random.normal(size=x_axis.shape))
result = qudi_fitting.make_gaussoffsetdip_fit(x_axis=x_axis, data=data_noisy)
plt.figure()
plt.plot(x_axis, data_noisy,'-b', label='data')
plt.plot(x_axis, result.best_fit,'-r', label='best fit result')
plt.plot(x_axis, result.init_fit,'-g',label='initial fit')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Counts (#)')
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.show()
print(result.fit_report())
def gaussianlinearoffset_testing_data():
x = np.linspace(0, 5, 30)
x_nice=np.linspace(0, 5, 101)
mod_final,params = qudi_fitting.make_gaussianwithslope_model()
data=np.loadtxt("./../1D_shllow.csv")
data_noisy=data[:,1]
data_fit=data[:,3]
x=data[:,2]
update=dict()
update["slope"]={"min":-np.inf,"max":np.inf}
update["offset"]={"min":-np.inf,"max":np.inf}
update["sigma"]={"min":-np.inf,"max":np.inf}
update["center"]={"min":-np.inf,"max":np.inf}
update["amplitude"]={"min":-np.inf,"max":np.inf}
result=qudi_fitting.make_gaussianwithslope_fit(x_axis=x, data=data_noisy, add_params=update)
#
##
# gaus=gaussian(3,5)
# qudi_fitting.data_smooth = filters.convolve1d(qudi_fitting.data_noisy, gaus/gaus.sum(),mode='mirror')
plt.plot(x,data_noisy,label="data")
plt.plot(x,data_fit,"k",label="old fit")
plt.plot(x,result.init_fit,'-g',label='init')
plt.plot(x,result.best_fit,'-r',label='fit')
plt.legend()
plt.show()
print(result.fit_report())