本文整理汇总了Python中pylab.plot_date函数的典型用法代码示例。如果您正苦于以下问题:Python plot_date函数的具体用法?Python plot_date怎么用?Python plot_date使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了plot_date函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plotmagtime
def plotmagtime(self, FontSize):
""" plot magnitude versus time """
import pylab as plt
plt.plot_date(self.time, self.mag)
#plt.title('Mag-time view')
plt.xlabel('time', fontsize=FontSize)
plt.ylabel('magnitude', fontsize=FontSize)
示例2: get_spot_history
def get_spot_history(self, instance_type, start=None, end=None, plot=False):
if not utils.is_iso_time(start):
raise exception.InvalidIsoDate(start)
if not utils.is_iso_time(end):
raise exception.InvalidIsoDate(end)
hist = self.conn.get_spot_price_history(start_time=start,
end_time=end,
instance_type=instance_type,
product_description="Linux/UNIX")
if not hist:
raise exception.SpotHistoryError(start,end)
dates = [ utils.iso_to_datetime_tuple(i.timestamp) for i in hist]
prices = [ i.price for i in hist ]
maximum = max(prices)
avg = sum(prices)/len(prices)
log.info("Current price: $%.2f" % hist[-1].price)
log.info("Max price: $%.2f" % maximum)
log.info("Average price: $%.2f" % avg)
if plot:
try:
import pylab
pylab.plot_date(pylab.date2num(dates), prices, linestyle='-')
pylab.xlabel('date')
pylab.ylabel('price (cents)')
pylab.title('%s Price vs Date (%s - %s)' % (instance_type, start, end))
pylab.grid(True)
pylab.show()
except ImportError,e:
log.error("Error importing pylab:")
log.error(str(e))
log.error("please check that matplotlib is installed and that:")
log.error(" $ python -c 'import pylab'")
log.error("completes without error")
示例3: mains_energy
def mains_energy():
import psycopg2
conn = psycopg2.connect('dbname=gateway')
cursor = conn.cursor()
meter_name = 'ug04'
date_start = '20111001'
date_end = '20111201'
query = """select *
from midnight_rider
where name = '%s' and
ip_address = '192.168.1.200' and
date >= '%s' and
date <= '%s'
order by date
""" % (meter_name, date_start, date_end)
shniz = cursor.execute(query)
shniz = cursor.fetchall()
dates = []
watthours = []
for s in shniz:
dates.append(s[0])
watthours.append(s[2])
import pylab
pylab.plot_date(dates,watthours)
pylab.grid()
pylab.show()
示例4: plot_dwaf_data
def plot_dwaf_data(realtime, file_name='data_plot.png', gauge=True):
x = pl.date2num(realtime.date)
y = realtime.q
pl.clf()
pl.figure(figsize=(7.5, 4.5))
pl.rc('text', usetex=True)# TEX fonts
pl.plot_date(x,y,'b-',linewidth=1)
pl.grid(which='major')
pl.grid(which='minor')
if gauge:
pl.ylabel(r'Flow rate (m$^3$s$^{-1}$)')
title = 'Real-time flow -- %s [%s]' % (realtime.station_id[0:6], realtime.station_desc)
else:
title = 'Real-time capacity -- %s [%s]' % (realtime.station_id[0:6], realtime.station_desc)
pl.ylabel('Percentage of F.S.C')
labeled_days = DayLocator(interval=3)
ticked_days = DayLocator()
dayfmt = DateFormatter('%d/%m/%Y')
ax = pl.gca()
ax.xaxis.set_major_locator(labeled_days)
ax.xaxis.set_major_formatter(dayfmt)
ax.xaxis.set_minor_locator(ticked_days)
pl.xticks(fontsize=10)
pl.yticks(fontsize=10)
pl.title(title, fontsize=14)
pl.savefig(file_name, dpi=100)
示例5: ForecastDraw
def ForecastDraw(self):
"""
at the day-level
:return:
"""
pl.title("aqi/time(day)")# give plot a title
pl.xlabel('time')# make axis labels
pl.ylabel('aqi')
data = np.loadtxt(StringIO(self._xyArrayStr), dtype=np.dtype([("t", "S13"), ("v", float)]))
datestr = np.char.replace(data["t"], "T", " ")
t = dt.datestr2num(datestr)
# k = pl.num2date(t)
# k2 = dt.num2date(t)
v = data["v"]
if len(t) > 30:
t = t[-30:]
v = v[-30:]
pl.plot_date(t, v, fmt="-o")
self.polyfit(t, v)
pl.subplots_adjust(bottom=0.3)
# pl.legend(loc=4)#指定legend的位置,读者可以自己help它的用法
ax = pl.gca()
ax.fmt_xdata = pl.DateFormatter('%Y-%m-%d %H:%M:%S')
pl.xticks(rotation=70)
# pl.xticks(t, datestr) # 如果以数据点为刻度,则注释掉这一行
ax.xaxis.set_major_formatter(pl.DateFormatter('%Y-%m-%d %H:%M'))
# pl.xlim(('2016-03-09 00:00', '2016-03-12 00:00'))
pl.grid() # 有格子
pl.show()# show the plot on the screen
return self._forecast_Value
示例6: plot_session_timeline
def plot_session_timeline(sessions,prefix=fname_prefix):
offset = {'behop':1,'lwapp':2 }
annot = {'behop':'b-*','lwapp':'r-*'}
pylab.figure()
for s in sessions:
pylab.plot_date(matplotlib.dates.date2num([s['start'],s['end']]),[offset[s['type']],offset[s['type']]],
annot[s['type']])
#pylab.plot([s['start'],s['end']],[offset[s['type']],offset[s['type']]], annot[s['type']])
pylab.xlim((STARTING_DAY,END_DAY))
pylab.ylim([0,3])
timespan = END_DAY - STARTING_DAY
print "Total Seconds %d" % timespan.total_seconds()
timeticks = [STARTING_DAY + timedelta(seconds=x) for x in range(0,int(timespan.total_seconds()) + 1, int(timespan.total_seconds()/4))]
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d-%H'))
plt.gca().set_xticks(timeticks)
#start = sessions[0]['start']
#dates = [(s['end'] - start).days for s in sessions]
#print dates
#plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
#tick_dates = [start + timedelta(days=i) for i in range(0,max(dates))]
#plt.gca().set_xticks(tick_dates)
pylab.savefig('%s_timeline' % (prefix))
示例7: drawCity
def drawCity(self):
"""
作图
:return:
"""
pl.title("pm25 / time " + str(self.numMonitors) + "_monitors")# give plot a title
pl.xlabel('time')# make axis labels
pl.ylabel('pm2.5')
self.fill_cityPm25List()
for monitorStr in self.cityPm25List:
data = np.loadtxt(StringIO(monitorStr), dtype=np.dtype([("t", "S13"),("v", float)]))
datestr = np.char.replace(data["t"], "T", " ")
t = pl.datestr2num(datestr)
v = data["v"]
pl.plot_date(t, v, fmt="-o")
pl.subplots_adjust(bottom=0.3)
# pl.legend(loc=4)#指定legend的位置,读者可以自己help它的用法
ax = pl.gca()
ax.fmt_xdata = pl.DateFormatter('%Y-%m-%d %H:%M:%S')
pl.xticks(rotation=70)
# pl.xticks(t, datestr) # 如果以数据点为刻度,则注释掉这一行
ax.xaxis.set_major_formatter(pl.DateFormatter('%Y-%m-%d %H:%M'))
pl.grid()
pl.show()# show the plot on the screen
示例8: line_plot
def line_plot(data, out):
"""Turning ([key, ...], [value, ...]) into line graphs"""
pylab.clf()
pylab.plot_date(data[0], data[1], '-')
pylab.savefig(out)
示例9: plot_diurnal
def plot_diurnal(headers):
"""
Diurnal plot of the emails, with years running along the x axis and times of
day on the y axis.
"""
xday = []
ytime = []
print 'making diurnal plot...'
for h in iterview(headers):
if len(h) > 1:
try:
s = h[1][5:].strip()
x = dateutil.parser.parse(s)
except ValueError:
print
print marquee(' ERROR: skipping ')
print h
print marquee()
continue
timestamp = mktime(x.timetuple()) # convert datetime into floating point number
mailstamp = datetime.fromtimestamp(timestamp)
xday.append(mailstamp)
# Time the email is arrived
# Note that years, month and day are not important here.
y = datetime(2010, 10, 14, mailstamp.hour, mailstamp.minute, mailstamp.second)
ytime.append(y)
plot_date(xday,ytime,'.',alpha=.7)
xticks(rotation=30)
return xday,ytime
示例10: plot_save
def plot_save(X, Y, title, filename):
clf()
xticks(rotation=90)
suptitle(title)
subplots_adjust(bottom=0.2)
plot_date(X, Y, "k.")
savefig(filename, dpi=600)
示例11: plotStock
def plotStock(symbol, startDate, endDate):
"""returns a plot of stock (symbol) between startDate and endDate
symbol: String, stock ticker symbol
startDate, endDate = tuple(YYYY, MM, DD)
"""
company = symbol
sYear, sMonth, sDay = startDate
eYear, eMonth, eDay = endDate
start = datetime(sYear, sMonth, sDay)
end = datetime(eYear, eMonth, eDay)
data = DataReader(company, "yahoo", start, end)
closingVals = data["Adj Close"]
#convert to matplotlib format
dates = [i for i in data.index]
dates = matplotlib.dates.date2num(dates)
pylab.ylim([0, int(max(closingVals)*1.2)])
pylab.plot_date(dates, closingVals, label = symbol, xdate = True,
ydate=False, linestyle = '-')
pylab.legend()
pylab.show()
示例12: load_graph
def load_graph():
pylab.figure(num = 1, figsize=(6, 3))
ax = pylab.gca() #get the current graphics region
#Set the axes position with pos = [left, bottom, width, height]
ax.set_position([.1,.15,.8,.75])
if zoom == False:
print "zoom = False"
pylab.plot_date(date, kiln_temp, 'r-', linewidth = 1)
if zoom == True:
print "zoom = True"
zoom_date = date[(len(date)-zoom_level):]
zoom_kiln_temp = kiln_temp[(len(kiln_temp)-zoom_level):]
pylab.plot(zoom_date, zoom_kiln_temp, 'r-', linewidth = 1)
pylab.title(r"Kiln Temperature")
ax.xaxis.set_major_formatter(DateFormatter('%H:%M'))
xlabels = ax.get_xticklabels()
#pylab.setp(xlabels,'rotation', 45, fontsize=10)
ylabels = ax.get_yticklabels()
#pylab.setp(ylabels,fontsize=10)
pylab.savefig('graph.png')
pylab.close(1)
graph = os.path.join("","graph.png")
graph_surface = pygame.image.load(graph).convert()
screen.blit(graph_surface, (100,30))
"""
示例13: work_1
def work_1():
data_in = datetime(2010,6,24,8,00,0)
data_fin = datetime(2010,6,24,22,00,0)
#np.concatenate((dati,dati2))
dati = df.query_db('greenhouse.db','data',data_in,data_fin)
Is = dati['rad_int_sup_solar']
lista_to_filter = df.smooht_Is(Is)
Is_2 = df.smooth_value(Is,lista_to_filter)
tra_P_M = mf.transpiration_P_M(Is_2,dati['rad_int_inf_solar'],0.64,2.96,((dati['temp_1']+dati['temp_2'])/2)+273.15,(dati['RH_1']+dati['RH_2'])/200)
tra_weight = mf.transpiration_from_balance(dati['peso_balanca'],300,2260000)
delta_peso = np.diff(dati['peso_balanca'])
fr,lista_irr,lista_irr_free = mf.find_irrigation_point(delta_peso,dati['data'])
lista_night = mf.remove_no_solar_point(dati['rad_int_sup_solar'],50)
lista_no = list(set(lista_irr+ lista_night))
tran_weight,lista_yes = mf.transpiration_from_balance_irr(dati['peso_balanca'],300,2260000,lista_no)
min_avg = 6
tra_weigh_avg,time_weight = df.avg2(tran_weight,lista_yes,min_avg)
tra_P_M_avg,time_P_M = df.avg2(tra_P_M,lista_yes,min_avg)
data_plot.plot_time_data_2_y_same_axis(dati['data'][time_P_M], tra_P_M_avg, 'tra Penman', tra_weigh_avg, 'trans weight')
RMSE = df.RMSE(tra_P_M_avg, tra_weigh_avg)
print "RMSE is", RMSE
print "RRMSE is", df.RRMSE(RMSE, tra_weigh_avg)
date = dati['data'][time_P_M].astype(object)
dates= pylab.date2num(date)
pylab.plot_date(dates,tra_weigh_avg,'rx')
示例14: main
def main():
Global.logdir = sys.argv[1]
Global.account = sys.argv[2]
Global.parameter = sys.argv[3]
Global.t_start = datetime.strptime(sys.argv[4], "%Y%m%d%H%M")
Global.t_end = datetime.strptime(sys.argv[5], "%Y%m%d%H%M")
lines = lines_from_dir("192_168_1_2%s.log" % (Global.account,), Global.logdir)
logs = meter_logs(lines)
print "Site:", Global.logdir
print "Meter:", Global.account
print "Parameter:", Global.parameter
print "Time Range:", Global.t_start.isoformat(' '), "to", Global.t_end.isoformat(' ')
values = sorted([(el['Time Stamp'], el[Global.parameter])
for el in logs], key=lambda t: t[0])
print len(values)
print "plotting..."
pylab.figure()
pylab.title("Site:%s, Meter: %s, Parameter: %s, Time Scale: %s to %s" % (
Global.logdir, Global.account, Global.parameter,
Global.t_start, Global.t_end))
pylab.xlabel("Time")
pylab.ylabel(Global.parameter)
pylab.plot_date(*zip(*values), fmt='-')
pylab.grid(True)
pylab.savefig('%s_%s_%s_%s_%s' % (
Global.logdir, Global.account, Global.parameter,
Global.t_start.strftime("%Y%m%d%H%M"), Global.t_end.strftime("%Y%m%d%H%M")))
pylab.show()
print "done."
示例15: plotdepthtime
def plotdepthtime(self, FontSize):
""" plot depth against time """
pylab.plot_date(vector_epoch2datetime(self['etime']), self['depth'],'o')
#pylab.title('Depth-time view')
pylab.xlabel('time', fontsize=FontSize)
pylab.ylabel('depth', fontsize=FontSize)
pylab.gca().invert_yaxis()