本文整理汇总了Python中mpldatacursor.datacursor函数的典型用法代码示例。如果您正苦于以下问题:Python datacursor函数的具体用法?Python datacursor怎么用?Python datacursor使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了datacursor函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: plot_histogram
def plot_histogram(self, bf, row, col, plot_sigma=True,
hold=False):
self.bf = bf
if self.bf is None:
raise Exception("Need to pass in a BinFile instance to plot object")
if not hasattr(self.bf, 'data_out'):
raise Exception("BinFile instance does not have any data.")
if not hold:
self.clear()
self.lines = []
try:
h = self.bf.data_out[row, col, :, :].real.flatten()
except:
print "Error in extracting histogram"
if hasattr(self.bf, 'pixel_label'):
label="Row%d, Col%d (Pix: %s)" % (self.bf.row_start+row, self.bf.col_start+col, self.bf.pixel_label.get((row, col), 'NC'))
else:
label="Row%d, Col%d" % (self.bf.row_start+row, self.bf.col_start+col)
self.hist(h, bins=20, label=label)
if MATPLOTLIBV1_0:
datacursor()
self.set_subplot_title("%s" % self.bf.basename)
if plot_sigma:
y1, y2 = self.get_ylims()
for x in (-8, 8):
self.plot([x, x], [y1, y2], 'r--', linewidth=2,
label="_nolegend_")
self.set_xlim(-64, 64)
self.set_legend(loc='best')
开发者ID:gopastro,项目名称:pyphamas,代码行数:29,代码来源:x64plots.py
示例2: plot
def plot(self):
specs = pl.array( list(set([ l['spec'] for l in self.lines ])) )
specs.sort()
self.specs = specs
pl.figure()
pl.hold('on')
pl.grid('on')
pl.jet()
lines = []
lines_spec = list(pl.zeros(len(specs)))
for i in range(0,len(self.lines)):
ispc = pl.find( specs == self.lines[i]['spec'] )
self.colr = pl.cm.get_cmap()( float(ispc)/len(specs) )
wl = self.lines[i]['wave']
ri = float(self.lines[i]['rel_int'])
lines.append( pl.plot( [wl, wl], [0., ri if not isnan(ri) else 0.], '.-', color=self.colr )[0] )
lines_spec[ispc] = lines[-1]
datacursor(lines,formatter='x={x:8.3f}\ny={y:8.3f}'.format)
pl.rc('text',usetex=True)
pl.xlabel('$\lambda ~ [\AA]$')
pl.ylabel('relative intensity [arb]')
pl.title('Spectrum for '+self.spec+' from NIST ASD')
if len(specs) > 1:
pl.legend( lines_spec,specs )
pl.show()
开发者ID:atronchi,项目名称:NISTASD,代码行数:30,代码来源:NISTASD.py
示例3: measure_iv
def measure_iv(self):
self.get_vd_values()
self.textBrowser.append('Measuring I-V from ' + str(self.vd_start) +
'V to ' + str(self.vd_stop) + ' V')
vd_values = np.linspace(self.vd_start, self.vd_stop, num=self.vd_steps,
endpoint=True)
id_values = np.zeros_like(vd_values)
# self.measure_current()
for i, vd in np.ndenumerate(vd_values):
self.set_voltage_vd(vd)
id_values[i] = self.measure_current()
if self.stop_engaged:
print('stop')
self.stop_engaged = False
break
self.update_progress((i[0] + 1.0)/self.vd_steps)
self.set_voltage_vd(0)
self.textBrowser.append('Measurement completed')
data = pd.DataFrame({'Voltage': vd_values, 'Current': id_values})
data.set_index('Voltage', inplace=True)
self.data_iv = data
data.to_csv('measurement_iv.csv')
data.to_msgpack('measurement_iv.msgpack')
ax = data.plot()
datacursor(ax)
# datacursor(display='single', draggable=True)
winsound.Beep(750, 1000)
fig = ax.get_figure()
fig.savefig('measurement_iv.png')
plt.show()
开发者ID:vishniakou,项目名称:scientific-instruments,代码行数:31,代码来源:fet_measurement.py
示例4: plot_k_walls
def plot_k_walls(k_walls, plot_range=None,
plot_data_points=False,):
"""
Plot K-walls for debugging purpose.
"""
pyplot.figure()
pyplot.axes().set_aspect('equal')
for k_wall in k_walls:
xs = k_wall.get_xs()
ys = k_wall.get_ys()
pyplot.plot(xs, ys, '-', label=k_wall.identifier)
if(plot_data_points == True):
pyplot.plot(xs, ys, 'o', color='k', markersize=4)
if plot_range is None:
pyplot.autoscale(enable=True, axis='both', tight=None)
else:
[[x_min, x_max], [y_min, y_max]] = plot_range
pyplot.xlim(x_min, x_max)
pyplot.ylim(y_min, y_max)
mpldatacursor.datacursor(
formatter='{label}'.format,
hover=True,
)
pyplot.show()
开发者ID:chan-y-park,项目名称:mose,代码行数:29,代码来源:plotting.py
示例5: exploredata1d
def exploredata1d(data, slider='chans', stack='ants'):
""" Set up interactive 1d (line) plotting for vis data of dimension (ints, ants, chans). """
axdict = {'ints': 0, 'ants': 1, 'chans': 2}
assert slider in axdict.keys() and stack in axdict.keys(), 'slider or stack param not allowed'
slax = axdict[slider]
# need to account for axis shift after first 'take'
stax = axdict[stack] if axdict[stack] <= slax else axdict[stack] - 1
slmax = data.shape[axdict[slider]]
stmax = data.shape[axdict[stack]]
xaxis = [name for name in axdict.keys() if name != slider and name != stack][0]
fcndict = {'Real': np.real, 'Imag': np.imag, 'Amp': np.abs, 'Phase': np.angle}
@interact(sl=(0, slmax, 1), f=['Real', 'Imag', 'Amp', 'Phase'])
def plotautos(sl, f):
pl.figure(figsize=(15,8))
pl.clf()
pl.xlabel(xaxis)
pl.ylabel(f)
fcn = fcndict[f]
for st in range(stmax):
pl.plot(fcn(data.take(sl, axis=slax).take(st, axis=stax)), label='{0} {1}'.format(stack.rstrip('s'), st))
print('Plotting {0} vs. {1}.'.format(f, xaxis))
print('Slider for {0}. A line per {1}.'.format(slider, stack.rstrip('s')))
print('Click on a line to see {0} number'.format(stack.rstrip('s')))
datacursor(formatter='{label}'.format)
开发者ID:HERA-Team,项目名称:herajupyter,代码行数:32,代码来源:herajupyter.py
示例6: Graph_Instant_boot
def Graph_Instant_boot():
print ('inside Graph_Instant_boot graph')
Plot1 = np.loadtxt('Output_VHFS_Instant_boot.txt')
Plot2 = np.loadtxt('Output_VHFS_Instant_boot_2.txt')
fig = plt.figure()
#pl.subplot(311)
pl.title('Instant_Boot: VHFS1 vs VHFS2')
pl.xlabel('Incrementals')
pl.ylabel('Time Taken in secs')
pl.xlim(-1,11)
x = Plot1[:,0]
y = Plot1[:,1]
y2 = Plot2[:,1]
#yerr = Plot1[:,4]
#xticks = Plot1[:,1]
#plt.xticks(xticks)
#plt.xscale('log')
#plt.yscale('log')
#plt.xticks(xticks)
#pl.errorbar(x,y,yerr,ecolor='b')
pl.plot(x,y, 'b', label = 'VHFS1', marker = 'o')
pl.plot(x,y2, 'y', label = 'VHFS2', marker = 'o')
pl.legend(loc = 'upper right', numpoints = 1)
datacursor(display='multiple', draggable=True)
#pl.show()
pl.savefig('Instant_boot_VHFS_vs_VHD.ps')
pl.savefig('Instant_boot_VHFS_vs_VHD.png')
pl.savefig('Instant_boot_VHFS_vs_VHD.pdf')
print ('endddd')
plt.close(fig)
开发者ID:preeyakrish,项目名称:Research_on_VHFS,代码行数:34,代码来源:Graph_for_instant_Boot.py
示例7: main
def main(icorr_mean_list):
suffix = rate2suffix(icorr_mean_list)
# load data
datapath = os.path.join(os.path.abspath('./'), 'data')
filename = 'popdata_'+suffix+'.npz'
datafile = os.path.join(datapath,filename)
if os.path.isfile(datafile) is False:
print 'no data available, execute Life_Cycle_Optimization.py with \
icorr_mean_list={} fist'.format(icorr_mean_list)
sys.exit(1)
else:
popdata = np.load(datafile)
allpop = popdata['allpop']
allfits = popdata['allfits']
front = popdata['front']
frontfits = popdata['frontfits']
pop = popdata['pop']
popfits = popdata['popfits']
plt.ion()
plt.close('all')
##plt.semilogx(np.array(frontfits)[:,0], np.array(frontfits)[:,1], 'bo', markeredgecolor='b')
#plt.semilogx(np.array(popfits)[:,0], np.array(popfits)[:,1], 'bo', markeredgecolor='b')
#for popfit in popfits:
for ind, popfit in zip(pop, popfits):
## journal version
#plt.semilogx(popfit[0], popfit[1], 'bo',markeredgecolor='b',
#label=u'flexure: {:d}, shear: {:d}, deck: {:d}'.format(ind[0], ind[1], ind[2]))
# conference version
plt.semilogx(popfit[0], popfit[1], 'bo',markeredgecolor='b',
label=u'({:d},{:d},{:d})'.format(ind[0], ind[1], ind[2]))
plt.ylim((-1,np.max(popfits)*1.1))
ax = plt.gca()
ax.ticklabel_format(axis='y', style='sci', scilimits=(-3,3))
plt.xlabel(u'Failure probability')
plt.ylabel(u'Strengthening cost (mm\\textsuperscript{3})')
## journal version
#annotate_text = u'P={x:.2e}, C={y:.2e}\n {{ {label} }}'
#datacursor(formatter=annotate_text.format,display='multiple', draggable=True,
#bbox=None, fontsize=9,
#arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))
# conference version
annotate_text = u'{label}'
datacursor(formatter=annotate_text.format,display='multiple', draggable=True,
bbox=None, fontsize=9,
arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))
pause = raw_input('press any key after annotation...')
plt.semilogx(np.array(allfits)[:,0], np.array(allfits)[:,1], 'o', markerfacecolor='lightgrey',
markeredgecolor='lightgrey', alpha=0.8)
plt.semilogx(np.array(popfits)[:,0], np.array(popfits)[:,1], 'bo', markeredgecolor='b')
开发者ID:cedavidyang,项目名称:Life_Cycle_Management_Optimization,代码行数:56,代码来源:frontPostProcessing.py
示例8: implot_data
def implot_data(self, bf, data_type='amp',
vmin=None, vmax=None,
hold=False, title=None,
colorbar=True, sti=False, **kwargs):
self.bf = bf
if self.bf is None:
raise Exception("Need to pass in a BinFile instance to plot object")
self.check_alive()
if not hold:
self.clear()
if not hasattr(self.bf, 'cross_corr') and not hasattr(self.bf, 'sti_cc'):
raise Exception("BinFile does not have cross correlation data. get_cross_corr_data() first on binfile")
if sti:
if not hasattr(self.bf, 'sti_cc'):
raise Exception("BinFile does not have sti cross corr data. Run sti_cross_correlate first")
self.bf.cc = self.bf.sti_cc.mean(axis=3).mean(axis=2)
else:
self.bf.cc = self.bf.cross_corr.mean(axis=2)
if MATPLOTLIBV1_0:
interpolation = 'none'
else:
interpolation = 'nearest'
if data_type == 'amp':
self.image = self.imshow(10*numpy.log10(numpy.abs(self.bf.cc)),
cmap=cm.spectral, interpolation=interpolation,
vmin=vmin, vmax=vmax,
**kwargs)
else:
self.image = self.imshow(numpy.angle(self.bf.cc),
cmap=cm.spectral, interpolation=interpolation,
vmin=vmin, vmax=vmax,
**kwargs)
ax, kw = self.plotobj._get_current_axes()
if MATPLOTLIBV1_0:
datacursor(self.image, display='single',bbox=dict(fc='white'),
arrowprops=dict(arrowstyle='simple', fc='white', alpha=0.5),
formatter="x: {x:.0f}\ny: {y:.0f}\nz: {z:.2f}".format)
def format_coord(x, y):
if data_type == 'amp':
z = (10*numpy.log10(numpy.abs(self.bf.cc)))[x, y]
else:
z = (numpy.angle(self.bf.cc))[x, y]
return 'x=%.1f, y=%.1f, z=%.2f' % (x, y, z)
ax, kw = self.plotobj._get_current_axes()
ax.format_coord = format_coord
# self.set_subplot_title(title)
if title is None:
title = "%s" % self.bf.basename
self.set_subplot_title(title)
if colorbar:
self.colorbar()
开发者ID:gopastro,项目名称:pyphamas,代码行数:53,代码来源:x64plots.py
示例9: omni_view
def omni_view(reds,vis,pol,int=10,chan=500,norm=False,cursor=True,save=None,colors=None,symbols=None, ex_ants=[]):
if not colors:
colors = ["#006BA4", "#FF7F0E", "#2CA02C", "#D61D28", "#9467BD", "#8C564B", "#E377C2", "#7F7F7F", "#BCBD22", "#17BECF"]
if not symbols:
symbols = ["o", "v", "^", "<", ">", "*"]
points = []
sym = []
col = []
bl = []
ngps = len(reds)
if save:
plt.clf()
plt.cla()
for i,gp in enumerate(reds):
c = colors[i%len(colors)]
s = symbols[i/len(colors)]
for r in gp:
if np.any([ant in r for ant in ex_ants]): continue
try:
points.append(vis[r][pol][int,chan])
bl.append(r)
except(KeyError):
points.append(np.conj(vis[r[::-1]][pol][int,chan]))
bl.append(r[::-1])
sym.append(s)
col.append(c)
points = np.array(points)
max_x=0
max_y=0
ax = plt.subplots(111)
for i,pt in enumerate(points):
if norm:
ax.scatter(pt.real/np.abs(pt), pt.imag/np.abs(pt), c=col[i], marker=sym[i], s=50, label='{}'.format(bl[i]))
else:
ax.scatter(pt.real, pt.imag, c=col[i], marker=sym[i], s=50, label='{}'.format(bl[i]))
if np.abs(pt.real) > max_x: max_x = np.abs(pt.real)
if np.abs(pt.imag) > max_y: max_y = np.abs(pt.imag)
if norm:
plt.xlim(-1,1)
plt.ylim(-1,1)
else:
plt.xlim(-max_x-.1*max_x,max_x+.1*max_x)
plt.ylim(-max_y-.1*max_y,max_y+.1*max_y)
plt.ylabel('imag(V)')
plt.xlabel('real(V)')
if cursor:
from mpldatacursor import datacursor
datacursor(formatter='{label}'.format)
if save:
plt.savefig(save)
return None
开发者ID:SaulAryehKohn,项目名称:capo,代码行数:52,代码来源:plot.py
示例10: lifetimefitting
def lifetimefitting(icorr_mean_list, str_yr_list=[0., 0., 0.]):
from scipy import stats
from scipy.optimize import curve_fit
# load data
suffix = rate2suffix(icorr_mean_list)
filename = 'pfhistory_str_'
for ti in str_yr_list:
filename = filename + str(int(ti)) + '_'
datapath = os.path.join(os.path.abspath('./'), 'data')
filename = filename+suffix+'.npz'
datafile = os.path.join(datapath,filename)
if os.path.isfile(datafile) is False:
print 'no data available, execute Life_Cycle_History.py with \
icorr_mean_list={} and str_yr_list={} fist'.format(icorr_mean_list,
str_yr_list)
sys.exit(1)
else:
pfhistory = np.load(datafile)
time_array = pfhistory['time']
pf_sys = pfhistory['system']
# lifetime fitting
# candidate cdfs
def fitexpon(xdata, *params):
lbd = params[0]
return stats.expon.cdf(xdata, scale=1./lbd)
def fitweibull(xdata, *params):
k = params[0] # shape param k in Weibull wiki
lbd = params[1] # scale param lbd in Weibull wiki
return stats.weibull_min.cdf(xdata, k, scale=lbd)
def fitgamma(xdata, *params):
k=params[0]
theta = params[1]
return stats.gamma.cdf(xdata, k, scale=theta)
poptExpon, pcovExpon = curve_fit(fitexpon, time_array, pf_sys, p0=[1.], bounds=(0.,np.inf))
poptWbl, pcovWbl = curve_fit(fitweibull, time_array, pf_sys, p0=[1.,5.], bounds=([0.,0.],[np.inf, np.inf]))
poptGamma, pcovGamma = curve_fit(fitgamma, time_array, pf_sys, p0=[1.,1.], bounds=([0.,0.],[np.inf,np.inf]))
plt.ion()
plt.figure()
plt.semilogy(time_array, pf_sys, 'o', label='$T_f$ data')
plt.semilogy(time_array, fitexpon(time_array, poptExpon[0]), ls='--', label='Exponential')
plt.semilogy(time_array, fitweibull(time_array,poptWbl[0],poptWbl[1]), ls='-', label='Weibull')
plt.semilogy(time_array, fitgamma(time_array,poptGamma[0],poptGamma[1]), ls=':', label='Gamma')
plt.xlabel('Time (year)')
plt.ylabel('Failure probability')
#plt.legend(loc='lower right', fontsize=9)
datacursor(formatter='{label}'.format,display='multiple', draggable=True,
bbox=None, fontsize=9,
arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))
开发者ID:cedavidyang,项目名称:Life_Cycle_Management_Optimization,代码行数:52,代码来源:optimizePostProcessing.py
示例11: Graph_GFS_write
def Graph_GFS_write():
print ('inside Graph_GFS graph')
Plot3 = np.loadtxt('Merge_write.txt')
Plot4 = np.loadtxt('Merge_read.txt')
fig = plt.figure()
pl.subplot(311)
pl.title('Write :: Chunk_and_Block Size vs Speed')
pl.xlabel('Chunk_and_Block Size in MB')
pl.ylabel('Speed in MBps')
#pl.xlim(0,10)
x = Plot3[:,1]
y = Plot3[:,3]
yerr = Plot3[:,4]
xticks = Plot3[:,1]
#plt.xticks(xticks)
plt.xscale('log')
#plt.yscale('log')
#plt.xticks(xticks)
pl.errorbar(x,y,yerr,ecolor='b')
#pl.plot(x,y, 'b-', marker ='o',)
datacursor(display='multiple', draggable=True)
#cursor = Dcursor.FollowDotCursor(ax, x, y)
#plt.show()
#pl.show()
pl.subplot(313)
pl.title('Read :: Chunk_and_Block Size vs Speed')
pl.xlabel('Chunk_and_Block Size in MB')
pl.ylabel('Speed in MBps')
#pl.xlim(0,10)
x = Plot4[:,1]
y = Plot4[:,3]
yerr = Plot4[:,4]
xticks = Plot4[:,1]
pl.xticks(xticks)
plt.xscale('log')
pl.errorbar(x,y,yerr,ecolor='b')
datacursor(display='multiple', draggable=True)
#pl.plot(x,y, 'b-', marker = 'o')
#pl.show()
#Dcursor2.DataCursor([write,read])
pl.show()
pl.savefig('GFS_Reading.ps')
pl.savefig('GFS_Reading.png')
pl.savefig('GFS_Reading.pdf')
print ('endddd')
plt.close(fig)
开发者ID:preeyakrish,项目名称:Research_on_VHFS,代码行数:52,代码来源:For_Ploting_GFS.py
示例12: plot_avg_time_locked_data
def plot_avg_time_locked_data(timeLockedData, timeAxis, subplot=None, timeToPlot=None, remove_channels=None, picker=None, labels=False, figure_id=0, figure=None):
if timeToPlot==None:
if np.size(np.shape(timeLockedData)) > 1:
samplesToPlot = [0, np.shape(timeLockedData)[1]]
else:
samplesToPlot = [0, np.shape(timeLockedData)[0]]
else:
Freq = len(timeAxis)/(timeAxis[-1]-timeAxis[0])
startingTimeDif = timeToPlot[0] - timeAxis[0]
endingTimeDif = timeToPlot[1] - timeAxis[0]
if startingTimeDif < 0:
raise ArithmeticError("The starting time to plot must be after the starting time of the trial")
if endingTimeDif < 0:
raise ArithmeticError("The end time to plot must be after the starting time of the trial")
samplesToPlot = [startingTimeDif*Freq, endingTimeDif*Freq]
if figure is None:
fig = plt.figure(figure_id)
else:
fig = figure
if subplot is not None:
ax = fig.add_subplot(subplot)
else:
ax = fig.add_subplot(111)
if picker:
def on_pick(event):
event.artist.set_visible(not event.artist.get_visible())
print(ax.lines.index(event.artist))
fig.canvas.draw()
fig.canvas.callbacks.connect('pick_event', on_pick)
if remove_channels is not None:
timeLockedData[remove_channels, :] = float('nan')
if np.size(np.shape(timeLockedData)) > 1:
lines = ax.plot(timeAxis[samplesToPlot[0]:samplesToPlot[1]], np.transpose(timeLockedData[:, samplesToPlot[0]:samplesToPlot[1]]), picker=picker)
else:
lines = ax.plot(timeAxis[samplesToPlot[0]:samplesToPlot[1]], timeLockedData[samplesToPlot[0]:samplesToPlot[1]], picker=picker)
if labels:
datacursor(hover=True)
for i in np.arange(0,len(lines)):
lines[i].set_label(str(i))
fig.add_subplot(ax)
plt.show()
return ax
开发者ID:georgedimitriadis,项目名称:themeaningofbrain,代码行数:50,代码来源:ploting_functions.py
示例13: plot_iv
def plot_iv(data,range,res,symbol):
fig=plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
act,=ax1.plot(data.DELTA,data.VOLATILITY,'r*',label='Actual Smile')
fit,=ax1.plot(range,res,'g',label='Fitted Smile')
ax1.set_xlabel('DELTA')
ax1.set_ylabel('VOLATILITY')
#ax2.plot(data.STRIKE_PR,data.VOLATILITY,'b*',label='Actual Smile')
ax2.set_xticks(data.DELTA)
ax2.set_xticklabels(data.STRIKE_PR,rotation=90,fontsize=12)
ax2.set_xlabel('STRIKE')
#plt.show()
datacursor()
plt.savefig("%s_VOL.jpg"%symbol)
开发者ID:ashgen,项目名称:NSEDataAnalytics,代码行数:16,代码来源:SplineInterpVol.py
示例14: datacursor
def datacursor(self, widget, unit=None, labname='Label'):
''' Plot datacursors (useful when the number of lines gets confusing)
Parameters
----------
unit and labname:
to customize the info box'''
# Clean previous cursors (prevent overlaps with remaining cursors)
while len(self.cursors) > 0:
dc = self.cursors.pop()
dc.hide().disable()
if self.actionDatacursor.isChecked() and CURSOR_AVAIL:
def formatter(x=None, y=None, z=None, s=None, label=None, **kwargs):
ax = kwargs['event'].mouseevent.inaxes
output = []
output.append(u't: {0:0.3e} s'.format(x))
output.append(u'y: {0:0.3e} {1}'.format(y, unit))
for key, val in zip(['z', 's'], [z, s]):
if val is not None:
try:
output.append(
u'{key}: {val:0.3e}'.format(key=key, val=val))
except ValueError:
# X & Y will be strings at this point.
# For masked arrays, etc, "z" and s values may be a
# string
output.append(
u'{key}: {val}'.format(key=key, val=val))
# label may be None or an empty string (for an un-labeled AxesImage)...
# Un-labeled Line2D's will have labels that start with an
# underscore
if label and not label.startswith('_'):
output.append(u'{0}: {1}'.format(labname, label))
if kwargs.get(u'point_label', None) is not None:
output.append(
u'Point: ' + u', '.join(kwargs['point_label']))
return u'\n'.join(output)
for ax in widget.axes:
if not ax.cursorlines is None:
self.cursors.append(mpldatacursor.datacursor(
ax.cursorlines, hover=True, size=10, color='k',
bbox=dict(fc='white', alpha=0.9),
formatter=formatter))
return None
开发者ID:erwanp,项目名称:qtplaskin,代码行数:55,代码来源:main.py
示例15: front_deprecated
def front_deprecated(icorr_mean_list):
suffix = rate2suffix(icorr_mean_list)
# load data
datapath = os.path.join(os.path.abspath('./'), 'data')
filename = 'popdata_'+suffix+'.npz'
datafile = os.path.join(datapath,filename)
if os.path.isfile(datafile) is False:
print 'no data available, execute Life_Cycle_Optimization.py with \
icorr_mean_list={} fist'.format(icorr_mean_list)
sys.exit(1)
else:
popdata = np.load(datafile)
# all pop is the same as pop
allpop = popdata['allpop']
allfits = popdata['allfits']
front = popdata['front']
frontfits = popdata['frontfits']
pop = popdata['pop']
popfits = popdata['popfits']
plt.ion()
plt.figure()
##plt.semilogx(np.array(frontfits)[:,0], np.array(frontfits)[:,1], 'bo', markeredgecolor='b')
for ind, popfit in zip(front, frontfits):
plt.semilogx(popfit[0], popfit[1], 'bo',
label=u'flexure: {:d}, shear: {:d}, deck: {:d}'.format(ind[0], ind[1], ind[2]))
plt.ylim((-1,np.max(popfits)*1.01))
ax = plt.gca()
ax.ticklabel_format(axis='y', style='sci', scilimits=(-3,3))
plt.xlabel(u'Failure probability (log scale)', fontsize=12)
plt.ylabel(u'Strengthening cost (mm\\textsuperscript{3})', fontsize=12)
annotate_text = u'P={x:.2e}, C={y:.2e}\n {{ {label} }}'
datacursor(formatter=annotate_text.format,display='multiple', draggable=True,
bbox=None, fontsize=12,
arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))
pause = raw_input('press any key after annotation...')
开发者ID:cedavidyang,项目名称:Life_Cycle_Management_Optimization,代码行数:41,代码来源:optimizePostProcessing.py
示例16: costkeeping
def costkeeping(icorr_mean_list):
suffix = rate2suffix(icorr_mean_list)
# load data
datapath = os.path.join(os.path.abspath('./'), 'data')
filename = 'costkeeping_'+suffix+'.npz'
datafile = os.path.join(datapath,filename)
if os.path.isfile(datafile) is False:
print 'no data available, execute Life_Cycle_Optimization.py with \
icorr_mean_list={} fist'.format(icorr_mean_list)
sys.exit(1)
else:
costkeeping = np.load(datafile)
plt.ion()
plt.figure()
plt.plot(costkeeping['flexure'][0,:], costkeeping['flexure'][1,:], 'b-',
label='Flexure (girder)')
plt.plot(costkeeping['shear'][0,:], costkeeping['shear'][1,:], 'r--',
label='Shear (girder)')
plt.plot(costkeeping['deck'][0,:], costkeeping['deck'][1,:], 'g-.',
label='Deck')
service_life = np.max((np.max(costkeeping['flexure'][0,:]),
np.max(costkeeping['shear'][0,:]), np.max(costkeeping['deck'][0,:])))
max_cost = np.max((np.max(costkeeping['flexure'][1,:]),
np.max(costkeeping['shear'][1,:]), np.max(costkeeping['deck'][1,:])))
plt.xlim((-1,service_life+1))
plt.ylim((-1,max_cost*1.01))
plt.xlabel('Strengthening time (year)')
plt.ylabel('Volumn of FRP (mm\\textsuperscript{3})')
ax = plt.gca()
ax.ticklabel_format(axis='y', style='sci', scilimits=(-3,3))
datacursor(formatter='{label}'.format,display='multiple', draggable=True,
bbox=None, fontsize=9,
arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3', facecolor='k'))
pause = raw_input('press any key after annotation...')
开发者ID:cedavidyang,项目名称:Life_Cycle_Management_Optimization,代码行数:39,代码来源:optimizePostProcessing.py
示例17: plot_rl
def plot_rl(self):
if self.cursor is not None: self.cursor.hide().disable()
matplotlib.rcdefaults()
self.figure.clf()
self.figure.subplots_adjust(left = 0.12, bottom = 0.12, right = 0.88, top = 0.98)
axes1 = self.figure.add_subplot(111)
axes1.cla()
axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix))
axes1.set_xlabel('Hz')
axes1.set_ylabel('Return loss, dB')
magnitude = np.absolute(self.gamma())
axes1.plot(self.xaxis, 20.0 * np.log10(magnitude), color = 'blue', label = 'Return loss')
self.cursor = datacursor(axes = self.figure.get_axes(), formatter = LabelFormatter(), display = 'multiple')
self.canvas.draw()
开发者ID:Split7fire,项目名称:red-pitaya-notes,代码行数:14,代码来源:vna.py
示例18: get_opt_vol_data_hist
def get_opt_vol_data_hist(symbol):
db=MySQLdb.connect(config.host,config.user,config.password,'NSE')
points=pd.DataFrame()
fig=plt.figure()
for i in [0,1,5]:
date=pd.read_sql(last_date_query%i,db)
date=date.timestamp[0].__str__()
data=get_opt_vol_data(symbol, date)
(range,res,pol)=perform_spline_calc(data, xlow=0, xhigh=1, xsep=0.02)
if i==0:
points=data.DELTA
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
act,=ax1.plot(data.DELTA,data.VOLATILITY,'r*',label='Actual Smile')
fit,=ax1.plot(range,res,'g',label='Fitted Smile')
ax1.set_xlabel('DELTA')
ax1.set_ylabel('VOLATILITY')
#ax2.plot(data.STRIKE_PR,data.VOLATILITY,'b*',label='Actual Smile')
ax2.set_xticks(data.DELTA)
ax2.set_xticklabels(data.STRIKE_PR,rotation=90,fontsize=12)
ax2.set_xlabel('STRIKE')
elif i==1:
ax1.plot(points,pol(points),'r',label='1 day ago')
else:
ax1.plot(points,pol(points),'b',label='7 days ago')
lgd=ax1.legend(loc='upper left',bbox_to_anchor=(1,1))
datacursor()
fig.savefig("%s_VOL.jpg"%symbol, bbox_extra_artists=(lgd,), bbox_inches='tight')
db.close()
开发者ID:ashgen,项目名称:NSEDataAnalytics,代码行数:37,代码来源:SplineInterpVol.py
示例19: set_data_cursor
def set_data_cursor(self):
if self.current_plot_idx is None:
return None
# Use a DataCursor to interactively display the label
# for artists of the current axes.
self.data_cursor = mpldatacursor.datacursor(
axes=self.plots[self.current_plot_idx],
formatter='{label}'.format,
tolerance=4,
hover=True,
#display='single',
#display='multiple',
#draggable=True,
)
开发者ID:chan-y-park,项目名称:mose,代码行数:15,代码来源:network_plot.py
示例20: plot_swr
def plot_swr(self):
if self.cursor is not None: self.cursor.hide().disable()
matplotlib.rcdefaults()
self.figure.clf()
self.figure.subplots_adjust(left = 0.12, bottom = 0.12, right = 0.88, top = 0.98)
axes1 = self.figure.add_subplot(111)
axes1.cla()
axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix))
axes1.yaxis.set_major_formatter(FuncFormatter(metric_prefix))
axes1.set_xlabel('Hz')
axes1.set_ylabel('SWR')
magnitude = np.absolute(self.gamma())
swr = np.maximum(1.0, np.minimum(100.0, (1.0 + magnitude) / np.maximum(1.0e-20, 1.0 - magnitude)))
axes1.plot(self.xaxis, swr, color = 'blue', label = 'SWR')
self.cursor = datacursor(axes = self.figure.get_axes(), formatter = LabelFormatter(), display = 'multiple')
self.canvas.draw()
开发者ID:Split7fire,项目名称:red-pitaya-notes,代码行数:16,代码来源:vna.py
注:本文中的mpldatacursor.datacursor函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论