当前位置: 首页>>代码示例>>Python>>正文


Python pyplot.plot_date函数代码示例

本文整理汇总了Python中matplotlib.pyplot.plot_date函数的典型用法代码示例。如果您正苦于以下问题:Python plot_date函数的具体用法?Python plot_date怎么用?Python plot_date使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了plot_date函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: plot_gestures_and_flux_score

def plot_gestures_and_flux_score(plot_title, gestures, flux, flux_diffs):
    """
    Plots a gesture score with flux values as well - this one suffers the window bug
    """
    idx = gestures.index
    # ax = plt.figure(figsize=(35,10),frameon=False,tight_layout=True).add_subplot(111)
    ax = plt.figure(figsize=(14, 6), frameon=False, tight_layout=True).add_subplot(211)
    ax.xaxis.set_major_locator(dates.SecondLocator(bysecond=[0]))
    ax.xaxis.set_major_formatter(dates.DateFormatter("%H:%M"))
    ax.yaxis.grid()
    plt.ylim(-0.5, 8.5)
    plt.yticks(np.arange(9), ['n', 'ft', 'st', 'fs', 'fsa', 'vss', 'bs', 'ss', 'c'])
    plt.ylabel("gesture")
    for n in gestures.columns:
        plt.plot_date(idx.to_pydatetime(), gestures[n], '-', label=n)
    # Plot Flux Data
    ax2 = plt.subplot(212, sharex=ax)
    idx = flux.index
    plt.plot_date(idx.to_pydatetime(), flux, '-', label=flux.name)
    plt.ylabel("flux")
    # Possible New Ideas Stage
    # new_ideas = flux_diffs.ix[flux_diffs > transitions.NEW_IDEA_THRESHOLD]
    # new_ideas = new_ideas.index
    # new_idea_colour = 'r'
    # for n in range(len(new_ideas)):
    #     x_val = new_ideas[n].to_pydatetime()
    #     ax.axvline(x=x_val, color=new_idea_colour, alpha=0.7, linestyle='--')
    #     ax2.axvline(x=x_val, color=new_idea_colour, alpha=0.7, linestyle='--')
    # Output Stage
    plt.savefig(plot_title.replace(":", "_") + '.pdf', dpi=300, format="pdf")
    plt.close()
开发者ID:cpmpercussion,项目名称:MetatoneClassifier,代码行数:31,代码来源:generate_posthoc_gesture_score.py

示例2: get_data_from_internet

def get_data_from_internet(stack, date):
    baseurl = "http://chartapi.finance.yahoo.com/instrument/1.0/"+ stack +"/chartdata;type=quote;range="+date+"/csv"
    sourece_code = urllib.request.urlopen(baseurl).read().decode()
    # print(sourece_code)
    stock_data = []
    split_source = sourece_code.split("\n")

    for line in split_source:
        split_line = line.split(',')
        if len(split_line) == 6:
            if 'values' not in line and 'labels' not in line:
                stock_data.append(line)

    print(stock_data)

    if 'd' in date:
        date, close, high, low, openp, volume = np.loadtxt(stock_data,
                                                           delimiter=',',
                                                           unpack=True,
                                                           converters={0: bytesdata2num('%y%m%d %H%M', 'd')})
    else:
        date, close, high, low, openp, volume = np.loadtxt(stock_data,
                                                           delimiter=',',
                                                           unpack=True,
                                                           converters={0: bytesdata2num('%Y%m%d', 'y')})
    plt.plot_date(date, close, '-', label='从网络加载股价')
    plt.xlabel("时间")
    plt.ylabel("股价")
    plt.title("练习从网络加载数据!")
    rect = plt.figure(1).patch
    rect.set_facecolor('c')
    plt.legend()   #plot有label选项时,必须要有此句
    plt.show()
开发者ID:yiyisf,项目名称:matplotlib,代码行数:33,代码来源:matplotlib_load_from_internet.py

示例3: graph_date_v_charge

