本文整理汇总了Python中matplotlib.dates.drange函数的典型用法代码示例。如果您正苦于以下问题:Python drange函数的具体用法?Python drange怎么用?Python drange使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了drange函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_drange
def test_drange():
"""
This test should check if drange works as expected, and if all the
rounding errors are fixed
"""
start = datetime.datetime(2011, 1, 1, tzinfo=mdates.UTC)
end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)
delta = datetime.timedelta(hours=1)
# We expect 24 values in drange(start, end, delta), because drange returns
# dates from an half open interval [start, end)
assert_equal(24, len(mdates.drange(start, end, delta)))
# if end is a little bit later, we expect the range to contain one element
# more
end = end + datetime.timedelta(microseconds=1)
assert_equal(25, len(mdates.drange(start, end, delta)))
# reset end
end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)
# and tst drange with "complicated" floats:
# 4 hours = 1/6 day, this is an "dangerous" float
delta = datetime.timedelta(hours=4)
daterange = mdates.drange(start, end, delta)
assert_equal(6, len(daterange))
assert_equal(mdates.num2date(daterange[-1]), end - delta)
示例2: run
def run(self):
""" start ECG plotting """
while not self.stopPlotThread.isSet():
self.parentFrame.ecgplotter.plot()
# check if the thread has been stopped. if yes, no need to update endtime.
if not self.stopPlotThread.isSet():
self.parentFrame.ecgplotter.endtime += datetime.timedelta(seconds=15)
# initialize the time size (nagiiba kase after every 15 seconds. needs to be extended
self.parentFrame.ecgplotter.timeaxis = num2date(
drange(
self.parentFrame.ecgplotter.starttime,
self.parentFrame.ecgplotter.endtime,
datetime.timedelta(milliseconds=10),
)
)
else:
break
# add slider at the end of plotting only
self.parentFrame.ecgplotter.addSlider(self.parentFrame.ecgplotter.endtime)
self.parentFrame.ecgplotter.canvas.draw()
self.parentFrame.ecgplotter.gui_repaint()
示例3: generate_graph
def generate_graph():
date1 = datetime.datetime( 2000, 3, 2)
date2 = datetime.datetime( 2000, 3, 6)
delta = datetime.timedelta(hours=6)
dates = drange(date1, date2, delta)
y = arange( len(dates)*1.0)
fig, ax = pyplot.subplots()
ax.plot_date(dates, y*y)
ax.set_xlim( dates[0], dates[-1] )
ax.xaxis.set_major_locator( DayLocator() )
ax.xaxis.set_minor_locator( HourLocator(arange(0,25,6)) )
ax.xaxis.set_major_formatter( DateFormatter('%Y-%m-%d') )
ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S')
fig.autofmt_xdate()
file_name = str(generate_uuid()) + '.png'
complete_file_name = GRAPHS_FOLDER + '/' + file_name
logger.debug ("Generando grafico: " + file_name)
pyplot.savefig( complete_file_name )
#pyplot.show()
return [file_name,complete_file_name]
示例4: initPlot
def initPlot(self):
""" redraw the canvas to set the initial x and y axes when plotting starts """
self.starttime = datetime.datetime.today()
self.currenttime = self.starttime + datetime.timedelta(seconds=3)
self.endtime = self.starttime + datetime.timedelta(seconds=15)
self.timeaxis = num2date(drange(self.starttime, self.endtime, datetime.timedelta(milliseconds=10)))
self.xvalues.append(self.timeaxis[0])
self.yvalues.append(self.parentPanel.myECG.ecg_leadII[0])
# for counter purposes only
self.ybuffer = self.yvalues
self.lines[0].set_data(self.xvalues, self.yvalues)
self.axes.set_xlim((date2num(self.starttime), date2num(self.currenttime)))
self.axes.xaxis.set_ticklabels(
self.createXTickLabels(self.currenttime), rotation=30, ha="right", size="smaller", name="Calibri"
)
self.samples_counter += 1
self.ysamples_counter += 1
self.buff_counter = 1
示例5: plot_samples
def plot_samples(sc, basedir, idx=None):
res = 15
t_day_start = sc.t_block_start - timedelta(hours=sc.t_block_start.hour,
minutes=sc.t_block_start.minute)
skip = (t_day_start - sc.t_start).total_seconds() / 60 / res
i_block_start = (sc.t_block_start - t_day_start).total_seconds() / 60 / res
i_block_end = (sc.t_block_end - t_day_start).total_seconds() / 60 / res
t = drange(sc.t_block_start, sc.t_block_end, timedelta(minutes=res))
unctrl = load(p(basedir, sc.run_unctrl_datafile))
P_el_unctrl = unctrl[:,0,skip + i_block_start:skip + i_block_end].sum(0)
sample_data = load(p(basedir, sc.run_pre_samplesfile))
if idx is not None:
sample_data = sample_data[idx].reshape((1,) + sample_data.shape[1:])
fig, ax = plt.subplots(len(sample_data))
if len(sample_data) == 1:
ax = [ax]
for i, samples in enumerate(sample_data):
# t = np.arange(samples.shape[-1])
# ax[i].plot(t, P_el_unctrl, ls=':')
l_unctrl, = ax[i].plot_date(t, P_el_unctrl, fmt=':', color=PRIMB, drawstyle='steps-post', lw=0.75)
l_unctrl.set_dashes([1.0, 1.0])
for s in samples:
ax[i].plot_date(t, s, fmt='-', drawstyle='steps-post', lw=0.75)
fig.autofmt_xdate()
示例6: draw
def draw():
from matplotlib.dates import DayLocator, HourLocator,MonthLocator ,WeekdayLocator, DateFormatter, drange
from matplotlib.dates import MONDAY
import datetime
mondays = WeekdayLocator()
days = DayLocator(None, 3)
months = MonthLocator()
yList = [0]*55
yList[0] = 0.11; yList[1] = 0.109; yList[2] = 0.108;yList[3] = 0.11; yList[4] = 0.111; yList[5] = 0.109; yList[6] = 0.111; yList[7] = 0.109; yList[8] = 0.108; yList[9] = 0.111; yList[10] = 0.112
figure, axes = plt.subplots()
startDate = datetime.datetime(2014, 3, 6, 0, 0, 0)
endDate = datetime.datetime(2014, 4, 30, 0, 0, 0)
delta = datetime.timedelta(hours=24)
dates = drange(startDate , endDate, delta)
axes.plot_date(dates, yList, '-', marker='.', linewidth=1)
axes.xaxis.set_major_locator(days)
axes.xaxis.set_major_formatter( DateFormatter("%b '%d"))
axes.xaxis.set_minor_locator(mondays)
axes.fmt_xdata = DateFormatter("%b '%d")
plt.ylim(0.08,0.20)
plt.ylabel('播放率')
axes.autoscale_view()
axes.xaxis.grid(True, 'major')
axes.xaxis.grid(True, 'minor')
axes.grid(True)
figure.autofmt_xdate()
plt.show()
示例7: plot
def plot(context, spills=False, filename=None, showlegend=True):
"""Produce a pretty plot of supply and demand."""
spill = context.spill
# aggregate demand
demand = context.demand.sum(axis=0)
plt.ylabel('Power (MW)')
title = 'Supply/demand balance\nRegions: %s' % context.regions
plt.suptitle(title)
if showlegend:
_legend(context)
xdata = mdates.drange(context.startdate,
context.startdate + dt.timedelta(hours=context.hours),
dt.timedelta(hours=1))
# Plot demand first.
plt.plot(xdata, demand, color='black', linewidth=2)
if spills:
peakdemand = np.empty_like(demand)
peakdemand.fill(demand.max())
plt.plot(xdata, peakdemand, color='black', linestyle='dashed')
accum = np.zeros(context.timesteps)
prev = accum.copy()
for g in _generator_list(context):
idx = context.generators.index(g)
accum += context.generation[idx]
# Ensure total generation does not exceed demand in any timestep.
assert(np.round(accum, 6) > np.round(demand, 6)).sum() == 0
plt.plot(xdata, accum, color='black', linewidth=0.5)
plt.fill_between(xdata, prev, accum, facecolor=g.patch.get_fc())
prev = accum.copy()
# Unmet demand is shaded red.
plt.fill_between(xdata, accum, demand, facecolor='red')
if spills:
prev = demand.copy()
for g in [g for g in context.generators if g.region() in context.regions]:
idx = context.generators.index(g)
accum += spill[idx]
plt.plot(xdata, accum, color='black')
plt.fill_between(xdata, prev, accum, facecolor=g.patch.get_fc(), alpha=0.3)
prev = accum.copy()
plt.gca().xaxis_date()
plt.gcf().autofmt_xdate()
for hr in np.argwhere(context.unserved):
unserved_dt = context.startdate + dt.timedelta(hours=hr[0])
xvalue = mdates.date2num(unserved_dt)
_, ymax = plt.gca().get_ylim()
plt.plot([xvalue], [ymax - 200], "yv", markersize=15, color='red')
if not filename:
plt.show() # pragma: no cover
else:
plt.savefig(filename)
示例8: plot_aggregated
def plot_aggregated(sc, bd, unctrl, ctrl, ctrl_sched, res=1):
t_day_start = sc.t_block_start - timedelta(hours=sc.t_block_start.hour,
minutes=sc.t_block_start.minute)
t = drange(t_day_start, sc.t_end, timedelta(minutes=res))
skip = (t_day_start - sc.t_start).total_seconds() / 60 / res
i_block_start = (sc.t_block_start - t_day_start).total_seconds() / 60 / res
i_block_end = (sc.t_block_end - t_day_start).total_seconds() / 60 / res
P_el_unctrl = unctrl[:,0,skip:].sum(0)
P_el_ctrl = ctrl[:,0,skip:].sum(0)
P_el_sched = ctrl_sched[:,skip:].sum(0)
T_storage_ctrl = ctrl[:,2,skip:]
ft = np.array([t[0]] + list(np.repeat(t[1:-1], 2)) + [t[-1]])
P_el_ctrl_fill = np.repeat(P_el_ctrl[:-1], 2)
fig, ax = plt.subplots(2, sharex=True)
fig.subplots_adjust(left=0.11, right=0.95, hspace=0.3, top=0.98, bottom=0.2)
ax[0].set_ylabel('P$_{\mathrm{el}}$ [kW]')
ymax = max(P_el_unctrl.max(), P_el_ctrl_fill.max(), P_el_sched.max(), 0) / 1000.0
ymin = min(P_el_unctrl.min(), P_el_ctrl_fill.min(), P_el_sched.min(), 0) / 1000.0
ax[0].set_ylim(ymin - abs(ymin * 0.1), ymax + abs(ymax * 0.1))
# xspace = (t[-1] - t[-2])
ax[0].set_xlim(t[0], t[24])
ax[0].axvspan(t[i_block_start], t[i_block_end], fc=GRAY+(0.1,), ec=EC)
ax[0].axvline(t[0], ls='-', color=GRAY, lw=0.5)
ax[0].axvline(t[len(t)/2], ls='-', color=GRAY, lw=0.5)
l_unctrl, = ax[0].plot_date(t, P_el_unctrl / 1000.0, fmt=':', color=PRIMB, drawstyle='steps-post', lw=0.75)
l_unctrl.set_dashes([1.0, 1.0])
# add lw=0.0 due to bug in mpl (will show as hairline in pdf though...)
l_ctrl = ax[0].fill_between(ft, P_el_ctrl_fill / 1000.0, facecolors=PRIM+(0.5,), edgecolors=EC, lw=0.0)
# Create proxy artist as l_ctrl legend handle
l_ctrl_proxy = Rectangle((0, 0), 1, 1, fc=PRIM, ec=WHITE, lw=0.0, alpha=0.5)
l_sched, = ax[0].plot_date(t, P_el_sched / 1000.0, fmt='-', color=PRIM, drawstyle='steps-post', lw=0.75)
ymax = T_storage_ctrl.max() - 273
ymin = T_storage_ctrl.min() - 273
ax[1].set_ylim(ymin - abs(ymin * 0.01), ymax + abs(ymax * 0.01))
ax[1].set_ylabel('T$_{\mathrm{storage}}\;[^{\circ}\mathrm{C}]$', labelpad=9)
ax[1].axvspan(t[i_block_start], t[i_block_end], fc=GRAY+(0.1,), ec=EC)
ax[1].axvline(t[0], ls='-', color=GRAY, lw=0.5)
ax[1].axvline(t[len(t)/2], ls='-', color=GRAY, lw=0.5)
for v in T_storage_ctrl:
ax[1].plot_date(t, v - 273.0, fmt='-', color=PRIMA, alpha=0.25, lw=0.5)
l_T_med, = ax[1].plot_date(t, T_storage_ctrl.mean(0) - 273.0, fmt='-', color=PRIMA, alpha=0.75, lw=1.5)
ax[0].xaxis.get_major_formatter().scaled[1/24.] = '%H:%M'
ax[-1].set_xlabel('Time')
fig.autofmt_xdate()
ax[1].legend([l_sched, l_unctrl, l_ctrl_proxy, l_T_med],
['Schedule', 'Uncontrolled', 'Controlled', 'Storage temperatures'],
bbox_to_anchor=(0., 1.03, 1., .103), loc=8, ncol=4,
handletextpad=0.2, mode='expand', handlelength=3,
borderaxespad=0.25, fancybox=False, fontsize='x-small')
return fig
示例9: newusersEvolution
def newusersEvolution(cursor=None, title=''):
result = cursor.execute("SELECT STRFTIME('%Y-%m-%d', rev_timestamp) AS date, rev_user_text FROM revision WHERE 1 ORDER BY date ASC")
newusers = {}
for row in result:
if not newusers.has_key(row[1]):
newusers[row[1]] = datetime.date(year=int(row[0][0:4]), month=int(row[0][5:7]), day=int(row[0][8:10]))
newusers2 = {}
for newuser, date in newusers.items():
if newusers2.has_key(date):
newusers2[date] += 1
else:
newusers2[date] = 1
newusers_list = [[x, y] for x, y in newusers2.items()]
newusers_list.sort()
startdate = newusers_list[0][0]
enddate = newusers_list[-1:][0][0]
delta = datetime.timedelta(days=1)
newusers_list = [] #reset, adding all days between startdate and enddate
d = startdate
while d < enddate:
if newusers2.has_key(d):
newusers_list.append([d, newusers2[d]])
else:
newusers_list.append([d, 0])
d += delta
import pylab
from matplotlib.dates import DateFormatter, rrulewrapper, RRuleLocator, drange
loc = pylab.MonthLocator(bymonth=(1,6))
formatter = DateFormatter('%Y-%m-%d')
dates = drange(startdate, enddate, delta)
fig = pylab.figure()
ax = fig.add_subplot(1,1,1)
ax.set_ylabel('Newusers')
ax.set_xlabel('Date (YYYY-MM-DD)')
print '#'*100
print len(dates)
print dates
print '#'*100
print len(pylab.array([y for x, y in newusers_list]))
print pylab.array([y for x, y in newusers_list])
print '#'*100
pylab.plot_date(dates, pylab.array([y for x, y in newusers_list]), 'o', color='green')
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(formatter)
ax.set_title(title)
ax.grid(True)
ax.set_yscale('log')
labels = ax.get_xticklabels()
pylab.setp(labels, rotation=30, fontsize=10)
示例10: gen_data
def gen_data(date_current,type,precision):
data_to_process =[] #debugging
delta = datetime.timedelta(minutes = precision) #debugging
if type == 'dayh':
date_previous = date_current - datetime.timedelta(days=1)
for item in drange(date_previous,date_current + datetime.timedelta(days=1),delta): #debugging
data_to_process.append({'datetimestamp':num2date(item),'Pactiva':1}) #debugging
elif type == 'week':
date_previous = (date_current -datetime.timedelta(days=7+date_current.weekday()))
for item in drange(date_previous,date_current + datetime.timedelta(days=1),delta): #debugging
data_to_process.append({'datetimestamp':num2date(item),'Pactiva':1}) #debugging
elif type == 'month':
if date_current.month < 2:
date_previous = date_current.replace(year=date_current.year-1,month=12,day=1)
else:
date_previous = date_current.replace(month=date_current.month - 1,day=1)
for item in drange(date_previous,date_current + datetime.timedelta(days=1),delta): #debugging
data_to_process.append({'datetimestamp':num2date(item),'Pactiva':1}) #debugging
elif type == 'year':
date_previous = date_current.replace(year=date_current.year - 1,month=1,day=1)
for item in drange(date_previous,date_current + datetime.timedelta(days=1),delta): #debugging
data_to_process.append({'datetimestamp':num2date(item),'Pactiva':1}) #debugging
return data_to_process
示例11: newpagesEvolution
def newpagesEvolution(cursor=None, title=""):
result = cursor.execute(
"SELECT STRFTIME('%Y-%m-%d', page_creation_timestamp) AS date, COUNT(*) AS count FROM page WHERE 1 GROUP BY date ORDER BY date ASC"
)
newpages = {}
for row in result:
d = datetime.date(year=int(row[0][0:4]), month=int(row[0][5:7]), day=int(row[0][8:10]))
newpages[d] = row[1]
newpages_list = [[x, y] for x, y in newpages.items()]
newpages_list.sort()
startdate = newpages_list[0][0]
enddate = newpages_list[-1:][0][0]
delta = datetime.timedelta(days=1)
newpages_list = [] # reset, adding all days between startdate and enddate
d = startdate
while d < enddate:
if newpages.has_key(d):
newpages_list.append([d, newpages[d]])
else:
newpages_list.append([d, 0])
d += delta
import pylab
from matplotlib.dates import DateFormatter, rrulewrapper, RRuleLocator, drange
loc = pylab.MonthLocator(bymonth=(1, 6))
formatter = DateFormatter("%Y-%m-%d")
dates = drange(startdate, enddate, delta)
fig = pylab.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_ylabel("Newpages")
ax.set_xlabel("Date (YYYY-MM-DD)")
print "#" * 100
print len(dates)
print dates
print "#" * 100
print len(pylab.array([y for x, y in newpages_list]))
print pylab.array([y for x, y in newpages_list])
print "#" * 100
pylab.plot_date(dates, pylab.array([y for x, y in newpages_list]), "o")
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(formatter)
ax.set_title(title)
ax.grid(True)
ax.set_yscale("log")
labels = ax.get_xticklabels()
pylab.setp(labels, rotation=30, fontsize=10)
示例12: convertPythonDateTime
def convertPythonDateTime(DateTime):
# Since it looks like matplotlib.dates.formatter does not work on work in mpld3...
# I have to manually make a function
print DateTime
delta = datetime.timedelta(days=1)
startDate = datetime.date(2015,5,5)#mdates.num2epoch(0)
endDate = datetime.date(2016,3,5)#mdates.num2epoch(DateTime[-1])
print delta
print startDate
print endDate
newDate = mdates.drange(startDate, endDate, delta)
print 'test'
return newDate
示例13: graphcoord_time
def graphcoord_time(axis):
time = mdates.drange(datetime.datetime(2014, 10, 21, 16),
datetime.datetime(2014, 10, 25, 16),
datetime.timedelta(minutes=15))
fig = plt.figure()
plt.plot_date(time, vector.T[axis]/50000, 'b-')
plt.ylabel(axis)
# 2014-10-23T08:30:24Z
plt.axvline(datetime.datetime(2014, 10, 23, 8, 30, 24))
fig.autofmt_xdate()
plt.show()
示例14: makeFakeRainData
def makeFakeRainData():
tdelta = dt.datetime(2001, 1, 1, 1, 5) - dt.datetime(2001, 1, 1, 1, 0)
start = dt.datetime(2001, 1, 1, 12, 0)
end = dt.datetime(2001, 1, 1, 16, 0)
daterange_num = mdates.drange(start, end, tdelta)
daterange = mdates.num2date(daterange_num)
rain_raw = [
0., 1., 2., 3., 4., 4., 4., 4., 4., 4., 4., 4.,
0., 0., 0., 0., 0., 5., 5., 5., 5., 5., 5., 5.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
1., 2., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0.]
return daterange, rain_raw
示例15: get_commit_by_date
def get_commit_by_date(self):
numdates = drange(self.start_date, self.stop_date, timedelta(days=1))
numcommits = [0 for i in numdates]
for rev, time, author in self.changesets:
date = to_datetime(time, utc).date()
#get index of day in the dates list
index = bisect(numdates, date2num(date)) - 1
numcommits[index] += 1
return (numdates, numcommits)