def show_results(self):
font = {'family': 'serif',
'color': 'k',
'weight': 'normal',
'size': 12,
}
pl.plot(self.x, self.y, 'c', label='firing angle = 45°')
pl.title('The Trajectory of a Cannon Shell', fontdict = font)
pl.xlabel('x (k$m$)')
pl.ylabel('y ($km$)')
pl.xlim(0, 60)
pl.ylim(0, 20)
pl.grid(True)
pl.legend(loc='upper right', shadow=True, fontsize='large')
pl.text(34.5, 16, ' With air drag and the \n dependence of g on altitude', fontdict = font)
pl.show()
python类ylabel()的实例源码
5 code 4.py 文件源码
项目:computational_physics_N2014301020117
作者: yukangnineteen
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
5 code 3.py 文件源码
项目:computational_physics_N2014301020117
作者: yukangnineteen
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
def show_results(self):
font = {'family': 'serif',
'color': 'k',
'weight': 'normal',
'size': 12,
}
pl.plot(self.x, self.y, 'c', label='firing angle = 45°')
pl.title('The Trajectory of a Cannon Shell', fontdict = font)
pl.xlabel('x (k$m$)')
pl.ylabel('y ($km$)')
pl.xlim(0, 60)
pl.ylim(0, 20)
pl.grid(True)
pl.legend(loc='upper right', shadow=True, fontsize='large')
pl.text(34.5, 16, ' With both air drag and \n reduced air density-adiabatic', fontdict = font)
pl.show()
def plotdata(obsmode,spectrum,val,odict,sdict,
instr,fieldname,outdir,outname):
isetting=P.isinteractive()
P.ioff()
P.clf()
P.plot(obsmode,val,'.')
P.ylabel('(pysyn-syn)/syn')
P.xlabel('obsmode')
P.title("%s: %s"%(instr,fieldname))
P.savefig(os.path.join(outdir,outname+'_obsmode.ps'))
P.clf()
P.plot(spectrum,val,'.')
P.ylabel('(pysyn-syn)/syn')
P.xlabel('spectrum')
P.title("%s: %s"%(instr,fieldname))
P.savefig(os.path.join(outdir,outname+'_spectrum.ps'))
matplotlib.interactive(isetting)
def plot_evaluation_episode_reward():
pylab.clf()
sns.set_context("poster")
pylab.plot(0, 0)
episodes = [0]
average_scores = [0]
median_scores = [0]
for n in xrange(len(csv_evaluation)):
params = csv_evaluation[n]
episodes.append(params[0])
average_scores.append(params[1])
median_scores.append(params[2])
pylab.plot(episodes, average_scores, sns.xkcd_rgb["windows blue"], lw=2)
pylab.xlabel("episodes")
pylab.ylabel("average score")
pylab.savefig("%s/evaluation_episode_average_reward.png" % args.plot_dir)
pylab.clf()
pylab.plot(0, 0)
pylab.plot(episodes, median_scores, sns.xkcd_rgb["windows blue"], lw=2)
pylab.xlabel("episodes")
pylab.ylabel("median score")
pylab.savefig("%s/evaluation_episode_median_reward.png" % args.plot_dir)
def plot_2D_heat_map(states,p,labels, inter=False):
import pylab as pl
X = np.unique(states[0,:])
Y = np.unique(states[1,:])
X_len = len(X)
Y_len = len(Y)
Z = np.zeros((X.max()+1,Y.max()+1))
for i in range(len(p)):
Z[states[0,i],states[1,i]] = p[i]
pl.clf()
pl.imshow(Z.T, origin='lower')
pl.xlabel(labels[0])
pl.ylabel(labels[1])
if inter== True:
pl.draw()
else:
pl.show()
def plot_2D_contour(states,p,labels,inter=False):
import pylab as pl
from pyme.statistics import expectation as EXP
exp = EXP((states,p))
X = np.unique(states[0,:])
Y = np.unique(states[1,:])
X_len = len(X)
Y_len = len(Y)
Z = np.zeros((X.max()+1,Y.max()+1))
for i in range(len(p)):
Z[states[0,i],states[1,i]] = p[i]
Z = np.where(Z < 1e-8,0.0,Z)
pl.clf()
XX, YY = np.meshgrid(X,Y)
pl.contour(range(X.max()+1),range(Y.max()+1),Z.T)
pl.axhline(y=exp[1])
pl.axvline(x=exp[0])
pl.xlabel(labels[0])
pl.ylabel(labels[1])
if inter == True:
pl.draw()
else:
pl.show()
def starPlot(targ_ra, targ_dec, data, iso, g_radius, nbhd):
"""Star bin plot"""
mag_g = data[mag_g_dred_flag]
mag_r = data[mag_r_dred_flag]
filter = star_filter(data)
iso_filter = (iso.separation(mag_g, mag_r) < 0.1)
# projection of image
proj = ugali.utils.projector.Projector(targ_ra, targ_dec)
x, y = proj.sphereToImage(data[filter & iso_filter]['RA'], data[filter & iso_filter]['DEC'])
plt.scatter(x, y, edgecolor='none', s=3, c='black')
plt.xlim(0.2, -0.2)
plt.ylim(-0.2, 0.2)
plt.gca().set_aspect('equal')
plt.xlabel(r'$\Delta \alpha$ (deg)')
plt.ylabel(r'$\Delta \delta$ (deg)')
plt.title('Stars')
def plot_time_freq(self, colors=True, ax=None):
import pylab as pl
if ax is None:
fig, allax = pl.subplots(1)
ax = allax
# make time matrix same shape as others
t = np.outer(self.t, np.ones(self.npeaks))
f = self.f
if colors:
mag = 20*np.log10(self.mag)
ax.scatter(t, f, s=6, c=mag, lw=0)
else:
mag = 100 + 20*np.log10(self.mag)
ax.scatter(t, f, s=mag, lw=0)
pl.xlabel('Time (s)')
pl.ylabel('Frequency (Hz)')
# if colors:
# cs = pl.colorbar(ax=ax)
# cs.set_label('Magnitude (dB)')
# pl.show()
return ax
def plot_time_mag(self):
import pylab as pl
pl.figure()
t = np.outer(self.t, np.ones(self.npeaks))
# f = np.log2(self.f)
f = self.f
mag = 20*np.log10(self.mag)
pl.scatter(t, mag, s=10, c=f, lw=0,
norm=pl.matplotlib.colors.LogNorm())
pl.xlabel('Time (s)')
pl.ylabel('Magnitude (dB)')
cs = pl.colorbar()
cs.set_label('Frequency (Hz)')
# pl.show()
return pl.gca()
def plot_time_freq_mag(self, minlen=10, cm=pl.cm.rainbow):
cadd = 30
cmax = 256
ccur = 0
part = [pp for pp in self.partial if len(pp.f) > minlen]
pl.figure()
pl.hold(True)
for pp in part:
# pl.plot(pp.start_idx + np.arange(len(pp.f)), np.array(pp.f))
mag = 100 + 20*np.log10(np.array(pp.mag))
pl.scatter(pp.start_idx + np.arange(len(pp.f)), np.array(pp.f),
s=mag, c=cm(ccur), lw=0)
ccur = np.mod(ccur + cadd, cmax)
pl.hold(False)
pl.xlabel('Time (s)')
pl.ylabel('Frequency (Hz)')
pl.show()
def visualiseNormObject(self):
shape = (2*self.extent, 2*self.extent)
pylab.ion()
pylab.clf()
#pylab.set_cmap("bone")
pylab.hot()
pylab.title("image: %s" % self.fitsFile)
pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
pylab.colorbar()
pylab.ylim(-1, 2*self.extent)
pylab.xlim(-1, 2*self.extent)
pylab.xlabel("Pixels")
pylab.ylabel("Pixels")
pylab.show()
def visualiseNormObject(self):
shape = (2*self.extent, 2*self.extent)
pylab.ion()
pylab.clf()
#pylab.set_cmap("bone")
pylab.hot()
pylab.title("image: %s" % self.fitsFile)
pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
pylab.colorbar()
pylab.ylim(-1, 2*self.extent)
pylab.xlim(-1, 2*self.extent)
pylab.xlabel("Pixels")
pylab.ylabel("Pixels")
pylab.show()
def main():
data = pd.read_table('../Real_Values.txt').get_values()
x = [float(d) for d in data]
test = np.array([669, 592, 664, 1005, 699, 401, 646, 472, 598, 681, 1126, 1260, 562, 491, 714, 530, 521, 687, 776, 802, 499, 536, 871, 801, 965, 768, 381, 497, 458, 699, 549, 427, 358, 219, 635, 756, 775, 969, 598, 630, 649, 722, 835, 812, 724, 966, 778, 584, 697, 737, 777, 1059, 1218, 848, 713, 884, 879, 1056, 1273, 1848, 780, 1206, 1404, 1444, 1412, 1493, 1576, 1178, 836, 1087, 1101, 1082, 775, 698, 620, 651, 731, 906, 958, 1039, 1105, 620, 576, 707, 888, 1052, 1072, 1357, 768, 986, 816, 889, 973, 983, 1351, 1266, 1053, 1879, 2085, 2419, 1880, 2045, 2212, 1491, 1378, 1524, 1231, 1577, 2459, 1848, 1506, 1589, 1386, 1111, 1180, 1075, 1595, 1309, 2092, 1846, 2321, 2036, 3587, 1637, 1416, 1432, 1110, 1135, 1233, 1439, 894, 628, 967, 1176, 1069, 1193, 1771, 1199, 888, 1155, 1254, 1403, 1502, 1692, 1187, 1110, 1382, 1808, 2039, 1810, 1819, 1408, 803, 1568, 1227, 1270, 1268, 1535, 873, 1006, 1328, 1733, 1352, 1906, 2029, 1734, 1314, 1810, 1540, 1958, 1420, 1530, 1126, 721, 771, 874, 997, 1186, 1415, 973, 1146, 1147, 1079, 3854, 3407, 2257, 1200, 734, 1051, 1030, 1370, 2422, 1531, 1062, 530, 1030, 1061, 1249, 2080, 2251, 1190, 756, 1161, 1053, 1063, 932, 1604, 1130, 744, 930, 948, 1107, 1161, 1194, 1366, 1155, 785, 602, 903, 1142, 1410, 1256, 742, 985, 1037, 1067, 1196, 1412, 1127, 779, 911, 989, 946, 888, 1349, 1124, 761, 994, 1068, 971, 1157, 1558, 1223, 782, 2790, 1835, 1444, 1098, 1399, 1255, 950, 1110, 1345, 1224, 1092, 1446, 1210, 1122, 1259, 1181, 1035, 1325, 1481, 1278, 769, 911, 876, 877, 950, 1383, 980, 705, 888, 877, 638, 1065, 1142, 1090, 1316, 1270, 1048, 1256, 1009, 1175, 1176, 870, 856, 860])
n_predict = 100
extrapolation = fourierExtrapolation(x, n_predict)
pl.figure()
pl.plot(np.arange(len(x), len(extrapolation) + len(x)), extrapolation, 'r', label = 'extrapolation')
pl.plot(x, 'b', label = 'Given Data', linewidth = 3)
pl.legend()
pl.ylabel('BPM')
pl.xlabel('Sample')
pl.title('Fourier Extrapolation')
pl.savefig('FourierExtrapolation.png')
#pl.show()
with open('Fourier_PredValues.txt', 'w') as out:
out.write(str([e for e in extrapolation]).strip('[]'))
def plot_z(z, dir=None, filename="z", xticks_range=None, yticks_range=None):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(16.0, 16.0)
pylab.clf()
for n in xrange(z.shape[0]):
result = pylab.scatter(z[n, 0], z[n, 1], s=40, marker="o", edgecolors='none')
pylab.xlabel("z1")
pylab.ylabel("z2")
if xticks_range is not None:
pylab.xticks(pylab.arange(-xticks_range, xticks_range + 1))
if yticks_range is not None:
pylab.yticks(pylab.arange(-yticks_range, yticks_range + 1))
pylab.savefig("{}/{}.png".format(dir, filename))
def plot(self,title='',include_baseline=False,equal_aspect=True):
""" Method that generates a plot of the ROC curve
Parameters:
title: Title of the chart
include_baseline: Add the baseline plot line if it's True
equal_aspect: Aspects to be equal for all plot
"""
pylab.clf()
pylab.plot([x[0] for x in self.derived_points], [y[1] for y in self.derived_points], self.linestyle)
if include_baseline:
pylab.plot([0.0,1.0], [0.0,1.0],'k-.')
pylab.ylim((0,1))
pylab.xlim((0,1))
pylab.xticks(pylab.arange(0,1.1,.1))
pylab.yticks(pylab.arange(0,1.1,.1))
pylab.grid(True)
if equal_aspect:
cax = pylab.gca()
cax.set_aspect('equal')
pylab.xlabel('1 - Specificity')
pylab.ylabel('Sensitivity')
pylab.title(title)
pylab.show()
def plot(func):
random_state = check_random_state(0)
one_core = []
multi_core = []
sample_sizes = range(1000, 6000, 1000)
for n_samples in sample_sizes:
X = random_state.rand(n_samples, 300)
start = time.time()
func(X, n_jobs=1)
one_core.append(time.time() - start)
start = time.time()
func(X, n_jobs=-1)
multi_core.append(time.time() - start)
pl.figure('scikit-learn parallel %s benchmark results' % func.__name__)
pl.plot(sample_sizes, one_core, label="one core")
pl.plot(sample_sizes, multi_core, label="multi core")
pl.xlabel('n_samples')
pl.ylabel('Time (s)')
pl.title('Parallel %s' % func.__name__)
pl.legend()
def plotAccuracyGraph(X, Y, Xlabel='Variable', Ylabel='Accuracy', graphTitle="Test Accuracy Graph", filename="graph.pdf"):
""" Plots and saves accuracy graphs """
try:
timestamp = int(time.time())
fig = P.figure(figsize=(8,5))
# Set the graph's title
P.title(graphTitle, fontname='monospace')
# Set the axes labels
P.xlabel(Xlabel, fontsize=12, fontname='monospace')
P.ylabel(Ylabel, fontsize=12, fontname='monospace')
# Add horizontal and vertical lines to the graph
P.grid(color='DarkGray', linestyle='--', linewidth=0.1, axis='both')
# Add the data to the graph
P.plot(X, Y, 'r-*', linewidth=1.0)
# Save figure
prettyPrint("Saving figure to ./%s" % filename)#(graphTitle.replace(" ","_"), timestamp))
P.tight_layout()
fig.savefig("./%s" % filename)#(graphTitle.replace(" ", "_"), timestamp))
except Exception as e:
prettyPrint("Error encountered in \"plotAccuracyGraph\": %s" % e, "error")
return False
return True
def generate(self, filename, show=True):
'''Generate a sample sequence, plot the resulting piano-roll and save
it as a MIDI file.
filename : string
A MIDI file will be created at this location.
show : boolean
If True, a piano-roll of the generated sequence will be shown.'''
piano_roll = self.generate_function()
midiwrite(filename, piano_roll, self.r, self.dt)
if show:
extent = (0, self.dt * len(piano_roll)) + self.r
pylab.figure()
pylab.imshow(piano_roll.T, origin='lower', aspect='auto',
interpolation='nearest', cmap=pylab.cm.gray_r,
extent=extent)
pylab.xlabel('time (s)')
pylab.ylabel('MIDI note number')
pylab.title('generated piano-roll')
def visualize_labeled_z(z_batch, label_batch, dir=None):
fig = pylab.gcf()
fig.set_size_inches(20.0, 16.0)
pylab.clf()
colors = ["#2103c8", "#0e960e", "#e40402","#05aaa8","#ac02ab","#aba808","#151515","#94a169", "#bec9cd", "#6a6551"]
for n in xrange(z_batch.shape[0]):
result = pylab.scatter(z_batch[n, 0], z_batch[n, 1], c=colors[label_batch[n]], s=40, marker="o", edgecolors='none')
classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
recs = []
for i in range(0, len(colors)):
recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i]))
ax = pylab.subplot(111)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.legend(recs, classes, loc="center left", bbox_to_anchor=(1.1, 0.5))
pylab.xticks(pylab.arange(-4, 5))
pylab.yticks(pylab.arange(-4, 5))
pylab.xlabel("z1")
pylab.ylabel("z2")
pylab.savefig("%s/labeled_z.png" % dir)
def ansQuest(maxTime,numTrials):
means=[]
distLists=performSim(maxTime,numTrials)
for t in range(maxTime+1):
tot=0.0
for distL in distLists:
tot+=distL[t]
means.append(tot/len(distL))
pylab.figure()
pylab.plot(means)
pylab.xlabel('distance')
pylab.ylabel('time')
pylab.title('Average Distance vs. Time ('+str(len(distLists))+'trials)')