本文整理汇总了Python中matplotlib.dates.rrulewrapper函数的典型用法代码示例。如果您正苦于以下问题:Python rrulewrapper函数的具体用法?Python rrulewrapper怎么用?Python rrulewrapper使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了rrulewrapper函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_RRuleLocator
def test_RRuleLocator():
import pylab
import matplotlib.dates as mpldates
import matplotlib.testing.jpl_units as units
from datetime import datetime
import dateutil
units.register()
# This will cause the RRuleLocator to go out of bounds when it tries
# to add padding to the limits, so we make sure it caps at the correct
# boundary values.
t0 = datetime( 1000, 1, 1 )
tf = datetime( 6000, 1, 1 )
fig = pylab.figure()
ax = pylab.subplot( 111 )
ax.set_autoscale_on( True )
ax.plot( [t0, tf], [0.0, 1.0], marker='o' )
rrule = mpldates.rrulewrapper( dateutil.rrule.YEARLY, interval=500 )
locator = mpldates.RRuleLocator( rrule )
ax.xaxis.set_major_locator( locator )
ax.xaxis.set_major_formatter( mpldates.AutoDateFormatter(locator) )
ax.autoscale_view()
fig.autofmt_xdate()
fig.savefig( 'RRuleLocator_bounds' )
示例2: test_rrulewrapper
def test_rrulewrapper():
r = rrulewrapper(2)
try:
pickle.loads(pickle.dumps(r))
except RecursionError:
print('rrulewrapper pickling test failed')
raise
示例3: plot
def plot(dates,samples,units,samType,graphdir):
i = 0
for d in dates:
if d.find('/')==-1:
first = d.find('-')
second = d.rfind('-')
# Check for missing month/day/year values in the file
try:
year = int(d[0:first])
except ValueError:
year = 1900
try:
month = int(d[first+1:second])
except ValueError:
month = 1
try:
day = int(d[second+1:])
except ValueError:
day = 1
if(first == -1 and second == -1):
day = 1
month = 1
dates[i] = datetime.date(year,month,day)
i = i+1
else:
first = d.find('/')
second = d.rfind('/')
dates[i] = datetime.date(int(d[second+1:]),int(d[0:first]),int(d[first+1:second]))
i = i+1
c = 0
for s in samples:
if s == '':
samples[c] = '0.0'
c = c+1
rule = rrulewrapper(YEARLY)
loc = RRuleLocator(rule)
formatter = DateFormatter('%Y')
#sample_range = (float(max(float(i) for i in samples)) - float(min(float(i) for i in samples)))
#sample_range = sample_range/25
fig, ax = plt.subplots()
#if (sample_range != 0):
# minorLocator = MultipleLocator(sample_range)
# ax.yaxis.set_minor_locator(minorLocator)
plt.plot_date(dates, samples)
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(formatter)
labels = ax.get_xticklabels()
plt.title(samType)
plt.ylabel(units)
plt.setp(labels, rotation=30, fontsize=12)
plt.savefig(graphdir+'/'+samType+'.png',bbox_inches='tight')
plt.close()
示例4: plotschedule
def plotschedule(begin, end, deadline, schedule, title='Schedule',
timePenalty=defaultTimePenalty, blocking=True, display=False):
fig = plt.figure()
fig.set_size_inches(18,13.5)
ax = fig.add_axes([0.2,0.2,0.75,0.7]) #[left,bottom,width,height]
ax.set_title(title)
ax.axvline(x=begin, color="green")
if end is not None:
ax.axvline(x=end, color="blue")
if deadline is not None:
ax.axvline(x=deadline, color="red")
# Plot the data
for (pulsar,start,stop, optimalUTC, priority) in reversed(schedule):
start_date = matplotlib.dates.date2num(start)
stop_date = matplotlib.dates.date2num(stop)
duration = stop_date - start_date
optimal_start = matplotlib.dates.date2num(optimalUTC) - 0.5*duration
ax.axhline(y=schedule.index((pulsar,start,stop, optimalUTC, priority)), color=(0.8, 0.8, 0.8), zorder=0)
ax.barh((schedule.index((pulsar,start,stop, optimalUTC, priority))), duration, left=optimal_start, height=0.5,align='center',label=pulsar, color=(0.9, 0.9, 0.9), edgecolor = "none")
ax.barh((schedule.index((pulsar,start,stop, optimalUTC, priority))), duration, left=start_date, height=0.6, align='center',label=pulsar, color=(min(determinetimebadness(start, stop, optimalUTC, timePenalty), int(colorNormalizeBadness))/colorNormalizeBadness, 0.0, 0.0))
# Format y-axis
pos = range(len(schedule))
locsy, labelsy = yticks(pos, zip(*schedule)[0])
plt.setp(labelsy,size='medium')
# Format x-axis
ax.axis('tight')
ax.xaxis_date()
rule = rrulewrapper(HOURLY, interval=3)
loc = RRuleLocator(rule)
formatter = DateFormatter("%d %h - %H h")
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(formatter)
labelsx = ax.get_xticklabels()
plt.setp(labelsx, rotation=30, fontsize=10)
if begin is None:
begin = datetime.datetime.now()
if deadline is not None:
plt.xlim(begin - datetime.timedelta(hours=1) ,deadline + datetime.timedelta(hours=1))
elif end is not None:
plt.xlim(begin - datetime.timedelta(hours=1) ,end + datetime.timedelta(hours=1))
else:
plt.xlim(begin)
fig.autofmt_xdate()
plt.savefig('gantt.svg')
plt.show(block=blocking)
示例5: graf
def graf():
# plt.rc('axes', grid=True)
# plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5)
# fig = plt.figure(facecolor='white')
# textsize = 9
# left, width = 0.1, 0.8
# rect1 = [left, 0.7, width, 0.2]
# axescolor = '#f6f6f6' # the axes background color
fig, ax = plt.subplots()
# fig, ax = plt.subplots()
fillcolor = 'darkgoldenrod'
monthsFmt = DateFormatter("%d %b %y %H:%M:%S")
with open(r".\report\test_online_main_page.csv", 'r', encoding='utf-8') as f:
arr = [x.strip().split(';') for x in f]
arr_time = [datetime.strptime(x[0], '%y/%m/%d %H:%M:%S') for x in arr[1:]]
arr_value = [x[1] for x in arr[1:]]
#datetime.strptime("14/07/05 10:20:16", '%y/%m/%d %H:%M:%S') # 05.06.2011 "%d.%m.%Y"
dt = datetime.now()
vv = dates_mt.date2num(dt)
date = []
n = []
# plt.plot(arr_time, arr_value, color=fillcolor)
#ax.xaxis.set_minor_locator(mondays)
rule = rrulewrapper(YEARLY, byeaster=1, interval=1)
loc = RRuleLocator(rule)
ax.plot_date(arr_time, arr_value, '-')#
#ax.xaxis.set_major_formatter(monthsFmt)
#fig.add_subplot(111)
#ax.xaxis.set_major_locator(loc)
hour = HourLocator(range(1,25), interval=4)
formatter = DateFormatter('%H:%M:%S %m/%d/%y')
ax.xaxis.set_major_locator(hour)
ax.xaxis.set_major_formatter(formatter)
##############################################
fig, ax2 = fig.add_subplot()
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
plt.savefig("fname2.png", dpi=None, facecolor='w', edgecolor='w',
orientation='portrait', papertype=None, format=None,
transparent=False, bbox_inches=None, pad_inches=0.1,
frameon=None)
plt.show()
示例6: _test_rrulewrapper
def _test_rrulewrapper(attach_tz, get_tz):
SYD = get_tz('Australia/Sydney')
dtstart = attach_tz(datetime.datetime(2017, 4, 1, 0), SYD)
dtend = attach_tz(datetime.datetime(2017, 4, 4, 0), SYD)
rule = mdates.rrulewrapper(freq=dateutil.rrule.DAILY, dtstart=dtstart)
act = rule.between(dtstart, dtend)
exp = [datetime.datetime(2017, 4, 1, 13, tzinfo=dateutil.tz.tzutc()),
datetime.datetime(2017, 4, 2, 14, tzinfo=dateutil.tz.tzutc())]
assert act == exp
示例7: _configure_xaxis
def _configure_xaxis(self):
''''x axis'''
# make x axis date axis
self._ax.xaxis_date()
# format date to ticks on every 7 days
rule = mdates.rrulewrapper(mdates.DAILY, interval=7)
loc = mdates.RRuleLocator(rule)
formatter = mdates.DateFormatter("%d %b")
self._ax.xaxis.set_major_locator(loc)
self._ax.xaxis.set_major_formatter(formatter)
xlabels = self._ax.get_xticklabels()
plt.setp(xlabels, rotation=30, fontsize=9)
示例8: CreateGanttChart
def CreateGanttChart(fname):
"""Create gantt charts with matplotlib
Give file name.
"""
ylabels = []
customDates = []
textlist = open(fname).readlines()
for tx in textlist:
if not tx.startswith('#'):
ylabel, startdate, enddate = tx.split(',')
ylabels.append(ylabel.replace('\n', ''))
customDates.append([_create_date(startdate.replace('\n', '')), _create_date(enddate.replace('\n', ''))])
ilen = len(ylabels)
pos = np.arange(0.5, ilen * 0.5 + 0.5, 0.5)
task_dates = {}
for i, task in enumerate(ylabels):
task_dates[task] = customDates[i]
fig = plt.figure(figsize=(20, 8))
ax = fig.add_subplot(111)
for i in range(len(ylabels)):
start_date, end_date = task_dates[ylabels[i]]
ax.barh((i * 0.5) + 0.5, end_date - start_date, left=start_date, height=0.3, align='center', edgecolor='lightgreen', color='orange', alpha=0.8)
locsy, labelsy = plt.yticks(pos, ylabels)
plt.setp(labelsy, fontsize=14)
# ax.axis('tight')
ax.set_ylim(ymin=-0.1, ymax=ilen * 0.5 + 0.5)
ax.grid(color='g', linestyle=':')
ax.xaxis_date()
rule = rrulewrapper(WEEKLY, interval=1)
loc = RRuleLocator(rule)
# formatter = DateFormatter("%d-%b '%y")
formatter = DateFormatter("%d-%b")
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(formatter)
labelsx = ax.get_xticklabels()
plt.setp(labelsx, rotation=30, fontsize=10)
font = font_manager.FontProperties(size='small')
ax.legend(loc=1, prop=font)
ax.invert_yaxis()
fig.autofmt_xdate()
plt.savefig(fname + '.svg')
plt.show()
示例9: sales_by_month
def sales_by_month(data_map,header,dates):
fn='sales_by_month.png'
rule = rrulewrapper(DAILY, byeaster=1, interval=5)
loc = RRuleLocator(rule)
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
weeks = mdates.WeekdayLocator()
days = mdates.DayLocator()
weeks.MAXTICKS = 2000
formatter = DateFormatter('%a %d/%m/%y')
#dates_x = drange(date1, date2, delta)
fig, ax1 = plt.subplots(nrows=1,ncols=1)
#ax=ax1
ax1.xaxis_date()
ax1.xaxis.set_major_formatter(formatter)
ax1.xaxis.set_major_locator(weeks)
ax1.xaxis.set_minor_locator(days)
labels = ax1.get_xticklabels()
#labels = ax1.xaxis.get_major_ticks()
plt.setp(labels, rotation=30, fontsize=10)
plt.title('Phone Calls, 30 days window')
ax1.grid()
key_inbound=(u'Inbound', 'crm.case.categ', 18)
plot_days(ax1, data_map, dates, key_inbound, line='k', label='Inbound Calls', days=30)
key_sales= (u'Sales Opportunity', 'crm.case.categ', 15)
plot_days(ax1, data_map, dates, key_sales, line='r', label='Sales Opportunity', days=30)
key_phone= (u'Retail Phone', 'sale.shop', 2)
plot_days(ax1, data_map, dates, key_phone, line='-', label='Closed Sales', days=30)
ax1.legend()
image_path=get_module_path('html_reports')
image_file=os.path.join(image_path,fn)
# print image_file
plt.savefig(image_file, bbox_inches='tight')
#print data_map
return fn
示例10: yticks
# # ax.barh((i*0.5)+1.0, end_date - mid_date, left=mid_date, height=0.3, align='center',label=labels[1], color='yellow')
# Format the y-axis
locsy, labelsy = yticks(pos,ylabels)
plt.setp(labelsy, fontsize = 14)
# Format the x-axis
ax.axis('tight')
ax.set_ylim(ymin = -0.1, ymax = 6.5)
ax.grid(color = 'g', linestyle = ':')
ax.xaxis_date() #Tell matplotlib that these are dates...
rule = rrulewrapper(WEEKLY, interval=1)
loc = RRuleLocator(rule)
formatter = DateFormatter("%b %d")
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(formatter)
labelsx = ax.get_xticklabels()
plt.setp(labelsx, rotation=30, fontsize=12)
# Format the legend
# font = font_manager.FontProperties(size='small')
# ax.legend(loc=1,prop=font)
# Finish up
ax.invert_yaxis()
示例11: figure
# Select only good data
qcLevel = 1
index_qcLevel = TEMP_qcFlag[:, 0, 0] == qcLevel
timeData = timeData[index_qcLevel]
tempData = TEMP[:, 0, 0]
tempData = tempData[index_qcLevel]
# plot temperature timeseries
figure1 = figure(num=None, figsize=(15, 10), dpi=80, facecolor="w", edgecolor="k")
ax1 = subplot(111)
plot(timeData, tempData)
title(
faimms_DATA.title
+ "\n"
+ "%0.2f m depth\n" % TEMP.sensor_depth
+ "location: lat=%0.2f; lon=%0.2f" % (faimms_DATA.variables["LATITUDE"][:], faimms_DATA.variables["LONGITUDE"][:])
)
xlabel(TIME.long_name)
ylabel(TEMP.standard_name + " in " + TEMP.units)
rule = rrulewrapper(DAILY, interval=1)
formatter = DateFormatter("%d/%m/%y")
loc = RRuleLocator(rule)
ax1.xaxis.set_major_locator(loc)
ax1.xaxis.set_major_formatter(formatter)
labels = ax1.get_xticklabels()
setp(labels, rotation=30, fontsize=10)
show()
示例12: main
#.........这里部分代码省略.........
for line in content[1:]:
#filter only pages with total (or dic is -d) greater or smaller than X
if opts.excludemorethan:
if float(line[tot_index]) > opts.excludemorethan:
continue
if opts.excludelessthan:
if float(line[tot_index]) < opts.excludelessthan:
continue
mat.append([x for x in _gen_data(line, opts.id_col,
ignorecols, onlycols)])
totals.append(float(line[tot_index]))
timestamps.append(ts2dt(line[opts.id_col]))
del content
mat = np.array(mat, dtype=np.float).transpose()
logging.info("Input file read. Ready to plot")
pdf_pag = PdfPages(files[1])
with Timr("Plotting"):
for i, series in enumerate(mat):
logging.info("Plotting page %d", i + 1)
# Don't plot zeros and skip zero revisions!
#ser = [x for x in series if x != 0]
#time = [x for k, x in enumerate(timestamps) if series[k] != 0]
#tot = [x for k, x in enumerate(totals) if series[k] != 0]
ser = [x for k, x in enumerate(series) \
if (not opts.start or timestamps[k] >= opts.start) and \
(not opts.end or timestamps[k] <= opts.end)]
time = [x for k, x in enumerate(timestamps) \
if (not opts.start or x >= opts.start) and \
(not opts.end or x <= opts.end)]
tot = [x for k, x in enumerate(totals) \
if (not opts.start or timestamps[k] >= opts.start) and \
(not opts.end or timestamps[k] <= opts.end)]
if opts.smooth and len(time) and len(ser) and len(tot):
time, ser, tot = smooth_values(time, ser, tot,
opts.smooth)
if opts.window and len(time) and len(ser) and len(tot):
time, ser, tot = collapse_values(time, ser, tot,
opts.window)
mean = float(sum(series)) / len(series)
#rel_mean is the mean for the period [opts.end, opts.start]
rel_mean = float(sum(ser)) / len(ser)
if opts.perc:
try:
mean = float(sum(series)) / sum(totals)
rel_mean = float(sum(ser)) / sum(tot)
except ZeroDivisionError:
mean = 0
rel_mean = 0
# Calculate percentages
ser = [calc_perc(x, tot[k]) for k, x in enumerate(ser)]
# Set axis limit 0-1 IS IT GOOD OR BAD?
#axis.set_ylim(0, 1)
plt.ylabel("%")
first_time = time[0].date()
last_time = time[-1].date()
plt.clf()
plt.subplots_adjust(bottom=0.25)
plt.xticks(rotation=90)
fig = plt.gcf()
fig.set_size_inches(11.7, 8.3)
axis = plt.gca()
axis.xaxis.set_major_formatter(md.DateFormatter('%Y-%m-%d'))
axis.set_xlim(matplotlib.dates.date2num(first_time),
matplotlib.dates.date2num(last_time))
if last_time - first_time < timedelta(days=30):
axis.xaxis.set_major_locator(md.DayLocator(interval=1))
axis.xaxis.set_minor_locator(md.DayLocator(interval=1))
else:
axis.xaxis.set_minor_locator(md.MonthLocator(interval=1))
#auto_loc = md.AutoDateLocator(minticks=8, maxticks=12, interval_multiples=True)
#auto_loc.intervald[md.MONTHLY] = [6]
rule = md.rrulewrapper(md.MONTHLY, interval=4)
auto_loc = md.RRuleLocator(rule)
axis.xaxis.set_major_locator(auto_loc)
axis.tick_params(labelsize='x-small')
plt.xlabel("Revisions Timestamp")
if len(time) and len(ser):
if opts.window:
time = [t.date() for t in time]
logging.info("Mean: %f", mean)
logging.info("Relative Mean: %f", rel_mean)
if header[i] == "negemo" or header[i] == "posemo":
print ser # ONLY FOR TESTING, FIXME WHEN FINISHED
plt.plot(matplotlib.dates.date2num(time), ser, "b.-")
plt.axhline(y=mean, color="r")
plt.title("%s - Mean: %.5f - Relative mean: %.5f" % (header[i], round(mean, 5), round(rel_mean, 5)))
pdf_pag.savefig()
pdf_pag.close()
示例13: float
splt = l.split(" ")
date_str = splt[0]
date.append( datetime.strptime(date_str,"%Y-%m-%dT%H%M%S.%f") )
voltage.append( float(splt[1]) )
gps_on.append( (splt[2] == "True") )
humidity.append( float(splt[3]) )
temp0.append( float(splt[4]) )
temp1.append( float(splt[5]) )
temp2.append( float(splt[6]) )
temp3.append( float(splt[7]) )
temp4.append( float(splt[8]) )
fig, (ax0, ax1, ax2, ax3) = plt.subplots(nrows=4, sharex=True)
formatter = DateFormatter('%d/%m/%y')
rule = rrulewrapper(DAILY)
loc = RRuleLocator(rule)
ax0.plot(date,voltage, ".")
ax0.xaxis.set_major_formatter(formatter)
ax0.xaxis.set_major_locator(loc)
ax0.set_title("voltage (V)")
ax1.plot(date,temp0, ".")
ax1.plot(date,temp1, ".")
ax1.plot(date,temp2, ".")
ax1.plot(date,temp3, ".")
ax1.plot(date,temp4, ".")
ax1.xaxis.set_major_formatter(formatter)
ax1.xaxis.set_major_locator(loc)
ax1.set_title("temperature (degC)")
示例14: subplot
# plot current profiles
figure1 =figure( figsize=(13, 18), dpi=80, facecolor='w', edgecolor='k')
ax1 = subplot(211)
pcolor(prof_2D_mesh , heightData_mesh , uCurrentData[:,:,0,0],cmap=cmap)
clim(UCUR.valid_min, UCUR.valid_max)
cbar = colorbar()
cbar.ax.set_ylabel(UCUR.long_name + ' in ' + UCUR.units)
title(anmn_DATA.title + '\nplot of ' + flag_meanings[qcLevel[0]] +
' and ' + flag_meanings[qcLevel[1]] + ' only')
xlabel('Profile Index')
ylabel(HEIGHT.long_name +' in ' + HEIGHT.units)
# plot profile index with time
ax2 = subplot(212)
plot(timeData,profIndex)
ylabel('Profile Index')
xlabel(anmn_DATA.variables['TIME'].long_name +' in DD/MM/YY')
# format date ticks
rule = rrulewrapper(MONTHLY, bymonthday=1, interval=1)
formatter = DateFormatter('%d/%m/%y')
loc = RRuleLocator(rule)
ax2.xaxis.set_major_locator(loc)
ax2.xaxis.set_major_formatter(formatter)
labels = ax2.get_xticklabels()
setp(labels, rotation=30, fontsize=10)
show()
示例15: get_locator
def get_locator(self, dmin, dmax):
'Pick the best locator based on a distance.'
delta = relativedelta(dmax, dmin)
numYears = (delta.years * 1.0)
numMonths = (numYears * 12.0) + delta.months
numDays = (numMonths * 31.0) + delta.days
numHours = (numDays * 24.0) + delta.hours
numMinutes = (numHours * 60.0) + delta.minutes
numSeconds = (numMinutes * 60.0) + delta.seconds
# numticks = 5
# Difference to original AutoDateLocator: less ticks
numticks = self.numticks
# self._freq = YEARLY
interval = 1
bymonth = 1
bymonthday = 1
byhour = 0
byminute = 0
bysecond = 0
if (numYears >= numticks):
self._freq = YEARLY
interval = int(numYears // numticks)
elif (numMonths >= numticks):
self._freq = MONTHLY
bymonth = range(1, 13)
interval = int(numMonths // numticks)
elif (numDays >= numticks):
self._freq = DAILY
bymonth = None
bymonthday = range(1, 32)
interval = int(numDays // numticks)
elif (numHours >= numticks):
self._freq = HOURLY
bymonth = None
bymonthday = None
byhour = range(0, 24) # show every hour
interval = int(numHours // numticks)
elif (numMinutes >= numticks):
self._freq = MINUTELY
bymonth = None
bymonthday = None
byhour = None
byminute = range(0, 60)
interval = int(numMinutes // numticks)
# end if
elif (numSeconds >= numticks):
self._freq = SECONDLY
bymonth = None
bymonthday = None
byhour = None
byminute = None
bysecond = range(0, 60)
interval = int(numSeconds // numticks)
# end if
else:
# do what?
# microseconds as floats, but floats from what reference point?
pass
rrule = rrulewrapper(self._freq, interval=interval,
dtstart=dmin, until=dmax,
bymonth=bymonth, bymonthday=bymonthday,
byhour=byhour, byminute=byminute,
bysecond=bysecond)
locator = RRuleLocator(rrule, self.tz)
locator.set_axis(self.axis)
locator.set_view_interval(*self.axis.get_view_interval())
locator.set_data_interval(*self.axis.get_data_interval())
return locator