本文整理汇总了Python中matplotlib.dates.epoch2num函数的典型用法代码示例。如果您正苦于以下问题:Python epoch2num函数的具体用法?Python epoch2num怎么用?Python epoch2num使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了epoch2num函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: plot_dataset
def plot_dataset(self, name=None, ax=None):
"""Function to plot data for a specified Data Center."""
values = []
times = []
max_value = 0
max_value_time = 0
for record in self.dataset[:]:
if record[0] == name:
times.append(dt.epoch2num(record[1]))
values.append(record[2])
if record[2] > max_value:
max_value = record[2]
max_value_time = dt.epoch2num(record[1])
self.dataset.remove(record)
else:
pass
value_mean = sum(values) / float(len(values))
print(
"Data Center:{}\nMax Value:{}, {}\nAverage Value:{}\n".format(
name, max_value, dt.num2date(max_value_time), value_mean
)
)
ax.plot_date(times, values, xdate=True)
开发者ID:DanielStreb1992,项目名称:ConversantCodingExercise,代码行数:26,代码来源:DatasetDisplay.py
示例2: set_signals
def set_signals(self, allSignals):
timestamp = time.time()
if timestamp - self._timestamp > self._delayDraw:
t1 = time.time()
self._timestamp = timestamp
height = SAMPLE_RATE / BINS
height /= 1e6
self._axes.set_color_cycle(None)
self.__clear_plots()
for freq, signals in allSignals:
barsX = []
for start, end, _level in signals:
tStart = epoch2num(start)
tEnd = epoch2num(end)
barsX.append([tStart, tEnd - tStart])
colour = self._axes._get_lines.color_cycle.next()
self._axes.broken_barh(barsX, [freq - height / 2, height],
color=colour,
gid='plot')
self._axes.axhspan(freq, freq, color=colour)
self._axes.get_figure().autofmt_xdate()
self._axes.relim()
self._canvas.draw()
delay = time.time() - t1
self._delayDraw += delay * 2.
self._delayDraw /= 2.
if self._delayDraw < 1. / MAX_TIMELINE_FPS:
self._delayDraw = 1. / MAX_TIMELINE_FPS
开发者ID:mvdroest,项目名称:RF-Monitor,代码行数:32,代码来源:dialog_timeline.py
示例3: extract_daily_interaction
def extract_daily_interaction(interaction):
tweets_per_day = defaultdict(int)
days = [mdates.epoch2num(long(el - el%SEC_IN_DAY)) for el in interaction]
days = set(days)
for day in days:
tweets_per_day[day] = sum(1 for el in interaction if mdates.epoch2num(long(el - el%SEC_IN_DAY)) == day)
return tweets_per_day
开发者ID:sanja7s,项目名称:SR_Twitter,代码行数:7,代码来源:graph.py
示例4: try_to_draw_vms_cache_refresh_lines
def try_to_draw_vms_cache_refresh_lines():
if(isNetflixInternal()):
try:
fp = open(vmsGCReportDirectory + os.path.sep + 'vms-cache-refresh-overall-events-milliseconds')
except IOError:
return
for line in fp:
line = line.rstrip('\r\n')
try:
(finish_time_ms_str, duration_ms_str) = line.split()
except ValueError:
continue
finish_time_ms = long(finish_time_ms_str)
duration_ms = long(duration_ms_str)
start_time_ms = finish_time_ms - duration_ms
start_time_secs = start_time_ms/1000.0
start_time_days = mdates.epoch2num(start_time_secs)
start_time_line = lines.Line2D([start_time_days,start_time_days], [0,maxGCEventDuration], color='r')
ax.add_line(start_time_line)
finish_time_secs = finish_time_ms/1000.0
finish_time_days = mdates.epoch2num(finish_time_secs)
finish_time_line = lines.Line2D([finish_time_days,finish_time_days], [0,maxGCEventDuration], color='c')
ax.add_line(finish_time_line)
fp.close()
# draw some fake lines just to get them into the legend
fake_vms_start_line = lines.Line2D([jvmBootDays,0], [jvmBootDays,0], label='VMS cache refresh start', color='r')
fake_vms_end_line = lines.Line2D([jvmBootDays,0], [jvmBootDays,0], label='VMS cache refresh end', color='c')
ax.add_line(fake_vms_start_line)
ax.add_line(fake_vms_end_line)
开发者ID:Netflix,项目名称:gcviz,代码行数:29,代码来源:visualize-gc.py
示例5: Print_Packet_Details
def Print_Packet_Details(decoded,SrcPort,DstPort,ts2):
if timestamp:
ts = '[%f] ' % time.time()
else:
ts = ''
#print decoded['data']
if "RCPT TO:" in decoded['data']:
try:
mail_try[decoded['source_address'],int(mp.epoch2num(ts2))] += 1
except:
mail_try[decoded['source_address'],int(mp.epoch2num(ts2))] = 1
try:
match = re.search(r"[a-zA-Z0-9_.+-][email protected][a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+", decoded['data'])
return '%sprotocol: %s %s:%s > %s:%s %s RCPT TO: %s' % (ts, protocols[decoded['protocol']],decoded['source_address'],SrcPort,decoded['destination_address'], DstPort, str(datetime.datetime.utcfromtimestamp(ts2)), match.group())
except:
return '%s%s:%s > %s:%s %s RCPT TO: %s' % (ts,decoded['source_address'],SrcPort,decoded['destination_address'], DstPort, str(datetime.datetime.utcfromtimestamp(ts2)), match.group())
if "MAIL FROM:" in decoded['data']:
try:
match = re.search(r"[a-zA-Z0-9_.+-][email protected][a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+", decoded['data'])
return '%sprotocol: %s %s:%s > %s:%s %s MAIL FROM: %s' % (ts, protocols[decoded['protocol']],decoded['source_address'],SrcPort,decoded['destination_address'], DstPort, str(datetime.datetime.utcfromtimestamp(ts2)), match.group())
except:
return '%s%s:%s > %s:%s %s MAIL FROM: %s' % (ts,decoded['source_address'],SrcPort,decoded['destination_address'], DstPort, str(datetime.datetime.utcfromtimestamp(ts2)), match.group())
if "From: " in decoded['data']:
try:
match = re.findall(r"[a-zA-Z0-9_.+-][email protected][a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+", decoded['data'])
return '%sprotocol: %s %s:%s > %s:%s %s mail body from / to: %s - %s' % (ts, protocols[decoded['protocol']],decoded['source_address'],SrcPort,decoded['destination_address'], DstPort, str(datetime.datetime.utcfromtimestamp(ts2)), match[0], match[1])
except:
return '%s%s:%s > %s:%s %s mail body from / to: %s - %s' % (ts,decoded['source_address'],SrcPort,decoded['destination_address'], DstPort, str(datetime.datetime.utcfromtimestamp(ts2)), match[0], match[1])
return " "
开发者ID:bstelte,项目名称:investigate,代码行数:29,代码来源:find-smtp.py
示例6: trades
def trades(timeSince): # gets the innermost bid and asks and information on the most recent trade.
adjustedTime = int(time.time()) - timeSince
response = requests.get(URL + str(adjustedTime))
splitResponse = response.text.splitlines()
prices = []
timestamps = []
amounts = []
mymax = 0
#Only keep one of each 30 lines
splitResponse = splitResponse[::30]
for i,line in enumerate(splitResponse):
splitline = splitResponse[i].split(',')
timestamp = splitline[0]
price = round(float(splitline[1]),2)
amount = splitline[2]
#print "amount: " + str(amount)
if mymax < amount:
mymax = amount
timestamps.append(float(timestamp))
print "\nEvent at time: ",mdates.epoch2num(float(timestamp))
prices.append(float(price))
amounts.append(float(amount)*5 )
fig = plt.figure()
#ax1 = plt.subplot(2,1,1)
ax1 = plt.subplot2grid((5,4), (0,0), rowspan=4, colspan=4)
secs = mdates.epoch2num(timestamps)
ax1.plot_date(secs, prices, 'k-', linewidth=.7)
ax1.grid(True)
plt.xlabel('Date')
plt.ylabel('Bitcoin Price')
#ax2 = plt.subplot(2,1,2, sharex=ax1)
ax2 = plt.subplot2grid((5,4), (4,0), sharex=ax1, rowspan=1, colspan=4)
ax2.plot(secs, amounts)
ax2.grid(True)
plt.ylabel('Volume')
#Use a DateFormatter to set the data to the correct format.
#Choose your xtick format string
#date_fmt = '%d-%m-%y %H:%M:%S'
date_fmt = '%d-%m-%y %H:%M'
date_formatter = mdates.DateFormatter(date_fmt)
ax1.xaxis.set_major_formatter(date_formatter)
#Tilt x-axis text to fit
fig.autofmt_xdate()
plt.show()
开发者ID:Jackson-Bahm,项目名称:bitfinex,代码行数:52,代码来源:basicGraph.py
示例7: candlestick_chart
def candlestick_chart(self, time_series, interval=40, show=False, filename='candlestick.png', volume_overlay=None):
tz = get_localzone()
adjusted_time_series = []
for item in time_series:
item[0] = epoch2num(item[0])
adjusted_time_series.append(item)
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
ax.xaxis.set_major_formatter(self._date_formatter(interval, tz=tz))
days_interval = interval / 86400.0
candlestick_ochl(ax, adjusted_time_series, width=(days_interval), colorup='green', colordown='red', alpha=0.9)
ax.xaxis_date(tz=tz.zone)
ax.autoscale_view()
yticks = ax.get_yticks()
x_start = min(yticks) - ((max(yticks) - min(yticks)) * 0.60)
plt.ylim([x_start,max(yticks)])
ax.grid(True)
plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
if volume_overlay != None:
# Add a seconds axis for the volume overlay
ax2 = ax.twinx()
yticks = ax.get_yticks()
print('yticks', yticks)
# set the position of ax2 so that it is short (y2=0.32) but otherwise the same size as ax
ax2.set_position(matplotlib.transforms.Bbox([[0.125,0.2],[0.9,0.42]]))
#print(days_interval * len(adjusted_time_series))
#ax2.set_position([0.125, 0.2, 0.8, 0.2])
# get data from candlesticks for a bar plot
dates = [x[0] for x in adjusted_time_series]
dates = np.asarray(dates)
volume = [x[1] for x in volume_overlay]
volume = np.asarray(volume)
ax2.bar(dates,volume,color='#aaaaaa',width=(days_interval),align='center',linewidth=0.0,alpha=0.8)
#scale the x-axis tight
#ax2.set_xlim(min(dates),max(dates))
# the y-ticks for the bar were too dense, keep only every third one
ax2yticks = ax2.get_yticks()
#print('yticks', ax2yticks)
#print('yticks2', ax2yticks[::3])
ax2.set_yticks(ax2yticks[::3])
ax2.yaxis.set_label_position("right")
ax2.set_ylabel('Volume', size=20)
# format the x-ticks with a human-readable date.
#xt = ax.get_xticks()
#new_xticks = [datetime.date.isoformat(num2date(d)) for d in xt]
#ax.set_xticklabels(new_xticks,rotation=45, horizontalalignment='right')
if show:
plt.show()
else:
plt.savefig(const.DATA_DIR + '/' + filename, bbox_inches='tight')
plt.close()
开发者ID:dominiek,项目名称:etherist,代码行数:60,代码来源:visualize.py
示例8: graph_animate
def graph_animate(i):
read_file = open('mcxlist.txt', 'r')
sep_file = read_file.read().split('\n')
x = []
y = []
for pair in sep_file:
XY = pair.split(' ')
if len(XY) > 1:
x.append(float(XY[0]))
y.append(float(XY[1]))
ax1.clear()
x = np.array(x)
y = np.array(y)
read_file.close()
#rotates timestamps
plt.setp(plt.xticks()[1], rotation=30)
#shows grid
ax1.grid(b=True, which='major', color='r')
plt.title('CFS Betagraph V0.0.1', color='w')
#plt x, and y cords
ax1.plot_date(md.epoch2num(x), y,'r',tz=est,linewidth=2,xdate=True,marker='o')
开发者ID:cfsip,项目名称:CFGraph,代码行数:26,代码来源:mcxgraph.py
示例9: histogram_data
def histogram_data(self, resolution = 'month', combined = True, start = None, stop = None):
s_date = start if start else self.start_date()
e_date = stop if stop else self.end_date()
s, e = self.search_date_range(s_date, e_date)
flat_messages = {}
if combined:
flat_messages = {'Combined':[timestamp(x[0].date()) for x in self._sms_history[s:e]]}
else:
for participant in self.participants + ['Me']:
flat_messages[participant] = [timestamp(x[0].date()) for x in self._sms_history[s:e] if x[1][1] == participant]
plt_data = []
for history in flat_messages.items():
label = history[0]
mpl_data = mdates.epoch2num(history[1])
plt_data += [(label, mpl_data)]
elapsed_time = e_date - s_date
if resolution == 'day':
num_buckets = elapsed_time.days
elif resolution == 'year':
num_buckets = int(elapsed_time.days / 365) + 1
else:
num_buckets = int(elapsed_time.days / 30) + 1
data_sets = []
for person in plt_data:
y, bin_edges = np.histogram(person[1], bins = num_buckets)
bin_centers = 0.5*(bin_edges[1:]+bin_edges[:-1])
data_sets.append((person[0], y, bin_centers))
return data_sets
开发者ID:rexkirshner,项目名称:text-analyzer,代码行数:34,代码来源:smsanalyzer.py
示例10: doplot
def doplot(series):
"""
Do the actual plotting of the series
Needs data with the given dtypes to be able to address the
'date', 'humidity', 'temperature' columns
"""
fig = pl.figure(figsize=(11.27, 8.69))
dates = [num2date(epoch2num(s[0]['date']), tz) for s in series]
ax1 = fig.add_subplot(211)
for i, s in enumerate(series):
ax1.plot_date(dates[i], s[0]['humidity'], '-', label=s[1])
ax1.set_ylabel("Humidity (%)")
ax1.legend(loc='best')
fig.autofmt_xdate()
ax2 = fig.add_subplot(212)
signs = ['s', 'x', 'o']
for i, s in enumerate(series):
ax2.plot_date(dates[i], s[0]['temperature'], signs[i % len(signs)], label=s[1])
ax2.set_ylabel("Temperature (C)")
ax2.legend(loc='best')
fig.autofmt_xdate()
ax1.set_title("%s -> %s" %(dates[0][0], dates[0][-1]))
开发者ID:UltracoldAtomsLab,项目名称:weatherreport,代码行数:25,代码来源:compare.py
示例11: info
def info(self): # General info of the data
f_name = self.filename
st = self.data['ST']
et = self.data['ET']
d_format = '%H:%M:%S'
# start date and time formatting
s_day = epoch2num(st) # num of days since epoch
s_date = datetime.date.fromordinal(s_day) # returns formatted date YYYY-MM-DD
s_time = time.gmtime(st) # returns struct_time of date and time values
e_time = time.gmtime(et)
# Range in seconds
st_sec = s_time.tm_hour * 3600 + s_time.tm_min * 60 + s_time.tm_sec
et_sec = e_time.tm_hour * 3600 + e_time.tm_min * 60 + e_time.tm_sec
dsec = et_sec - st_sec
start_str = time.strftime(d_format, s_time)
end_str = time.strftime(d_format, e_time)
info_d = {'Filename': f_name, 'Date': s_date, 'Start': start_str, 'End': end_str, 'dt': dsec}
'''
print('Filename: ', f_name)
print('Date: ', s_date, ', epoch[day]: ', s_day[0])
print('GMT:')
print('Start Time : ', time.strftime(d_format, s_time), ', End Time: ', time.strftime(d_format, e_time))
'''
return info_d
开发者ID:eanunez,项目名称:pyscripts,代码行数:29,代码来源:plt_filter.py
示例12: saveGraph
def saveGraph(f):
if f != "null":
matfirstbeat = mdates.epoch2num(firstbeat.keys())
plt.plot_date(matfirstbeat, firstbeat.values(), 'bs', linewidth=0.25, label='firstbeat heartrate')
matstressapp = mdates.epoch2num(stress.keys())
matbasispeak = mdates.epoch2num(basispeak.keys())
plt.plot_date(matbasispeak, basispeak.values(), 'gs', linewidth=0.25, label='Basis Peak Heartrate')
plt.plot_date(matstressapp, stress.values(), 'ro', linewidth=3.0, label='stress app annotation heartrate')
plt.xlabel('Date')
plt.ylabel('Heartrate')
plt.title('Subject %s' % subjectnum)
plt.ylim([-5, 200])
plt.legend()
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.savefig('C:/Users/jfzabalx/Pictures/Stress_Study_Heartrate/{0}.png'.format(subjectnum))
plt.close()
开发者ID:Julianxzabala,项目名称:Python-Scripts,代码行数:18,代码来源:AnalyzeAndGraph.py
示例13: transform_date
def transform_date(self, inputdate):
"""Parameters:
inputdate: Unix time - int representing number of seconds from Epoch
Returns date in matplotlib date format, that is float number of days since 0001
"""
return mdates.epoch2num(inputdate)
开发者ID:adantra,项目名称:pymta,代码行数:9,代码来源:plotting.py
示例14: divide_fit
def divide_fit(X, y, ax):
n = len(X)
X1 = X[: n/2]
X2 = X[n/2:]
y1 = y[: n/2]
y2 = y[n/2:]
lr1 = linear_model.LinearRegression()
lr1.fit(X1, y1)
if lr1.coef_ < 0:
divide_fit(X1, y1, ax)
else:
X_ts_track1 = mdate.epoch2num(np.array(X1) / 1000)
ax.plot_date(X_ts_track1, lr1.predict(np.array(X1).reshape(-1, 1))[:], marker='o', ms=1, c='red')
lr2 = linear_model.LinearRegression()
lr2.fit(X2, y2)
if lr2.coef_ < 0:
divide_fit(X2, y2, ax)
else:
X_ts_track2 = mdate.epoch2num(np.array(X2)/1000)
ax.plot_date(X_ts_track2, lr2.predict(np.array(X2).reshape(-1, 1))[:], marker='o', ms=1, c='red')
开发者ID:avalanchesiqi,项目名称:yt-longevity,代码行数:20,代码来源:plot_rate_ts_value2.py
示例15: _dt_to_float_ordinal
def _dt_to_float_ordinal(dt):
"""
Convert :mod:`datetime` to the Gregorian date as UTC float days,
preserving hours, minutes, seconds and microseconds. Return value
is a :func:`float`.
"""
if isinstance(dt, (np.ndarray, Series)) and com.is_datetime64_ns_dtype(dt):
base = dates.epoch2num(dt.asi8 / 1.0E9)
else:
base = dates.date2num(dt)
return base
开发者ID:Acanthostega,项目名称:pandas,代码行数:11,代码来源:converter.py
示例16: hero_per_month
def hero_per_month(player_id, hero_id):
hist = Player(player_id).stat_func('matches', hero_id=hero_id)
hist = hist[::-1]
time = hist[0]['start_time']
quantity = []
kk = 0
m = 0
q = 0
month = []
for i in hist:
if i['start_time'] < time:
try:
if i['hero_id'] == hero_id:
q += 1
kk += 1
except:
pass
else:
time += 2592000
quantity.append(q)
month.append(time)
q = 0
m += 1
plt.xkcd()
plt.gca().cla()
plt.title('number of games played as {} per month'.format(hero_dic[hero_id]))
y = quantity
secs = mdates.epoch2num(month)
ax = plt.gca()
years = mdates.YearLocator() # every year
yearsFmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
tick = 5 if max(y) > 20 else 1
yint = range(min(y), math.ceil(max(y))+2, tick) # set only int ticks
plt.yticks(yint)
plt.plot(secs, y, color='blue')
plt.savefig('images/graphs/hero.png')
return "{} games".format(kk)
开发者ID:Maartenvm,项目名称:dota2-discord-bot,代码行数:54,代码来源:hero_graph.py
示例17: _plot_dateplot
def _plot_dateplot(self, data):
""" Make the date plot """
# Rotate datemarks on xaxis
self.ax1.set_xticklabels([], rotation=25, horizontalalignment='right')
# Left axis
for dat in data['left']:
# Form legend
if dat['lgs'].has_key('legend'):
legend = dat['lgs']['legend']
else:
legend = None
# Plot
if len(dat['data']) > 0:
self.ax1.plot_date(mdates.epoch2num(dat['data'][:,0]),
dat['data'][:,1],
label=legend,
xdate=True,
color=self.c.get_color(),
tz=self.tz,
fmt='-')
# Right axis
for dat in data['right']:
# Form legend
if dat['lgs'].has_key('legend'):
legend = dat['lgs']['legend']
else:
legend = None
# Plot
if len(dat['data']) > 0:
self.ax2.plot_date(mdates.epoch2num(dat['data'][:,0]),
dat['data'][:,1],
label=legend,
xdate=True,
color=self.c.get_color(),
tz=self.tz,
fmt='-')
# No data
if self.measurement_count == 0:
y = 0.00032 if self.o['left_logscale'] is True else 0.5
self.ax1.text(0.5, y, 'No data', horizontalalignment='center',
verticalalignment='center', color='red', size=60)
开发者ID:CINF,项目名称:DataPresentationWebsite,代码行数:41,代码来源:ourmatplotlib.py
示例18: plot
def plot(self, output):
fig, ax = self.logplot
x = dates.epoch2num(self.time_axis)
ax.cla()
ax.plot_date(x, self.total_duration, 'b-')
ax.plot_date(x, self.total_duration_average, 'r-')
ax.xaxis.set_major_formatter(self.dateformatter)
ax.set_ylabel('Temps de parcours (min)')
ax.set_ylim(np.nanmin(self.total_duration)-2., np.nanmax(self.total_duration)+2.)
fig.autofmt_xdate()
fig.tight_layout()
fig.savefig( output, format='png' )
开发者ID:NS2LPS,项目名称:sytadin,代码行数:12,代码来源:webapp.py
示例19: read_dates
def read_dates(limit, stream=sys.stdin):
"""
Read newline-separated unix time from stream
"""
dates = []
for line in stream:
num = epoch2num(float(line.strip()))
dates.append(num)
if num < limit:
break
stream.close()
return dates
开发者ID:padenot,项目名称:FOSDEM-14,代码行数:12,代码来源:datehist.py
示例20: draw_charts
def draw_charts(i):
a.clear()
#Formatowanie wykresu
secs = mdate.epoch2num(time_list)
date_fmt = '%d-%m-%y %H:%M:%S'
date_formatter = mdate.DateFormatter(date_fmt)
a.xaxis.set_major_formatter(date_formatter)
f.autofmt_xdate()
#Pobranie typu i informacji o nim
chart_type = choose_type(actual_chart_type)
#Ustawienia etykiet
a.set_ylabel(chart_type[0], color=chart_type[2])
#Rysowanie wykresow
a.plot_date(secs,chart_type[1], linestyle='-', color=chart_type[2])
开发者ID:xxxnoxisxxx,项目名称:PITE-fly_recorder,代码行数:14,代码来源:black_box.py
注:本文中的matplotlib.dates.epoch2num函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论