def graph_date_v_charge(data):
    """
    Graphs charge data over time.
    
    @param data: Parsed data from log file; output of L{parseLog}
    """
    
    print "Graphing Date v. Charge"
    
    # Build color data based on charge percentage
    colors = []
    for charge in data['charges']:
        
        colors.append((1-charge/100.0, charge/100.0, 0.3))


    f1 = pyplot.figure(1)

    for i in range(len(data['dates'])):
        pyplot.plot_date(data['dates'][i], data['charges'][i], 'o', color=colors[i], 
                         markersize=3, markeredgewidth=0.1)

    pyplot.ylim(0,100)
    pyplot.xlabel('Date')
    pyplot.ylabel('Charge [%]')
    pyplot.title('Laptop Battery Charge')
    pyplot.grid(True)
    pyplot.figure(1).autofmt_xdate()

    pyplot.savefig(outfile + ".png", dpi=500)

    pyplot.close(f1)
开发者ID:mposner,项目名称:battery_logging,代码行数:32,代码来源:analyze.py

示例4: plot_timeline_epoch

def plot_timeline_epoch(usr1, usr2, interaction1=None, interaction2=None):
	print "########## Plotting for ", usr1, usr2, "###################"
	if interaction1 is not None:
		tweets_per_day1 = extract_daily_interaction(interaction1)
		plt.plot_date(x=tweets_per_day1.keys(), y=tweets_per_day1.values(), fmt=u'b*')
		print usr1, len(tweets_per_day1.keys()), sorted(tweets_per_day1.keys())
	if interaction2 is not None:
		#print usr2, len(interaction2)
		tweets_per_day2 = extract_daily_interaction(interaction2)
		plt.plot_date(x=tweets_per_day2.keys(), y=tweets_per_day2.values(), fmt=u'xr')
	if interaction1 is not None and interaction2 is not None:
		print usr1, usr2
		plt.title("Mentions 2 users: from " + usr1 + " (blue); from " + usr2 + " (red).")
	elif interaction1 is not None:
		plt.title("Mentions from " + usr1 + " to " + usr2 + ".")
	elif interaction2 is not None:
		plt.title("Mentions from " + usr2 + " to " + usr1 + ".")
	else:
		print "No interaction between 2 users to be plotted."
		return
	plt.xticks(rotation=70)
	plt.ylabel("# tweets per day")
	plt.grid(True)
	plt_name = WORKING_FOLDER + "2_usr_interaction/interaction_" + usr1 + "_and_" + usr2 + ".png"
	plt.savefig(plt_name, bbox_inches='tight', dpi=440)
	print "########## Plotting DONE for ", usr1, usr2, "###############"
	plt.clf()
开发者ID:sanja7s,项目名称:SR_Twitter,代码行数:27,代码来源:graph.py

示例5: draw_viz

def draw_viz(t1, t2):
    data_store = sds()
    delta = datetime.timedelta(days=1)

    t1_data = []
    t2_data = []
    dates = []

    d_cursor = data_store.get_company_data(t1)
    for d in d_cursor:
        t1_data.append(d["Adj Clos"])
        dates.append(d["date"])
    d_cursor = data_store.get_company_data(t2)
    for d in d_cursor:
        t2_data.append(d["Adj Clos"])
    print len(t1_data), len(t2_data)
    p, sprd, beta = fc.get_adf(t1, t2, spread=True)
    dates = mpl.dates.date2num(dates)
    p1 = plt.plot_date(dates, sprd, "b-.", label="Sprd")
    p2 = plt.plot_date(dates, t1_data, "g-.", label=t1)
    p3 = plt.plot_date(dates, t2_data, "r-.", label=t2)
    plt.grid(True)
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)

    def add_vert_line(event):
        plt.avspan(event.xdata, event.xdata, ls="p-")

    print "Beta: %f" % beta
    plt.show()
开发者ID:hezhenke,项目名称:Mecha-Trader,代码行数:29,代码来源:draw_time_series.py

