我们从Python开源项目中,提取了以下14个代码示例,用于说明如何使用matplotlib.pyplot.plot_date()。
def get_stock(symbol): last_year_date = datetime.strftime(datetime.now() - relativedelta(years=1), "%Y-%m-%d") date = get_last_trading_date() url = requests.get('https://www.quandl.com/api/v3/datasets/WIKI/{}.json?start_date={}&end_date={}'.format(symbol, last_year_date, date)) json_dataset = url.json() json_data = json_dataset['dataset']['data'] dates = [] closing = [] for day in json_data: dates.append(datetime.strptime(day[0], "%Y-%m-%d")) closing.append(day[4]) plt.plot_date(dates, closing, '-') plt.title(symbol) plt.xlabel('Date') plt.ylable('Stock Price') plt.savefig('foo.png')
def animate(i): # updates the graph continuously with open('bitcoin_usd.csv') as csv_file: readcsv = csv.reader(csv_file, delimiter=',') xs = [] ys = [] for row in readcsv: if len(row) > 1: x, y = [float(s) for s in row] xs.append(dt.datetime.fromtimestamp(x)) ys.append(y) print(len(xs)) dates = matplotlib.dates.date2num(xs) fig.clear() plt.xlabel("timestamp") plt.ylabel("price of a bitcoin in usd") plt.plot_date(dates, ys, 'r.-') # this gives a line instead of scatter plot
def vykresli_spojnice(hodnoty, nadpis, jednotky): fig, ax = pyplot.subplots() pyplot.title(nadpis) pyplot.xlabel('datum') pyplot.ylabel(jednotky) x_hodnoty = [polozka[0] for polozka in hodnoty] y_hodnoty = [polozka[1] for polozka in hodnoty] pyplot.plot_date(x_hodnoty, y_hodnoty, 'b-', linewidth=0.5) pyplot.axhline(0, linewidth=0.2) # v jakých intervalech a jak mají vypadat popisky na ose X ax.xaxis.set_major_locator(YearLocator()) pyplot.show()
def plot_by_all( data ): x_vals = list() y_vals = list() for k in sorted(data): x_vals.append( datetime.datetime.strptime(k, key_pattern) ) y_vals.append(data[k]) x_vals2 = matplotlib.dates.date2num(x_vals) plt.clf() #plt.plot_date(x_vals2, y_vals) plt.plot(x_vals2, y_vals) plt.show()
def plot_by_interval(data, zamg_dfs = None): p_vals = {} # sort by year for k in sorted(data): v = data[k] d_obj = datetime.datetime.strptime(k, key_pattern) series_key = datetime.datetime.strftime(d_obj, "%Y") #data_key = datetime.datetime.strftime(d_obj, "%m-%d") p_vals.setdefault(series_key, dict()).setdefault("x_vals", list()).append(d_obj) p_vals.setdefault(series_key, dict()).setdefault("y_vals", list()).append(v) plt.clf() fig, axis = plt.subplots(nrows=len(p_vals)*2, sharex=False, sharey=False) a_iter = iter(axis) for k in sorted(p_vals): v = p_vals[k] ax = next(a_iter) y_vals = v["y_vals"] x_vals = matplotlib.dates.date2num(v["x_vals"]) ax.plot_date(x_vals, y_vals) # ax.plot(x_vals, y_vals) ax = next(a_iter) if zamg_dfs is not None and k in zamg_dfs: df = zamg_dfs[k] df['Wien Hohe Warte']['48,2486']['16,3564']['198.0']['Anhöhe']['Ebene']\ ['Lufttemperatur']['Lufttemperatur um 14 MEZ (°C)'].plot(ax=ax) plt.show()
def plot_pvals_filtered_dfs(p_vals, filtered_dfs, years = None): year_count = len(p_vals) if years is not None: i = 0 for k in p_vals: if not k in years: continue i += 1 year_count = i plt.clf() fig, axis = plt.subplots(nrows=year_count * 2, sharex=False, sharey=False) a_iter = iter(axis) for k in sorted(p_vals): if years is not None and not k in years: continue v = p_vals[k] ax = next(a_iter) y_vals = v["y_vals"] x_vals = matplotlib.dates.date2num(v["x_vals"]) ax.plot_date(x_vals, y_vals, marker='x') # ax.plot(x_vals, y_vals) ax = next(a_iter) if filtered_dfs is not None and k in filtered_dfs: df = filtered_dfs[k] df.plot(ax=ax, marker='+', linestyle='' ) plt.show()
def plot_tick_range_normalised(tick_path, range_start, range_end): if os.path.exists(tick_path) == False: print(tick_path + ' file doesnt exist') quit() date_cols = ['RateDateTime'] df = pd.read_csv(tick_path, usecols=['RateDateTime','RateBid','RateAsk']) start_index = tfh.find_index_closest_date(range_start, tick_path) end_index = tfh.find_index_closest_date(range_end, tick_path) # dont proceed if we didnt find indices if (start_index is None or end_index is None): print('start_index or end_index was None') quit() ticks_s = df.iloc[start_index:end_index] ticks = ((ticks_s['RateAsk'] + ticks_s['RateBid']) / 2.0) ticks_norm = (ticks - ticks.min()) / (ticks.max() - ticks.min()) dates_dt = [dt.datetime.strptime(str.split(x, '.')[0], '%Y-%m-%d %H:%M:%S') for x in ticks_s['RateDateTime'].values] dates = mdates.date2num(dates_dt) plt.plot_date(dates, ticks_norm, 'b-')
def plot_tick_range(tick_path, range_start, range_end): if os.path.exists(tick_path) == False: print(tick_path + ' file doesnt exist') quit() date_cols = ['RateDateTime'] df = pd.read_csv(tick_path, usecols=['RateDateTime','RateBid','RateAsk']) start_index = tfh.find_index_closest_date(range_start, tick_path) end_index = tfh.find_index_closest_date(range_end, tick_path) # dont proceed if we didnt find indices if (start_index is None or end_index is None): print('start_index or end_index was None') quit() ticks_s = df.iloc[start_index:end_index] ticks = (ticks_s['RateAsk'] + ticks_s['RateBid']) / 2.0 dates_dt = [dt.datetime.strptime(str.split(x, '.')[0], '%Y-%m-%d %H:%M:%S') for x in ticks_s['RateDateTime'].values] dates = mdates.date2num(dates_dt) #fig = plt.figure() #ax1 = plt.subplot2grid((1,1), (0,0)) plt.plot_date(dates, ticks, 'b-')
def main(): array_metrics=get_array_kpi() perfdatalist=array_metrics.get('perf_data') hostiolist = [] dtstimelist = [] readresponselist =[] print (perfdatalist) for perf_host in perfdatalist: hostiolist.append(perf_host.get('HostIOs')) readresponselist.append(perf_host.get('ReadResponseTime')) epochtime=(perf_host.get ('timestamp')) dtstime = round(epochtime/1000) dtstimelist.append(dtstime) dateconv=np.vectorize(dt.datetime.fromtimestamp) convtimelist =(dateconv(dtstimelist)) # print(convtimelist) fig, ax = plt.subplots(1) fig.autofmt_xdate() xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S') ax.xaxis.set_major_formatter(xfmt) plt.plot_date(convtimelist,hostiolist,'-') plt.plot_date(convtimelist, readresponselist, '-') plt.legend(['HostIOs', 'ReadResponseTime'], loc='upper left') plt.subplots_adjust(bottom=0.1) plt.xticks(rotation=25) plt.ylabel('Host IOs') plt.xlabel('Time') plt.title('Host IOs and Read Response times over the last Hour') plt.show()
def UMDmodelVcss(modelfile,cssfile,plotdir): ''' Plot comparison of model run to observed data ''' import matplotlib matplotlib.use('Agg') import numpy as np import sys from netCDF4 import Dataset import matplotlib.pyplot as plt from datetime import datetime # read in file and vars f = Dataset(modelfile,'r') wrfeta = f.variables['ZNU'][0][:] times = f.variables['Times'][:] wrflats = f.variables['XLAT'][0][:] wrflons = f.variables['XLONG'][0][:] var = f.variables['CO2_ANT'][:,0,:,:] z = 0 # assuming lowest level of model # College Park lat/lon UMD = [38.99,-76.94] UMDx,UMDy = findpoint(wrflats,wrflons,UMD[0],UMD[1]) # read in CO2 data from SENSE format date,time,co2css,ch4css,h2ocss = np.genfromtxt(cssfile,missing_values=-9999.00,filling_values=np.nan,usecols=(0,1,2,3,4),unpack=True) co2css[co2css==-9999]=np.nan # above doesn't work; explicitly define here tim = ["%8d%06d" % (date[t],time[t]) for t in range(len(date))] tim = [datetime.strptime(tim[t], "%Y%m%d%H%M%S") for t in range(len(tim))] # convert wrf times to datetime objects times = [''.join(times[t,:]) for t in range(len(times))] times = [datetime.strptime(times[t],"%Y-%m-%d_%H:%M:%S") for t in range(len(times))] # plot data plt.plot_date(times,var[:,UMDy,UMDx],color='red',label='WRF') plt.plot_date(tim,co2css,color='black',label='LGR') plt.ylim([380,430]) plt.legend() plt.savefig(plotdir+'/UMDLGRvWRF.png')
def generateActivityInfoForGroup(self, groupName): timestampNow = int(time()) timestampYesterday = timestampNow - self.timestampSubtract records = list(self.coll.find({ 'to': groupName, 'timestamp': { '$gt': timestampYesterday } }).sort([ ('timestamp', DESCENDING) ])) fn = self.generateTmpFileName() # Get histogram for activity hist, bins = np.histogram([ x['timestamp'] for x in records ], bins=24) center = (bins[:-1] + bins[1:]) / 2 datex = [ datetime.fromtimestamp(x) for x in center ] pp.figure(figsize=(6,14)) ax = pp.subplot(2, 1, 1) pp.plot_date(datex, hist, '.-') pp.gcf().autofmt_xdate() pp.xlabel(u'??????', fontproperties=self.prop) pp.ylabel(u'??????', fontproperties=self.prop) ax.xaxis.set_major_formatter(DateFormatter('%m-%d %H:%M')) # Get bar chart for active users pieDat = Counter([ x['from'] for x in records ]) pieDatSorted = sorted([ (k, pieDat[k]) for k in pieDat ],key=lambda x: x[1], reverse=True) if len(pieDatSorted) > self.maxActivityInfoCount: pieDatSorted = pieDatSorted[:self.maxActivityInfoCount] ax = pp.subplot(2, 1, 2) width = 0.7 x = np.arange(len(pieDatSorted)) + width xText = [ xx[0] for xx in pieDatSorted ] y = [ xx[1] for xx in pieDatSorted ] pp.bar(x, y, width) a = pp.gca() a.set_xticklabels(a.get_xticks(), { 'fontProperties': self.prop }) pp.xticks(x, xText, rotation='vertical') pp.xlabel(u'??', fontproperties=self.prop) pp.ylabel(u'24?????', fontproperties=self.prop) ax.set_xlim([ 0, len(xText) + 1 - width ]) pp.margins(0.2) pp.savefig(fn) return fn
def plot_lamptemp_ts(ax, data): """ Plots the lamp temperature """ plt.setp(ax.get_xticklabels(), visible=False) ax.set_ylabel('temp (degC)') ax.set_ylim(34, 38) ax.plot_date(data['mpl_timestamp'][:, 0].ravel(), data['AL52CO_lamptemp'][:].ravel(), '-', color='#ff4d4d') ax.text(0.05, 0.98, 'Lamp Temp', axes_title_style, transform=ax.transAxes) return ax
def make_efficiency_date( total_data, avg_data, f_name, title=None, x_label=None, y_label=None, x_ticks=None, y_ticks=None): fig = plt.figure() if title is not None: plt.title(title, fontsize=16) if x_label is not None: plt.ylabel(x_label) if y_label is not None: plt.xlabel(y_label) v_date = [] v_val = [] for data in total_data: dates = dt.date2num(datetime.datetime.strptime(data[0], '%H:%M')) to_int = round(float(data[1])) plt.plot_date(dates, data[1], color=plt.cm.brg(to_int)) for data in avg_data: dates = dt.date2num(datetime.datetime.strptime(data[0], '%H:%M')) v_date.append(dates) v_val.append(data[1]) plt.plot_date(v_date, v_val, "^y-", label='Average') plt.legend() plt.savefig(f_name) plt.close(fig)
def plot_tick_range(tick_path, range_start, range_end): if os.path.exists(tick_path) == False: print(tick_path + ' file doesnt exist') quit() date_cols = ['RateDateTime'] df = pd.read_csv(tick_path, usecols=['RateDateTime','RateBid','RateAsk']) start_index = tfh.find_index_closest_date(range_start, tick_path) end_index = tfh.find_index_closest_date(range_end, tick_path) # dont proceed if we didnt find indices if (start_index is None or end_index is None): print('start_index or end_index was None') quit() ticks_s = df.iloc[start_index:end_index] ticks = (ticks_s['RateAsk'] + ticks_s['RateBid']) / 2.0 dates_dt = [dt.datetime.strptime(str.split(x, '.')[0], '%Y-%m-%d %H:%M:%S') for x in ticks_s['RateDateTime'].values] dates = mdates.date2num(dates_dt) #fig = plt.figure() #ax1 = plt.subplot2grid((1,1), (0,0)) plt.plot_date(dates, ticks, 'b-') # candlestick_ohlc(ax1, ohlc, width=0.0004, colorup='#77d879', colordown='#db3f3f') # for label in ax1.xaxis.get_ticklabels(): # label.set_rotation(45) # ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M')) # ax1.xaxis.set_major_locator(mticker.MaxNLocator(10)) # ax1.grid(True) # plt.xlabel('Date') # plt.ylabel('Price') # plt.title(ohlc_path) # plt.legend() # plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0) #plt.show() # plot_ohlc_range