本文整理汇总了Python中matplotlib.dates.num2date函数的典型用法代码示例。如果您正苦于以下问题:Python num2date函数的具体用法?Python num2date怎么用?Python num2date使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了num2date函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: update_attributes
def update_attributes(self):
if self.fbfile.data is None:
self.start_text.SetLabel('n/a')
self.end_text.SetLabel('n/a')
else:
self.start_text.SetLabel(num2date(self.data['dn_py'][0]).strftime("%Y-%m-%d %H:%M:%S"))
self.end_text.SetLabel(num2date(self.data['dn_py'][-1]).strftime("%Y-%m-%d %H:%M:%S"))
开发者ID:rustychris,项目名称:freebird,代码行数:7,代码来源:gui.py
示例2: drawGraph
def drawGraph(events,filename):
#determine the number of bins (bars) on the graph by
#splitting the time the data spans by a time interval
#calculate the time spanned by the data
latestReading = num2date(max(events))
earliestReading = num2date(min(events))
dateRange = latestReading - earliestReading
numberOfSeconds = dateRange.seconds + dateRange.days * 24 * 3600
#chop the data up into roughly 20 min intervals (in seconds)
intervalSize = 24*60*60
#calculate how many intervals are there in numberOfSeconds
#round up so there is always at least one
histogramBins = math.ceil(float(numberOfSeconds)/float(intervalSize))
#draw the graph
debug (str(histogramBins)+" histogramBins")
debug (str(numberOfSeconds)+" numberOfSeconds")
debug (str(intervalSize)+" intervalSize")
debug (str(latestReading)+" latestReading")
debug (str(earliestReading)+" earliestReading")
debug (str(dateRange)+" dateRange")
debug (str(intervalSize)+" intervalSize")
fig = plotDatehist(events, histogramBins, "Bird Box 1 Activity", intervalSize)
#save the graph to a file
pyplot.savefig(filename)
开发者ID:NestBoxTech,项目名称:Bird-box-activity-counter,代码行数:30,代码来源:drawgraph.py
示例3: daily_timseries
def daily_timseries( ts ):
fig = Figure( ( 2.56, 2.56 ), 300 )
canvas = FigureCanvas(fig)
ax = fig.add_axes((0,0,1,1))
ax.set_ylim( [ 0 , 500 ] )
preferspan = ax.axhspan( SAFE[0], SAFE[1],
facecolor='g', alpha=0.2,
edgecolor = '#003333',
linewidth=1
)
# XXX: gets a list of days.
timestamps = glucose.get_days( ts.time )
halfday = dates.relativedelta( hours=12 )
soleday = dates.relativedelta( days=1 )
xmin, xmax = ( timestamps[ 0 ], timestamps[ 1 ] + soleday )
ax.set_xlim( [ xmin, xmax ] )
#fig.autofmt_xdate( )
#plot_glucose_stems( ax, ts )
plt.setp(ax.get_xminorticklabels(), visible=False )
plt.setp(ax.get_xmajorticklabels(), visible=False )
plt.setp(ax.get_ymajorticklabels(), visible=False )
plt.setp(ax.get_yminorticklabels(), visible=False )
ax.grid(True)
xmin, xmax = ax.get_xlim( )
log.info( pformat( {
'xlim': [ dates.num2date( xmin ), dates.num2date( xmax ) ],
} ) )
return canvas
开发者ID:bewest,项目名称:diabetes,代码行数:33,代码来源:make_series.py
示例4: on_select_helper
def on_select_helper(self, xmin, xmax):
""" Helper for on_select methods """
# convert matplotlib float dates to a datetime format
date_min = mdates.num2date(xmin)
date_max = mdates.num2date(xmax)
# put the xmin and xmax in datetime format to compare
date_min = datetime.datetime(date_min.year, date_min.month, date_min.day, date_min.hour, date_min.minute)
date_max = datetime.datetime(date_max.year, date_max.month, date_max.day, date_max.hour, date_max.minute)
# find the indices that were selected
indices = np.where((self.dates >= date_min) & (self.dates <= date_max))
indices = indices[0]
# get the selected dates and values
selected_dates = self.dates[indices]
selected_values = self.parameter["data"][indices]
# compute simple stats on selected values
selected_values_mean = nanmean(selected_values)
selected_value_max = np.nanmax(selected_values)
selected_value_min = np.nanmin(selected_values)
return selected_dates, selected_values, selected_values_mean, selected_value_max, selected_value_min
开发者ID:jlant-usgs,项目名称:waterapputils,代码行数:25,代码来源:matplotlibwidget.py
示例5: onselect
def onselect(xmin, xmax):
"""
A select event handler for the matplotlib SpanSelector widget.
Selects a min/max range of the x or y axes for a matplotlib Axes.
"""
# convert matplotlib float dates to a datetime format
date_min = mdates.num2date(xmin)
date_max = mdates.num2date(xmax)
# put the xmin and xmax in datetime format to compare
date_min = datetime.datetime(date_min.year, date_min.month, date_min.day, date_min.hour, date_min.minute)
date_max = datetime.datetime(date_max.year, date_max.month, date_max.day, date_max.hour, date_max.minute)
# find the indices that were selected
indices = np.where((dates >= date_min) & (dates <= date_max))
indices = indices[0]
# set the data in second plot
plot2.set_data(dates[indices], parameter['data'][indices])
# calculate new mean, max, min
param_mean = nanmean(parameter['data'][indices])
param_max = np.nanmax(parameter['data'][indices])
param_min = np.nanmin(parameter['data'][indices])
ax2.set_xlim(dates[indices][0], dates[indices][-1])
ax2.set_ylim(param_min, param_max)
# show text of mean, max, min values on graph; use matplotlib.patch.Patch properies and bbox
text3 = 'mean = %.2f\nmax = %.2f\nmin = %.2f' % (param_mean, param_max, param_min)
ax2_text.set_text(text3)
fig.canvas.draw()
开发者ID:HydroLogic,项目名称:nwispy,代码行数:34,代码来源:nwispygui.py
示例6: format_coord
def format_coord(x, y):
display_coord = current.transData.transform((x, y))
if not self.button_vcursor.isChecked():
inv = other.transData.inverted()
try:
ax_coord = inv.transform(display_coord)
except IndexError:
ax_coord = transformCoord2Log(display_coord, other, current)
if other.get_lines():
unit1 = "(%s)" % self.dictofline[other.get_lines()[0]].unit
else:
return ""
if current.get_lines():
unit2 = "(%s)" % self.dictofline[current.get_lines()[0]].unit
else:
if unit1 == "(Torr)":
return ('{:<} y1%s = {:<}'.format(
*[num2date(x).strftime("%a %d/%m %H:%M:%S"), '{:.3e}'.format(ax_coord[1])])) % unit1
else:
return ('{:<} y1%s = {:<}'.format(
*[num2date(x).strftime("%a %d/%m %H:%M:%S"), '{:.2f}'.format(ax_coord[1])])) % unit1
if unit1 == "(Torr)":
return ('{:<} y1%s = {:<} y2%s = {:<}'.format(
*[num2date(x).strftime("%a %d/%m %H:%M:%S"), '{:.3e}'.format(ax_coord[1]),
'{:.2f}'.format(y)])) % (unit1, unit2)
else:
return ('{:<} y1%s = {:<} y2%s = {:<}'.format(
*[num2date(x).strftime("%a %d/%m %H:%M:%S"), '{:.3e}'.format(ax_coord[1]),
'{:.2f}'.format(y)])) % (unit1, unit2)
else:
self.verticalCursor(x, display_coord)
return ""
开发者ID:CraigLoomis,项目名称:ics_sps_engineering_plotData,代码行数:34,代码来源:graph.py
示例7: __init__
def __init__(self,par,display):
gtk.Menu.__init__(self)
ann = gtk.MenuItem(label=_("Annotate"))
sub_ann = gtk.Menu()
ann.set_submenu(sub_ann)
for (ctx,color) in par.annotations.contexts():
it = gtk.ImageMenuItem("")
img = gtk.Image()
img.set_from_stock(gtk.STOCK_BOLD,gtk.ICON_SIZE_MENU)
it.set_image(img)
it.get_child().set_markup("<span bgcolor=\""+color+"\">"+ctx+"</span>")
it.connect('activate',lambda w,str: par.create_annotation(str),ctx)
sub_ann.append(it)
sub_ann.append(gtk.SeparatorMenuItem())
new_it = gtk.ImageMenuItem(_("New context..."))
new_img = gtk.Image()
new_img.set_from_stock(gtk.STOCK_ADD,gtk.ICON_SIZE_MENU)
new_it.set_image(new_img)
new_it.connect('activate',lambda w: par.create_context())
sub_ann.append(new_it)
self.append(ann)
if display.src.hasCapability("play"):
play_it = gtk.ImageMenuItem(stock_id=gtk.STOCK_MEDIA_PLAY)
(start,end) = par.input_state.selection
play_it.connect('activate',self.play_annotation,
par.get_parent().get_parent(),
display,
num2date(start,UTC()),
num2date(end,UTC()))
self.append(play_it)
开发者ID:hguenther,项目名称:context-annotator,代码行数:30,代码来源:main.py
示例8: _getdata
def _getdata(self,scname,dates):
dates=np.array(dates)
dates=dates[np.argsort(dates)]
try:
dtend=dates[-1]+timedelta(1)
dtstart=dates[0]
except TypeError:
dtend=num2date(dates[-1]+1)
dtstart=num2date(dates[0])
times,Lstar,MLT,MLAT,InvLat,density=get_density_and_time(scname,dtstart,dtend)
# Find the points that are valid in all arrays
validpoints=np.where(-(density.mask+times.mask))
# Remove invalid points from all the arrays
times=times[validpoints]
Lstar=Lstar[validpoints]
MLT=MLT[validpoints]
MLAT=MLAT[validpoints]
InvLat=InvLat[validpoints]
density=density[validpoints]
maxima=np.where(local_maxima(Lstar))[0]
minima=np.where(local_maxima(-Lstar))[0]
segmentbounds=np.insert(maxima,np.searchsorted(maxima,minima),minima)
segmentbounds[-1]-=1
otimes=date2num(times)
return times,Lstar,MLT,MLAT,InvLat,density,segmentbounds
开发者ID:jhaiduce,项目名称:event_specific_density,代码行数:31,代码来源:densitymodels.py
示例9: set_ticks
def set_ticks(self, axis, start, stop, step, minor):
"""Sets ticks from start to stop with stepsize step on the axis.
params:
axis: is a Axis instance on which the ticks should be set.
start: is the limit_min.
stop: is the limit_max,
minor: True if minor ticks should be set, False if major ticks.
"""
if step:
if isinstance(step, datetime.timedelta):
stop_date = mdates.num2date(stop)
start_date = mdates.num2date(start)
range_seconds = (stop_date - start_date).total_seconds()
step_seconds = step.total_seconds()
nr_intervals = int(math.ceil(
float(range_seconds) / float(step_seconds)))
ticks = [mdates.date2num(start_date + x * step)
for x in xrange(nr_intervals)]
else:
step = float(step)
ticks = np.arange(
math.ceil(start / step) * step, stop + step, step)
if ticks[-1] > stop:
ticks = ticks[:-1]
if minor:
major_ticks = set(axis.get_majorticklocs())
minor_ticks = set(ticks)
ticks = sorted(minor_ticks.difference(major_ticks))
axis.set_ticks(ticks, minor)
开发者ID:SharpLu,项目名称:Sympathy-for-data-benchmark,代码行数:29,代码来源:backend.py
示例10: find_LowHighTide_Amplitudes
def find_LowHighTide_Amplitudes(time_array, wl_array, tau=12.42/24., prc=1./24., order=1, plot=False, log=False, datetime_fmt='%d.%m.%Y %H:%M', plot_title="",
axeslabel_fontsize=18., title_fontsize=20., axesvalues_fontsize=18., annotation_fontsize=18., legend_fontsize=18.):
"""
This script should be used with data which has no missing regions. Although it will work with all data, but
may produce inaccuraces. Missing values should be represented by np.nan in wl_array.
time_array - numpy array with datetime objects
wl_array - numpy array with measured values of waterlevel. Must have same lenght as time_array
tau - float, signal period in days
prc - indicates presicion value +- for comparing time diffrerence between found extremums
with tidal_cycle
order - integer for scipy.signal.argrelextrema()
plot - boolean flag to show plot
log - boolean flag to show log
# tidal cycle is aproximately 12h25min. Each timestep is 10 min => tidal cycle is 74.5 timesteps
# therefore, maxima and minima will be filtered in a range of 73 to 76 timesteps from each other
# for safety reasons lets take 720min
"""
if len(time_array) != len(wl_array):
raise ValueError('time and waterlevel arays should have equal lenght.\nGot: len(time)={0}, len(wl)={1}'.format( len(time_array), len(wl_array)))
local_maximums = scipy.signal.argrelextrema(wl_array, np.greater_equal, order=order, mode='clip')[0]
local_minimums = scipy.signal.argrelextrema(wl_array, np.less_equal, order=order, mode='clip')[0]
local_maximums = remove_regions_from_extremums(local_maximums, log=log)
local_minimums = remove_regions_from_extremums(local_minimums, log=log)
errors_high = check_extremums_dt(local_maximums, time_array, tau=tau, prc=prc, log=log)
errors_low = check_extremums_dt(local_minimums, time_array, tau=tau, prc=prc , log=log)
if plot:
with sns.axes_style("whitegrid"):
plot_extremums(time_array, wl_array, local_minimums, local_maximums, time_errors_high=errors_high, time_errors_low=errors_low,
date_xaxis=True, dt=[tau, prc], plot_title=plot_title,
axeslabel_fontsize=axeslabel_fontsize, title_fontsize=title_fontsize, axesvalues_fontsize=axesvalues_fontsize,
annotation_fontsize=annotation_fontsize, legend_fontsize=legend_fontsize)
#####################
# now create list for return....
LOW_TIDE = list()
for v in local_minimums:
t = time_array[v]
w = wl_array[v]
DateTime = datetime.strftime(num2date(t), datetime_fmt)
LOW_TIDE.append([DateTime, w])
HIGH_TIDE = list()
for v in local_maximums:
t = time_array[v]
w = wl_array[v]
DateTime = datetime.strftime(num2date(t), datetime_fmt)
HIGH_TIDE.append([DateTime, w])
return LOW_TIDE, HIGH_TIDE
开发者ID:cdd1969,项目名称:scripts_farge,代码行数:60,代码来源:create_lowhightide_from_hydrograph_+plot_errors.py
示例11: on_click
def on_click(event):
#capture events and button pressed
events.append(event)
if event.button == 1:
l = self.left
elif event.button == 3:
l = self.right
l.set_xdata([event.xdata, event.xdata])
l.figure.canvas.draw()
#get the left slice time data, convert matplotlib num to date
#format date string for the GUI start date field
x1 = self.left.get_xdata()[0]
temp_date = mdates.num2date(x1, tz=pytz.timezone(str(self.tzstringvar.get())))
datestring = temp_date.strftime('%m/%d/%y %H:%M:%S')
self.date1.set(datestring)
#get the left slice time data, convert matplotlib num to date
#format date string for the GUI start date field
x2 = self.right.get_xdata()[0]
temp_date2 = mdates.num2date(x2, tz=pytz.timezone(str(self.tzstringvar.get())))
datestring2 = temp_date2.strftime('%m/%d/%y %H:%M:%S')
self.date2.set(datestring2)
xy = [[x1, 0], [x1, 1], [x2, 1], [x2, 0], [x1, 0]]
#draw yellow highlight over selected area in graph
patch.set_xy(xy)
patch.figure.canvas.draw()
开发者ID:cmazzullo,项目名称:wave-sensor,代码行数:30,代码来源:chopper2.py
示例12: emolt_plotting
def emolt_plotting(yrday,depth,temp,time11,samesites0,ax,k,ave_temp0,rgbcolors):
#"ax" you can do like fig = plt.figure() ; ax = fig.add_subplot(111)
#"k" "samesites0" ,this function should be in "for" loop, for k in range(len(samesites0)):
# except "k", all of them should be a list
#ave_temp0 means every average temperature for every samesites
#rgbcolors is a color box, we select colors from it for plot
temp0,yrday0=[],[]
if temp<>[]:
depth111s=min(depth)
# sorted Temperature by date,time
a=zip(yrday,temp)
b=sorted(a, key=lambda a: a[0])
for e in range(len(temp)):
yrday0.append(b[e][0])
temp0.append(b[e][1])
plt.plot(yrday0,temp0,color=rgbcolors[k],label=samesites0[k]+'(s): -'+str(int(depth111s))+','+str(round(ave_temp0[k],1))+'F',lw = 3)
plt.ylabel('Temperature')
plt.title('temp from '+num2date(min(time11)).strftime("%d-%b-%Y")+' to '+num2date(max(time11)).strftime("%d-%b-%Y"))
plt.legend()
#choose suited unit in x axis
if max(time11)-min(time11)<5:
monthsFmt = DateFormatter('%m-%d\n %H'+'h')
if 5<=max(time11)-min(time11)<366:
monthsFmt = DateFormatter('%m-%d')
if max(time11)-min(time11)>366:
monthsFmt = DateFormatter('%Y-%m')
ax.xaxis.set_major_formatter(monthsFmt)
#ax.set_xlabel(str(num2date(min(time11)).year)+"-"+str(num2date(max(time11)).year),fontsize=17)
#limit x axis length
ax.set_xlabel('Notation:(s) means near the surface of sea')
plt.xlim([min(time11),max(time11)+(max(time11)-min(time11))/2])
plt.savefig('/net/home3/ocn/jmanning/py/huanxin/work/hx/please rename .png')
plt.show()
开发者ID:xhx509,项目名称:catch,代码行数:35,代码来源:getemolt_function.py
示例13: get_12h_intervals
def get_12h_intervals(interval):
my_intervals = list()
for el in interval:
# convert time number to date in order to compare, 43200sec=12hours
if (md.num2date(el[1]) - md.num2date(el[0])).total_seconds() == 43200:
my_intervals.append(el)
return my_intervals
开发者ID:KravitzLab,项目名称:FED,代码行数:7,代码来源:meal_bars.py
示例14: PaceDateGraph
def PaceDateGraph(x_list, y_list, graph_title, graph_xaxis, graph_yaxis):
"""Creates a graph showing the average pace of each run at the same
distance range"""
dates = [mdates.date2num(day) for day in x_list]
#paces = [Hour2Seconds(time) for time in y1_paceList]
fig, ax = plt.subplots()
ax.plot(dates, y_list, '#FAC8CA')
ax.set_title(graph_title)
ax.set_xlabel(graph_xaxis)
ax.set_ylim([(min(y_list)-60), (max(y_list)+60)])
ax.set_ylabel(graph_yaxis)
ax.fill_between(dates, y_list, color='#FCE6E6')
ax.xaxis.set_major_formatter(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%Y'))
dates.append(mdates.date2num(mdates.num2date(min(dates))-timedelta(days=3)))
dates.append(mdates.date2num(mdates.num2date(max(dates))+timedelta(days=3)))
ax.set_xlim([(mdates.num2date(min(dates))), (mdates.num2date(max(dates)))])
# if graph_type == "month":
# ax2.xaxis.set_major_formatter(mdates.DayLocator())
# ax2.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m'))
# elif graph_type == "all":
# dates.append(mdates.date2num(mdates.num2date(min(dates))-timedelta(days=3)))
# dates.append(mdates.date2num(mdates.num2date(max(dates))+timedelta(days=3)))
# ax2.set_xlim([(mdates.num2date(min(dates))), (mdates.num2date(max(dates)))])
plt.show()
开发者ID:callumkift,项目名称:Running-Statistics,代码行数:28,代码来源:running_data.py
示例15: trajectory_point_to_str
def trajectory_point_to_str(data, index, with_address=True):
coords = "%s, %s" % tuple(data[index][1:])
if with_address:
geocoder = Geocoder()
address = geocoder.reverse(coords, exactly_one = True).address
else:
address = None
tz = pytz.timezone('US/Pacific')
date = num2date(data[index][0], tz=tz)
try:
dt = (num2date(data[index+1][0]) - date).total_seconds()
dist = distance(data[index], data[index+1])
v = ms_to_mph*dist/dt if dt!=0 else 0
if dt < 60:
dt_str = "%ds" % dt
elif dt < 60*60:
dt_str = "%dmin" % (dt/60,)
else:
dt_str = "%.1fh" % (dt/60/60,)
metrics = "%s; %.2fm; %.fmph" % (dt_str, dist, v)
except IndexError:
metrics = "NO DATA"
return "Index:%s; Date:%s; Address:%s; Coords: %s; dt,ds,v:%s" % \
(index, date, address, coords, metrics)
开发者ID:driver-pete,项目名称:driver-pete-python-sandbox,代码行数:25,代码来源:gmaps.py
示例16: get_axis
def get_axis( ax, limit ):
xmin, xmax = limit
ax.set_xlim( [ xmin, xmax ] )
ax.grid(True)
#ax.set_ylim( [ ts.value.min( ) *.85 , 600 ] )
#ax.set_xlabel('time')
majorLocator = dates.DayLocator( )
majorFormatter = dates.AutoDateFormatter( majorLocator )
minorLocator = dates.HourLocator( interval=6 )
minorFormatter = dates.AutoDateFormatter( minorLocator )
#ax.xaxis.set_major_locator(majorLocator)
#ax.xaxis.set_major_formatter(majorFormatter)
ax.xaxis.set_minor_locator(minorLocator)
ax.xaxis.set_minor_formatter(minorFormatter)
labels = ax.get_xminorticklabels()
plt.setp(labels, rotation=30, fontsize='small')
plt.setp(ax.get_xmajorticklabels(), rotation=30, fontsize='medium')
xmin, xmax = ax.get_xlim( )
log.info( pformat( {
'xlim': [ dates.num2date( xmin ), dates.num2date( xmax ) ],
'xticks': dates.num2date( ax.get_xticks( ) ),
} ) )
开发者ID:bewest,项目名称:diabetes,代码行数:30,代码来源:make_series.py
示例17: fix_trajectory_timezone
def fix_trajectory_timezone(filename, folder_to_put, change_filename=True):
'''
Add timezone to the trajectory
'''
# http://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/
traj = read_compressed_trajectory(filename, with_timezone=False)
tz = timezone('US/Pacific')
for i in range(traj.shape[0]):
d = num2date(traj[i, 0])
d = d.replace(tzinfo = None)
d = tz.localize(d)
traj[i, 0] = date2num(d)
result_filename = os.path.split(filename)[-1]
if change_filename:
file_date = num2date(date_str_to_num_converter_no_timezone(result_filename))
file_date = file_date.replace(tzinfo = None)
file_date = tz.localize(file_date)
result_filename = num_to_date_str_converter(date2num(file_date), with_timezone=True)
resulting_path = os.path.join(folder_to_put, result_filename)
write_compressed_trajectory(traj, os.path.join(folder_to_put, result_filename), with_timezone=True)
return resulting_path
开发者ID:driver-pete,项目名称:driver-pete-python-sandbox,代码行数:25,代码来源:fix_time_zone.py
示例18: viewlim_to_dt
def viewlim_to_dt(self):
major_ticks = self.axis.get_majorticklocs()
# to deal with non-uniform interval of major_ticks...
#like days on month: [1,8,22,29,1,8,...]
max_major_ticks_interval = max([abs(x2-x1) for (x1, x2) in zip(major_ticks[:-1],major_ticks[1:])])
return ( dates.num2date(major_ticks[0], self.tz),
dates.num2date(major_ticks[0]+max_major_ticks_interval, self.tz) )
开发者ID:ryo1kato,项目名称:timeseriesplot,代码行数:7,代码来源:timeseriesplot.py
示例19: mouseMoved
def mouseMoved(self,evt):
pos = evt[0] ## using signal proxy turns original arguments into a tuple
if self.sceneBoundingRect().contains(pos):
mousePoint = self.plotItem.vb.mapSceneToView(pos)
index = int(mousePoint.x())
xLeft = self.candleData[0,0]
xRight = self.candleData[len(self.candleData)-1,0]
if index > xLeft and index < xRight:
#self.textInfo.setText('[%0.1f, %0.1f]' % (mousePoint.x(), mousePoint.y()))
#self.textInfo.setHtml('<div style="text-align: center"><span style="color: #FFF;">This is the</span><br><span style="color: #FF0; font-size: 16pt;">[%0.1f, %0.1f]</span></div>'% (mousePoint.x(), mousePoint.y()))
a = np.where(self.candleData[:,0]==index)
if(len(a[0])>0):
import matplotlib.dates as mpd
import datetime as dt
date = mpd.num2date(self.candleData[3,0])
strDate = dt.datetime.strftime(date, '%Y-%m-%d')
self.textInfo.setHtml(
'<div style="text-align: center">\
<span style="color: #FFF;">\
Current bar info:\
</span>\
<br>\
<span style="color: #FF0; font-size: 10pt;">\
time:%s\
<br>\
open:%0.3f\
<br>\
high:%0.3f\
<br>\
low:%0.3f\
<br>\
close:%0.3f\
</span>\
</div>'\
% (dt.datetime.strftime(mpd.num2date(self.candleData[a[0][0],0]),'%Y-%m-%d'),
self.candleData[a[0][0],1],
self.candleData[a[0][0],2],
self.candleData[a[0][0],3],
self.candleData[a[0][0],4]))
#date = np.array([mpd.date2num(dt.datetime.strptime(dateStr, '%Y-%m-%d')) )
# 0)get environments
rect = self.sceneBoundingRect()
top = rect.top()
left = rect.left()
bottom = rect.bottom()
width = rect.width()
xAxis = mousePoint.x()
yAxis = mousePoint.y()
# 1)set postions
self.vLine.setPos(xAxis)
self.hLine.setPos(yAxis)
self.textInfo.setPos(xAxis,yAxis)
开发者ID:UpSea,项目名称:ZipLineMid,代码行数:59,代码来源:test02.py
示例20: giant_timeseries
def giant_timeseries( ts ):
fig = Figure( ( 20.3, 3.5 ), 300 )
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
preferspan = ax.axhspan( SAFE[0], SAFE[1],
facecolor='g', alpha=0.35,
edgecolor = '#003333',
linewidth=1
)
# visualize glucose using stems
# XXX: gets a list of days.
timestamps = glucose.get_days( ts.time )
delta = dates.relativedelta( days=1, hours=12 )
oneday = dates.relativedelta( days=1 )
xmin, xmax = ( timestamps[ 0 ], timestamps[ -1 ] )
ax.set_xlim( [ xmin, xmax ] )
markers, stems, baselines = ax.stem( ts.time, ts.value,
linefmt='b:' )
plt.setp( markers, color='red', linewidth=.5,
marker='o'
)
plt.setp( baselines, marker='None' )
fig.autofmt_xdate( )
ax.set_title('glucose history')
ax.grid(True)
ax.set_xlabel('time')
majorLocator = dates.DayLocator( )
majorFormatter = dates.AutoDateFormatter( majorLocator )
minorLocator = dates.HourLocator( interval=6 )
minorFormatter = dates.AutoDateFormatter( minorLocator )
ax.xaxis.set_major_locator(majorLocator)
ax.xaxis.set_major_formatter(majorFormatter)
ax.xaxis.set_minor_locator(minorLocator)
ax.xaxis.set_minor_formatter(minorFormatter)
labels = ax.get_xminorticklabels()
plt.setp(labels, rotation=30, fontsize='small')
plt.setp(ax.get_xmajorticklabels(), rotation=30, fontsize='medium')
xmin, xmax = ax.get_xlim( )
log.info( pformat( {
'xlim': [ dates.num2date( xmin ), dates.num2date( xmax ) ],
} ) )
ax.set_ylabel('glucose mm/dL')
return canvas
开发者ID:bewest,项目名称:diabetes,代码行数:59,代码来源:make_series.py
注:本文中的matplotlib.dates.num2date函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论