示例6: plotAllData

    def plotAllData( self, allData, particleSize, room ):
        dates = allData['Time']
        print 'Plotting and saving averages'
        for shift in ['Day Shift','Night Shift','Empty Lab']:
            pyplot.figure(num=None, figsize=(16,9), dpi=100, facecolor='w', edgecolor='k')
            pyplot.plot_date(dates,allData[shift + ' Avg'], 'b-')
            pyplot.xlabel( 'Date (MT) ')
            pyplot.ylabel( 'Average Count' )
            pyplot.title( room + ' ' + shift + ' Averages for ' + particleSize + ' um Counts' )
            pyplot.savefig( room + particleSize + 'Avg' + shift[:-6] + '.png')

            pyplot.set_yscale('log')
            pyplot.title( room + ' ' + shift + ' Averages for ' + particleSize + ' um Counts Log Scale' )
            pyplot.savefig( room + particleSize + 'Avg' + shift[:-6] + '.png')

        print 'Plotting and saving baselines'   
        for shift in ['Day Shift','Night Shift','Empty Lab']:
            pyplot.figure(num=None, figsize=(16,9), dpi=100, facecolor='w', edgecolor='k')
            pyplot.plot_date(dates,allData[shift + ' Base'], 'b-')
            pyplot.xlabel( 'Date (MT)' )
            pyplot.ylabel( 'Baseline' )
            pyplot.title( room + ' ' + shift + ' Baselines for ' + particleSize + ' um Counts' )
            pyplot.savefig( room + particleSize + 'Base' + shift[:-6] + '.png')

            pyplot.set_yscale('log')
            pyplot.title( room + ' ' + shift + ' Baselines for ' + particleSize + ' um Counts Log Scale' )
            pyplot.savefig( room + particleSize + 'Base' + shift[:-6] + '.png')
开发者ID:rpetersburg,项目名称:mjdb-history-analysis,代码行数:27,代码来源:DataAnalysis.py

示例7: stockData

def stockData(stock):
    stock_price_url='http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv'    
    source_req=urllib2.Request(stock_price_url)
    source_response=urllib2.urlopen(source_req)
    source_code=source_response.read().decode()
    
    stock_data=[]
    split_source=source_code.split('\n')
    
    for  line in split_source:
        split_line=line.split(',')
        if len(split_line)==6:
            if 'values' not in line and 'labels' not in line:
                stock_data.append(line)
                
                
    date,closep,highp,lowp,openp,volume=np.loadtxt(stock_data,
                                              delimiter=',',
                                              unpack=True,
                                              converters={0: bytespdate2num('%Y%m%d')})
        
    plt.plot_date(date,closep,'-',label='price')
    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.title('Intresting Graph \n Check it out')
    plt.show()
开发者ID:rishikksh20,项目名称:matplotlib,代码行数:26,代码来源:basicFileDataLoadOperations.py

示例8: main

def main():
    # Request data from NIWAData
    response = get(URL, auth=HTTPBasicAuth(USERNAME, PASSWORD))

    # Successful requests will return HTTP status code 200
    if response.status_code != 200:
        raise Exception('Failed to request NIWAData: %s' % response.reason)

    # Parse the JSON response
    data = response.json()
    
    # You can retrieve the attributes about the dataset,
    analysis_time = data['data']['analysisTime']
    measure_mame = data['data']['measureName']
    name = data['data']['name']
    unit_symbol = data['data']['unitSymbol']
    # and also the values
    values = data['data']['values']
    pprint(data)

    # Plot the values, where x[0] has the datetime, and x[1] the current float value
    # Note that we are sorting the values by datetime, as they may
    # not always come sorted
    dates =  np.array([datetime.strptime(x[0], '%Y-%m-%dT%H:%M:%S%z') for x in sorted(values.items())])
    values = np.array([x[1] for x in sorted(values.items())])

    plt.plot_date(x=dates, y=values, fmt="r-")
    plt.title(name)
    plt.ylabel("Value in %s" % unit_symbol)
    plt.grid(True)
    plt.show()
开发者ID:niwa,项目名称:data-mashup,代码行数:31,代码来源:python_script.py

示例9: try_prod24h_before

def try_prod24h_before(columns=['Tout', 'vWind', 'vWindavg24', 'prod24h_before'], add_const=False, y=y):
    plt.close('all')
    X = all_data[columns]
    res = mlin_regression(y, X, add_const=add_const)
    timesteps = ens.gen_hourly_timesteps(dt.datetime(2015,12,17,1), dt.datetime(2016,1,15,0))
    
    plt.subplot(2,1,1)
    plt.plot_date(timesteps, y, 'b', label='Actual prodution')
    plt.plot_date(timesteps, res.fittedvalues, 'r', label='Weather model')
    prstd, iv_l, iv_u = wls_prediction_std(res)    
    plt.plot_date(timesteps, iv_u, 'r--', label='95% conf. int.')
    plt.plot_date(timesteps, iv_l, 'r--')
    plt.ylabel('MW')
    plt.legend(loc=2)
    plt.subplot(2,1,2)
    plt.plot_date(timesteps, res.resid, '-', label='Residual')
    plt.ylabel('MW')
    plt.legend()
    
    print "MAE = " + str(mae(res.resid))
    print "MAPE = " + str(mape(res.resid, y))
    print "RMSE = " + str(rmse(res.resid))
    
    print res.summary()
    
       
    return res
开发者ID:magndahl,项目名称:dmi_ensemble_handler,代码行数:27,代码来源:model_selection.py

示例10: plot_on_timeline

def plot_on_timeline(col, verbose=True):
    """Plots points on a timeline
    
    Parameters
    ----------
    col : np.array
    verbose : boolean
        iff True, display the graph

    Returns
    -------
    matplotlib.figure.Figure
        Figure containing plot

    
    Returns
    -------
    matplotlib.figure.Figure
    """
    col = utils.check_col(col)
    # http://stackoverflow.com/questions/1574088/plotting-time-in-python-with-matplotlib
    if is_nd(col):
        col = col.astype(datetime)
    dates = matplotlib.dates.date2num(col)
    fig = plt.figure()
    plt.plot_date(dates, [0] * len(dates))
    if verbose:
        plt.show()
    return fig
开发者ID:digideskio,项目名称:diogenes,代码行数:29,代码来源:display.py

示例11: plot

 def plot(self, widget):
     plt.xlabel('Date/Time')
     plt.ylabel('Temperature [%sF]' % self.degree_symbol)
     plt.title('Recorded temperature history')
     plt.grid(True)
     plt.plot_date(self.plotX, self.plotY, fmt='bo', tz=None, xdate=True)
     plt.show()
开发者ID:Myoldmopar,项目名称:Programs,代码行数:7,代码来源:main.py

示例12: graph_csv

def graph_csv(output_directory, csv_file, plot_title, output_filename, y_label=None, precision=None, graph_height="600", graph_width="1500", graph_type="line", graph_color="black"):
  """ Single metric graphing function using matplotlib"""
  if not os.path.getsize(csv_file):
    return False, None
  y_label = y_label or plot_title
  days, impressions = numpy.loadtxt(csv_file, unpack=True, delimiter=",", converters={ 0: convert_to_mdate})
  fig = plt.figure()
  fig.set_size_inches(float(graph_width) / 80, float(graph_height) / 80)
  if graph_type == "line":
    line_style = "-"
    marker = " "
  else:
    marker = "."
    line_style = None

  plt.plot_date(x=days, y=impressions, linestyle=line_style, marker=marker, color=graph_color)
  plt.title(plot_title)
  plt.ylabel(y_label)
  plt.grid(True)
  # Get current axis and its xtick labels
  labels = plt.gca().get_xticklabels()
  for label in labels:
    label.set_rotation(30)
  plot_file_name = os.path.join(output_directory, output_filename + ".png")
  fig.savefig(plot_file_name)
  plt.close()
  return True, None
开发者ID:haricharankr,项目名称:naarad,代码行数:27,代码来源:matplotlib_naarad.py

示例13: graph_csv_n

def graph_csv_n(output_directory, csv_file, plot_title, output_filename, columns, y_label=None, precision=None, graph_height="600", graph_width="1500", graph_type="line", graph_color="black"):
  if not os.path.getsize(csv_file):
    return False, None
  y_label = y_label or plot_title
  fig = plt.figure()
  fig.set_size_inches(float(graph_width) / 80, float(graph_height) / 80)
  if graph_type == "line":
    line_style = "-"
    marker = None
  else:
    marker = "."
    line_style = None

  np_data = numpy.loadtxt(csv_file, delimiter=",", converters={ 0: convert_to_mdate})
  np_data = np_data.transpose()
  xdata = np_data[0]
  ydata = [[]]*len(np_data)
  for i in range(1,len(np_data)):
    print i
    ydata[i-1] = numpy.asarray(np_data[i], dtype=numpy.float)
    plt.plot_date(x=xdata, y=ydata[i-1], linestyle=line_style, marker=marker, color=graph_color)
  plt.title(plot_title)
  plt.ylabel(y_label)
  plt.grid(True)
  # Get current axis and its xtick labels
  labels = plt.gca().get_xticklabels()
  for label in labels:
    label.set_rotation(30)
  plot_file_name = os.path.join(output_directory, output_filename + ".png")
  fig.savefig(plot_file_name)
  plt.close()
  return True, None
开发者ID:haricharankr,项目名称:naarad,代码行数:32,代码来源:matplotlib_naarad.py

示例14: graph_csv_new

def graph_csv_new(output_directory, csv_files, plot_title, output_filename, columns, y_label=None, precision=None, graph_height="600", graph_width="1500", graph_type="line", graph_color="black"):
  y_label = y_label or plot_title
  fig = plt.figure()
  fig.set_size_inches(float(graph_width) / 80, float(graph_height) / 80)
  if graph_type == "line":
    line_style = "-"
    marker = None
  else:
    marker = "."
    line_style = None
  colors = ['red', 'green', 'blue', 'yellow']
  i = 0 
  for csv_file in csv_files:
    days, impressions = numpy.loadtxt(csv_file, unpack=True, delimiter=",", converters={ 0: convert_to_mdate})
    plt.plot_date(x=days, y=impressions, linestyle=line_style, marker=marker, color=colors[i])
    i+=1
  plt.title(plot_title)
  plt.ylabel(y_label)
  plt.grid(True)
  # Get current axis and its xtick labels
  labels = plt.gca().get_xticklabels()
  for label in labels:
    label.set_rotation(30)
  plot_file_name = os.path.join(output_directory, output_filename + ".png")
  fig.savefig(plot_file_name)
  plt.close()
  return True, None
开发者ID:haricharankr,项目名称:naarad,代码行数:27,代码来源:matplotlib_naarad.py

示例15: recalc_final_result

def recalc_final_result(base_dir="/home/oferb/docs/train_project", experiment_id="webcam2", use_resized=False):
    import shutil

    if use_resized:
        frame_base = "frames_resized"
    else:
        frame_base = "frames"

    frames_dir = "%s/data/%s/%s" % (base_dir, experiment_id, frame_base)
    resized_files_dir = os.path.join(base_dir, "output", experiment_id, "frames_resized_done")
    resized_files_dir_times = os.path.join(base_dir, "output", experiment_id, "frames_resized_done_times")
    files = os.listdir(resized_files_dir)
    import re

    ids = []
    for filename in files:
        ids.append(re.findall(r"\d+", filename))

    img_times = []
    for an_id, filename in zip(ids, files):
        img_filename = utils.get_image_filename(frames_dir, int(an_id[0]), use_resized)
        img_times.append(dt.datetime.fromtimestamp(os.path.getctime(img_filename)))
        shutil.copy2(
            os.path.join(resized_files_dir, filename),
            os.path.join(resized_files_dir_times, "%s_%s" % (img_times[-1], filename)),
        )

    values = np.ones([len(img_times), 1])
    plt.plot_date(img_times, values)
开发者ID:hasadna,项目名称:OpenTrain,代码行数:29,代码来源:code_written_to_run_once.py


注:本文中的matplotlib.pyplot.plot_date函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。