我们从Python开源项目中,提取了以下26个代码示例,用于说明如何使用matplotlib.pyplot.autoscale()。
def _plot(xvec, yvec, title='', xlabel='', ylabel='', maxplot=10, **kwargs): """Simple plot""" def _subplot(yvec): dimLen = len(yvec.shape) if dimLen == 1: X = [yvec] elif dimLen == 2: X = [n.mean(yvec, 1)] elif dimLen == 3: X = [n.mean(yvec[k, :, :], 1) for k in range(0, yvec.shape[0])] [plt.plot(xvec, k, label=str(i), **kwargs) for i, k in enumerate(X)] ax = plt.gca() ax.set_xlabel(xlabel), ax.set_ylabel(ylabel) ax.set_title(title), ax.legend() plt.autoscale(tight=True) return ax return _sub(yvec, _subplot, maxplot=maxplot)
def plot(self, saveDir=None): # for i in range(3): # plt.plot(self.sampleTimes, self.data[:,i]) plt.figure() plt.autoscale(tight=True) plt.plot(self.sampleTimes, self.data) minVal = np.min(self.data) - .2 maxVal = np.max(self.data) + .2 for time in self.gestureTimes: plt.plot([time, time], [minVal, maxVal], color='k', linestyle='--', linewidth=1) plt.title(self.gestureLabel) if saveDir: ensureDirExists(saveDir) fileName = "%s_%d" % (self.gestureLabel, self.id) fileName = join(saveDir, fileName) plt.savefig(fileName) # else: # plt.show() # TODO uncomment
def get_plot_buf(x, clusters, mu, logstd, true_mu, true_logstd): N = x.shape[0] K = mu.shape[0] fig = plt.figure() # print(clusters.shape) # print(x.shape) ax = fig.add_subplot(111, aspect='auto') plt.scatter(x[:, 0], x[:, 1], c=clusters, s=50) # print(mu, logstd) ells = [Ellipse(xy=mean_, width=6*np.exp(logstd_[0]), height=6*np.exp(logstd_[1]), angle=0, facecolor='none', zorder=10, edgecolor='g', label='predict' if i==0 else None) for i, (mean_, logstd_) in enumerate(zip(mu, logstd))] true_ells = [Ellipse(xy=mean_, width=6*np.exp(logstd_[0]), height=6*np.exp(logstd_[1]), angle=0, facecolor='none', zorder=10, edgecolor='r', label='true' if i==0 else None) for i,(mean_, logstd_) in enumerate(zip(true_mu, true_logstd))] # print(ells[0]) [ax.add_patch(ell) for ell in ells] [ax.add_patch(true_ell) for true_ell in true_ells] ax.legend(loc='best') ax.set_title('N={},K={}'.format(N, K)) plt.autoscale(True) buf = io.BytesIO() fig.savefig(buf, format='png') plt.close() buf.seek(0) return buf
def __init__(self, size=(600,350)): streams = resolve_byprop('name', 'bci', timeout=2.5) try: self.inlet = StreamInlet(streams[0]) except IndexError: raise ValueError('Make sure stream name=bci is opened first.') self.running = True self.ProcessedSig = [] self.SecondTimes = [] self.count = -1 self.sampleCount = self.count self.maximum = 0 self.minimum = 0 plt.ion() plt.hold(False) self.lineHandle = plt.plot(self.SecondTimes, self.ProcessedSig) plt.title("Live Stream EEG Data") plt.xlabel('Time (s)') plt.ylabel('mV') #plt.autoscale(True, 'y', tight = True) plt.show() #while(1): #secondTimes.append(serialData[0]) #add time stamps to array 'timeValSeconds' #floatSecondTimes.append(float(serialData[0])/1000000) # makes all second times into float from string #processedSig.append(serialData[6]) #add processed signal values to 'processedSig' #floatProcessedSig.append(float(serialData[6]))
def generate_graph(): with open('../../data/netinterface.dat', 'r') as csvfile: data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True) for row in data_source: # [0] column is a time column # Convert to datetime data type a = datetime.strptime((row[0]),'%H:%M:%S') x.append((a)) # The remaining columns contain data r_kb.append(row[4]) s_kb.append(row[5]) # Plot lines plt.plot(x,r_kb, label='Kilobytes received per second', color='#009973', antialiased=True) plt.plot(x,s_kb, label='Kilobytes sent per second', color='#b3b300', antialiased=True) # Graph properties plt.xlabel('Time',fontstyle='italic') plt.ylabel('Kb/s',fontstyle='italic') plt.title('Network statistics') plt.grid(linewidth=0.4, antialiased=True) plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.18), ncol=2, fancybox=True, shadow=True) plt.autoscale(True) # Graph saved to PNG file plt.savefig('../../graphs/netinterface.png', bbox_inches='tight') #plt.show() # ====================== # MAIN # ======================
def generate_graph(): with open('../../data/cpu.dat', 'r') as csvfile: data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True) for row in data_source: # [0] column is a time column # Convert to datetime data type a = datetime.strptime((row[0]),'%H:%M:%S') x.append((a)) # The remaining columns contain data user_cpu.append(row[2]) system_cpu.append(row[4]) idle_cpu.append(row[7]) # Plot lines plt.plot(x,user_cpu, label='User %', color='g', antialiased=True) plt.plot(x,system_cpu, label='System %', color='r', antialiased=True) plt.plot(x,idle_cpu, label='Idle %', color='b', antialiased=True) # Graph properties plt.xlabel('Time',fontstyle='italic') plt.ylabel('CPU %',fontstyle='italic') plt.title('CPU usage graph') plt.grid(linewidth=0.4, antialiased=True) plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True) plt.autoscale(True) # Graph saved to PNG file plt.savefig('../../graphs/cpu.png', bbox_inches='tight') #plt.show() # ====================== # MAIN # ======================
def generate_graph(): with open('../../data/swap.dat', 'r') as csvfile: data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True) for row in data_source: # [0] column is a time column # Convert to datetime data type a = datetime.strptime((row[0]),'%H:%M:%S') x.append((a)) # The remaining columns contain data swap_free.append(str(int(row[1])/1024)) swap_used.append(str(int(row[2])/1024)) # Plot lines plt.plot(x,swap_used, label='Used', color='r', antialiased=True) plt.plot(x,swap_free, label='Free', color='g', antialiased=True) # Graph properties plt.xlabel('Time',fontstyle='italic') plt.ylabel('SWAP (MB)',fontstyle='italic') plt.title('SWAP usage graph') plt.grid(linewidth=0.4, antialiased=True) plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True) plt.autoscale(True) # Graph saved to PNG file plt.savefig('../../graphs/swap.png', bbox_inches='tight') #plt.show() # ====================== # MAIN # ======================
def generate_graph(): with open('../../data/ram.dat', 'r') as csvfile: data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True) for row in data_source: # [0] column is a time column # Convert to datetime data type a = datetime.strptime((row[0]),'%H:%M:%S') x.append((a)) # The remaining columns contain data free_mem.append(str((int(row[1])/1024)+(int(row[4])/1024)+(int(row[5])/1024))) used_mem.append(str((int(row[2])/1024)-(int(row[4])/1024)-(int(row[5])/1024))) buffer_mem.append(str(int(row[4])/1024)) cached_mem.append(str(int(row[5])/1024)) # Plot lines plt.plot(x,free_mem, label='Free', color='g', antialiased=True) plt.plot(x,used_mem, label='Used', color='r', antialiased=True) plt.plot(x,buffer_mem, label='Buffer', color='b', antialiased=True) plt.plot(x,cached_mem, label='Cached', color='c', antialiased=True) # Graph properties plt.xlabel('Time',fontstyle='italic') plt.ylabel('Memory (MB)',fontstyle='italic') plt.title('RAM usage graph') plt.grid(linewidth=0.4, antialiased=True) plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True) plt.autoscale(True) # Graph saved to PNG file plt.savefig('../../graphs/ram.png', bbox_inches='tight') #plt.show() # ====================== # MAIN # ======================
def generate_graph(): with open('../../data/sockets.dat', 'r') as csvfile: data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True) for row in data_source: # [0] column is a time column # Convert to datetime data type a = datetime.strptime((row[0]),'%H:%M:%S') x.append((a)) # The remaining columns contain data t_tcp.append(str((int(row[2]))+(int(row[6])))) t_tcp_use.append(row[2]) t_udp_use.append(row[3]) t_tcp_time_wait.append(row[6]) # Plot lines plt.plot(x,t_tcp, label='Total TCP sockets', color='#ff9933', antialiased=True) plt.plot(x,t_tcp_use, label='TCP sockets in use', color='#66ccff', antialiased=True) plt.plot(x,t_udp_use, label='UDP sockets in use', color='#009933', antialiased=True) plt.plot(x,t_tcp_time_wait, label='TCP sockets in TIME WAIT state', color='#cc3300', antialiased=True) # Graph properties plt.xlabel('Time',fontstyle='italic') plt.ylabel('Number of sockets',fontstyle='italic') plt.title('Sockets') plt.grid(linewidth=0.4, antialiased=True) plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.20), ncol=2, fancybox=True, shadow=True) plt.autoscale(True) # Graph saved to PNG file plt.savefig('../../graphs/sockets.png', bbox_inches='tight') #plt.show() # ====================== # MAIN # ======================
def generate_graph(): with open('../../data/loadaverage.dat', 'r') as csvfile: data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True) for row in data_source: # [0] column is a time column # Convert to datetime data type a = datetime.strptime((row[0]),'%H:%M:%S') x.append((a)) # The remaining columns contain data m1.append(row[3]) m5.append(row[4]) m15.append(row[5]) # Plot lines plt.plot(x,m1, label='1 min', color='g', antialiased=True) plt.plot(x,m5, label='5 min', color='r', antialiased=True) plt.plot(x,m15, label='15 min', color='b', antialiased=True) # Graph properties plt.xlabel('Time',fontstyle='italic') plt.ylabel('Load average',fontstyle='italic') plt.title('Load average graph') plt.grid(linewidth=0.4, antialiased=True) plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True) plt.autoscale(True) # Graph saved to PNG file plt.savefig('../../graphs/loadaverage.png', bbox_inches='tight') #plt.show() # ====================== # MAIN # ======================
def generate_graph(): with open('../../data/proc.dat', 'r') as csvfile: data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True) for row in data_source: # [0] column is a time column # Convert to datetime data type a = datetime.strptime((row[0]),'%H:%M:%S') x.append((a)) # The remaining columns contain data procs_per_second.append(row[1]) # Plot lines plt.plot(x,procs_per_second, label='Processes created per second', color='r', antialiased=True) # Graph properties plt.xlabel('Time',fontstyle='italic') plt.ylabel('Processes',fontstyle='italic') plt.title('Processes created per second graph') plt.grid(linewidth=0.4, antialiased=True) plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True) plt.autoscale(True) # Graph saved to PNG file plt.savefig('../../graphs/proc.png', bbox_inches='tight') #plt.show() # ====================== # MAIN # ======================
def generate_graph(): with open('../../data/iotransfer.dat', 'r') as csvfile: data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True) for row in data_source: # [0] column is a time column # Convert to datetime data type a = datetime.strptime((row[0]),'%H:%M:%S') x.append((a)) # The remaining columns contain data b_read_second.append(row[4]) b_written_second.append(row[5]) # Plot lines plt.plot(x,b_read_second, label='Blocks read per second', color='r', antialiased=True) plt.plot(x,b_written_second, label='Blocks written per second', color='g', antialiased=True) # Graph properties plt.xlabel('Time',fontstyle='italic') plt.ylabel('Blocks per second',fontstyle='italic') plt.title('IO Transfer graph') plt.grid(linewidth=0.4, antialiased=True) plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True) plt.autoscale(True) # Graph saved to PNG file plt.savefig('../../graphs/iotransfer.png', bbox_inches='tight') #plt.show() # ====================== # MAIN # ======================
def generate_graph(): with open('../../data/proc.dat', 'r') as csvfile: data_source = csv.reader(csvfile, delimiter=' ', skipinitialspace=True) for row in data_source: # [0] column is a time column # Convert to datetime data type a = datetime.strptime((row[0]),'%H:%M:%S') x.append((a)) # The remaining columns contain data contextsw_per_second.append(row[2]) # Plot lines plt.plot(x,contextsw_per_second, label='Context switches performed per second', color='r', antialiased=True) # Graph properties plt.xlabel('Time',fontstyle='italic') plt.ylabel('Context switches',fontstyle='italic') plt.title('Context switches') plt.grid(linewidth=0.4, antialiased=True) plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=2, fancybox=True, shadow=True) plt.autoscale(True) # Graph saved to PNG file plt.savefig('../../graphs/contextsw.png', bbox_inches='tight') #plt.show() # ====================== # MAIN # ======================
def plot_pic(pic): #### 1 STEEM - exchange plt.figure(pic["num"]) plt.bar(pic["xtics"] - 0.2, pic["df1"], width=0.4, color="blue", label=pic["x_legend"]) plt.bar(pic["xtics"] + 0.2, pic["df2"], width=0.4, color="lightblue", label=pic["y_legend"]) plt.legend(loc = "best") if "Monthly" in pic["title"]: x_ticks = [] for mon in pic["df1"].index.values: x_ticks.append(monthes_list[mon - 1]) plt.xticks(pic["xtics"], x_ticks) else: plt.xticks(pic["xtics"], pic["df1"].index.values) plt.title(pic["title"]) plt.xlabel(pic["x_label"]) plt.ylabel(pic["y_label"]) plt.autoscale(tight=True) plt.subplots_adjust(bottom = pic["bottom"]) plt.savefig(img_path + pic["fname"]) # STEEM flow rate
def plot_models(x, y, models, fname, mx=None, ymax=None, xmin=None): plt.figure(num=None, figsize=(8, 6)) plt.clf() plt.scatter(x, y, s=10) plt.title("Web traffic over the last month") plt.xlabel("Time") plt.ylabel("Hits/hour") plt.xticks( [w * 7 * 24 for w in range(10)], ['week %i' % w for w in range(10)]) if models: if mx is None: mx = sp.linspace(0, x[-1], 1000) for model, style, color in zip(models, linestyles, colors): # print "Model:",model # print "Coeffs:",model.coeffs plt.plot(mx, model(mx), linestyle=style, linewidth=2, c=color) plt.legend(["d=%i" % m.order for m in models], loc="upper left") plt.autoscale(tight=True) plt.ylim(ymin=0) if ymax: plt.ylim(ymax=ymax) if xmin: plt.xlim(xmin=xmin) plt.grid(True, linestyle='-', color='0.75') plt.savefig(fname) # first look at the data
def drawimg(X, y, W, filename=None, title=''): """ Save data plus boundary to filname. """ if not filename: _, filename = tempfile.mkstemp(prefix='nntour-') plt.clf() pos = np.array([x[1:] for i, x in enumerate(X) if y[i] == 1]) neg = np.array([x[1:] for i, x in enumerate(X) if y[i] == -1]) axes = plt.gca() axes.set_xlim([-2, 2]) axes.set_ylim([-2, 2]) axes.get_xaxis().set_visible(False) axes.get_yaxis().set_visible(False) plt.title(title) plt.autoscale(enable=False) plt.scatter(pos[:, 0], pos[:, 1], color='b') plt.scatter(neg[:, 0], neg[:, 1], color='r') xb = np.linspace(-2, 2, 1000) yb = (-W[0] - W[1] * xb) / W[2] plt.plot(xb, yb, '-', color='k') plt.savefig(filename)
def plot(self): fig().plot(); #jus' closes a previous plot self.format(); d=self.data() plt.plot(d['trn'],label='training') po=plt.plot(d['vld'],label='validation')[0] po.axes.set_yscale('log') po.axes.get_xaxis().set_label_text('epoch') po.axes.get_yaxis().set_label_text('$L$') plt.legend(loc='upper right') plt.autoscale(tight=True) plt.tight_layout(pad=0.05) return po
def __init__(self): #fig = plt.figure('Figure Simulator') #self.fig2 = plt.subplot(122, projection = 'polar') #plt.title('Polar') #fig1,ax = fig.add_subplot(111) #fig1 = plt.subplot(111) fig, ax = plt.subplots(sharex=True, sharey=True) ax.set_title('Figure Simulator') ax.axis([-10,10,-10,10]) ax.set_anchor('C') ax.set_title('Mouse Input') ax.set_xlabel('Pose X') ax.set_ylabel('Pose Y') ax.set_xlim(-10,10) ax.set_ylim(-10,10) ax.set_autoscalex_on(False) ax.set_autoscaley_on(False) ax.grid(True) for direction in ["left", "right", "bottom", "top"]: ax.spines[direction].set_visible(False) fig.canvas.mpl_connect('figure_enter_event', enter_figure) fig.canvas.mpl_connect('figure_leave_event', leave_figure) fig.canvas.mpl_connect('axes_enter_event', enter_axes) fig.canvas.mpl_connect('axes_leave_event', leave_axes) fig.canvas.mpl_connect('button_press_event', OnClick) fig.canvas.mpl_connect('button_release_event', OnRelease) timer = fig.canvas.new_timer(interval=100) timer.add_callback(timer_callback, ax) timer.start() plt.autoscale(enable=False, axis='both', tight=None)
def plotDf(df, xlabel="Classifier", ylabel="Dataset", title=None, symmetricAboutMean=False, cmap='RdBu'): data = df.values if symmetricAboutMean: mean = data.mean() bound = max(abs(data.max() - mean), abs(data.min() - mean)) lower = mean - bound upper = mean + bound else: lower = data.min() upper = data.max() plt.rcParams["font.size"] = 17 # plt.figure(figsize=(10, 10)) fig, ax = plt.subplots(figsize=(10, 10)) p = ax.pcolormesh(data, cmap=cmap, vmin=lower, vmax=upper) plt.colorbar(p, ax=ax) plt.yticks(np.arange(0.5, len(df.index), 1), df.index) plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns, fontsize=13, rotation=80) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.autoscale(True, tight=True) plt.tight_layout() plt.show()
def _graph_lsl(self): while self.running: # initial run self.sample, self.timestamp = self.inlet.pull_sample(timeout=5) #if self.timeBuffer[0] == 0.0: # self.timeBuffer = collections.deque([self.timestamp] * self._bufsize, self._bufsize) # time correction to sync to local_clock() try: if self.timestamp is not None and self.sample is not None: self.timestamp = self.timestamp + self.inlet.time_correction(timeout=5) except TimeoutError: pass self.SecondTimes.append(self.timestamp) #add time stamps to array 'timeValSeconds' #print(abs(self.sample[3])/1000) self.ProcessedSig.append(abs(self.sample[3])/1000) #add processed signal values to 'processedSig' if(abs(self.sample[3]/1000) > self.maximum): self.maximum = abs(self.sample[3]/1000) if(abs(self.sample[3]/1000) < self.minimum): self.minimum = abs(self.sample[3]/1000) self.sampleCount = self.sampleCount + 1 self.count = self.count + 1 #plt.show() if((self.count % 20 == 0) and (self.count != 0)): #every 20 samples (ie ~ 0.2 ms) is when plot updates. Change the sample number (ie 20) to modify frequency at which plot updates #if(self.count == 20): self.count = -1 self.lineHandle[0].set_ydata(self.ProcessedSig) self.lineHandle[0].set_xdata(self.SecondTimes) #plt.xlim(0, 5) plt.xlim(self.SecondTimes[0], self.SecondTimes[-1]) plt.ylim(self.minimum - 0.75, self.maximum + 0.75) #plt.ylim(0, 20) #plt.ylim(0, 10) #elf.ax.set_autoscaley_on(True) #plt.autoscale(enable=True, axis='y', tight=True) plt.pause(0.01) if(self.sampleCount >= 511): #shows up to 2 seconds of data (512 samples = 2s of data given a 256 Hz sampling freq by the BCI) self.ProcessedSig.pop(0) self.SecondTimes.pop(0) plt.pause(0.01) print('closing graphing utility') self.inlet.close_stream()
def heatmap(xlabels=None, ylabels=None, weights=None, output_file=None): """ Draw a heatmap showing the alignment between two sequences. :param xlabels: input words :param ylabels: output words :param weights: numpy array of shape (len(xlabels), len(ylabels)) :param output_file: write the figure to this file, or show it into a window if None """ from matplotlib import pyplot as plt weights *= 10 xlabels = xlabels or [] ylabels = ylabels or [] fig, ax = plt.subplots() plt.autoscale(enable=True, axis='x', tight=True) #ax.pcolor(weights, cmap=plt.cm.Greys) ax.pcolor(weights, cmap=plt.cm.Greys) ax.set_frame_on(False) # plt.colorbar(mappable=heatmap_) # put the major ticks at the middle of each cell ax.set_yticks(np.arange(weights.shape[0]) + 0.5, minor=False) ax.set_xticks(np.arange(weights.shape[1]) + 0.5, minor=False) ax.invert_yaxis() ax.xaxis.tick_top() ax.set_xticklabels(xlabels, minor=False) ax.set_yticklabels(ylabels, minor=False) ax.tick_params(axis='both', which='both', length=0) plt.xticks(rotation=90, fontsize=20) plt.xticks(fontsize=18) plt.yticks(fontsize=18) plt.tight_layout() plt.subplots_adjust(wspace=0, hspace=0) # ax.set_aspect('equal') ax.grid(True) xsize = max(2.0 + len(xlabels) / 3, 8.0) ysize = max(2.0 + len(ylabels) / 3, 8.0) fig.set_size_inches(xsize, ysize, forward=True) if output_file is None: plt.show() else: plt.savefig(output_file)
def line_2subplots(): """ Creates a split plot with one set of x axis labels and two subplots. """ # Save data to redraw plot later save_data('line_2subplots') # set the screen title, size, density fig = plt.figure(title,graph_dimensions,graph_dpi) # do the plot # top half of the graph plot_number 1 nrows = 2 ncols = 1 plot_number = 1 ax = plt.subplot(nrows,ncols,plot_number) plt.title(title) plt.ylabel(ylabel1) plt.grid(which="major") red = 'r' plt.plot(xdatetimes,ylists[0],red) plt.autoscale(tight=True) fig.autofmt_xdate() ax.fmt_xdata = mdates.DateFormatter('%m/%d/%Y %H:%M') datetimefmt = mdates.DateFormatter('') ax.xaxis.set_major_formatter(datetimefmt) # bottom half of the graph plot_number 2 plot_number = 2 ax = plt.subplot(nrows,ncols,plot_number) plt.ylabel(ylabel2) plt.grid(which="major") green='g' plt.plot(xdatetimes,ylists[1],green) plt.autoscale(tight=True) fig.autofmt_xdate() ax.fmt_xdata = mdates.DateFormatter('%m/%d/%Y %H:%M') loc=mdates.AutoDateLocator() datetimefmt = mdates.AutoDateFormatter(loc) ax.xaxis.set_major_formatter(datetimefmt) ax.xaxis.set_major_locator(loc) # subplots_adjust settings vleft = 0.07 # the left side of the subplots of the figure vright = 0.97 # the right side of the subplots of the figure # vbottom = 0.15 # the bottom of the subplots of the figure vbottom = 0.10 # the bottom of the subplots of the figure vtop = 0.95 # the top of the subplots of the figure vwspace = 0.0 # the amount of width reserved for blank space between subplots vhspace = 0.08 # the amount of height reserved for white space between subplots plt.subplots_adjust(left=vleft,right=vright,bottom=vbottom,top=vtop,wspace=vwspace,hspace=vhspace) fileorscreen(title+'.png') return
def plot_timeseries(kwargs): """ Plot different timeseries in list vs list optional of target timeseries """ timeseries = kwargs.get('timeseries') #list(array([timesteps, 3])) contains min, max, mean filename = kwargs.get('filename') targets = kwargs.get('targets', []) ts_labels = kwargs.get('ts_labels', None) suptitle = kwargs.get('suptitle', '') title = kwargs.get('title', '') alpha = kwargs.get('alpha', 1.) balpha = kwargs.get('balpha', alpha/4) linewidth = kwargs.get('linewidth', 1.) linestyle_lines = kwargs.get('linestyle_lines', ['-', ':']) markes_lines = kwargs.get('markes_lines', ['', '']) fig, ax = pl.subplots(figsize=kwargs.get('figsize', [8,5])) if not isinstance(timeseries, list): timeseries = [timeseries] colors = [pl.cm.brg(i) for i in np.linspace(0, 0.9, len(timeseries))] for t_i, ts in enumerate(timeseries): ax.fill_between(np.arange(len(ts[:,1])), ts[:,1], ts[:,0], facecolor=colors[t_i], alpha=balpha, linestyle=':') ax.plot(ts[:,2], linestyle=linestyle_lines[ts_labels[t_i].endswith('(train)')], alpha=alpha, label=str(ts_labels[t_i]), linewidth=linewidth, color=colors[t_i-ts_labels[t_i].endswith('(train)')], marker=markes_lines[ts_labels[t_i].endswith('(train)')]) color = kwargs.get('target_color', 'r') for (t_i, tar) in enumerate(targets): line_styles = '-' ax.plot(tar, linestyle=line_styles, color=color, alpha=alpha, label='target', linewidth=0.6) #pl.axvline(x=118, linestyle='-.', color='r') ax.set_xlabel(kwargs.get('xlabel', '')) ax.set_ylabel(kwargs.get('ylabel', '')) if kwargs.get('ylim', None) is not None: pl.ylim(kwargs.get('ylim')) pl.grid() pl.axis('on') pl.suptitle(suptitle) pl.title(title)#, fontsize=kwargs.get('fontsize', 10)) pl.autoscale(enable=True) pl.tight_layout() # Shrink current axis by 20% box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) leg = ax.legend(loc='center left', prop=kwargs.get('legend_props', {'size':10}), bbox_to_anchor=(1, 0.5)) # make lines wider for legobj in leg.legendHandles: legobj.set_linewidth(3.0) pl.savefig(filename) return 0
def timeseries_prediction_vs_target(kwargs): """ Plot different timeseries in list vs list of target timeseries """ predictions = kwargs.get('predictions') #2dims (timesteps, predictions) targets = kwargs.get('targets') filename = kwargs.get('filename') suptitle = kwargs.get('suptitle', '') title = kwargs.get('title', '') alpha = kwargs.get('alpha', 1.) fig, ax = pl.subplots(figsize=[20,20]) linestyle_lines = '-' for (n_i, n) in enumerate(np.arange(predictions.shape[1])): if n_i == 0: colors = [pl.cm.brg(i) for i in np.linspace(0, 0.9, predictions.shape[1]-1)] #ax.set_color_cycle(colors) #depreciated with matplotlib 1.5 ax.set_prop_cycle(cycler('color', colors)) else: ax.plot(predictions[:,n], linestyle=linestyle_lines, alpha=alpha, label=str(n), linewidth=0.4) ax.plot(predictions[:,0], linestyle='-', alpha=alpha, label='prediction', color='k', linewidth=0.6) color='r' for (t_i, tar) in enumerate(targets): line_styles = '-' ax.plot(tar, linestyle=line_styles, color=color, alpha=alpha, label='target', linewidth=0.6) color='b' pl.axvline(x=118, linestyle='-.', color='r') ax.set_xlabel('timestep') ax.set_ylabel('activations') pl.grid() pl.axis('on') pl.suptitle(suptitle) pl.title(title, fontsize=10) pl.autoscale(enable=True) pl.savefig(filename) return 0
def run(num_tests): lab = Labyrinth(file='5x5.csv') ga_won = 0 gens = [] fitness = [] print('Running GA tests ({})'.format(num_tests)) for i in range(num_tests): print('Test ?{} - '.format(i), end='') ga = GeneticAlgorithm(lab, elitism_num=2, num_population=100, max_iter=150, crossover_pts=1, roulette_mult=2, max_moves_mult=2, file_name='try_{}'.format(i)) ga.save_data() if ga.found_winner: print('Found winner') ga_won += 1 gens.append(ga.max_gen) fitness.append(ga.pop) else: gens.append(0) fitness.append(ga.pop) print('Didn\'t find winner') fitness = np.array(fitness) print(fitness.shape) print('Stats:\n? won: \t{}\n% won: \t{}\n? gens req (avg): \t{}\nAvg fitness: \t{}' .format(ga_won, 100 * ga_won / num_tests, np.mean(gens), np.mean(fitness[:, :, 1]))) # num_subplots = 0 # plt.autoscale = True # f, ax = plt.subplot(2, len(fitness)) # # for i, pop in enumerate(fitness[:, :, 1]): # plt.subplot() # ax[0][i].plot(pop[:, 1]) ax_gens = plt.subplot(211) ax_gens.set_ylim([math.ceil(min(gens) - 0.5 * (max(gens) - min(gens))), math.ceil(min(gens) + 0.5 * (max(gens) - min(gens)))]) plt.bar(np.arange(num_tests), width=0.35, height=gens, color='m') print('Running random search tests ({})'.format(num_tests)) iterations = [] rand_won = 0 for i in range(num_tests): print('Test ?{} - '.format(i), end='') ga = GeneticAlgorithm(lab, selection='random', min_moves_mult=0.5, max_moves_mult=2, file_name='rng_try_{}'.format(i)) if ga.found_winner: print('Found winner') rand_won += 1 else: print('Didn\'t find winner') iterations.append(ga.max_gen) print('Stats:\n? won: \t{}\n% won: \t{}\n? iters (avg): \t{}' .format(rand_won, 100 * rand_won / num_tests, np.mean(iterations))) ax_iterations = plt.subplot(212, sharex=ax_gens) ax_iterations.set_ylim([math.ceil(min(iterations) - 0.5 * (max(iterations) - min(iterations))), math.ceil(min(iterations) + 0.5 * (max(iterations) - min(iterations)))]) plt.bar(np.arange(num_tests), width=0.35, height=iterations, color='y') # ax.legend((rects1[0], rects2[0]), ('Men', 'Women')) plt.show(block=False)
def line(): """ Creates a single graph with date and time as the x axis and a variable number of plots. """ # Save data to redraw plot later save_data('line') # set the screen title, size, density fig = plt.figure(title,graph_dimensions,graph_dpi) # do the plot plt.title(title) plt.ylabel(ylabel1) plt.grid(which="major") for plot_num in range(len(ylists)): plt.plot(xdatetimes,ylists[plot_num],color=my_colors(plot_num)) # date time formatting ax = plt.axes() fig.autofmt_xdate() ax.fmt_xdata = mdates.DateFormatter('%m/%d/%Y %H:%M') loc=mdates.AutoDateLocator() datetimefmt = mdates.AutoDateFormatter(loc) ax.xaxis.set_major_formatter(datetimefmt) ax.xaxis.set_major_locator(loc) # other formatting plt.legend(ylistlabels,loc='upper left') plt.autoscale(tight=True) # subplots_adjust settings - single plot so zero space between plots vleft = 0.06 # the left side of the subplots of the figure vright = 0.97 # the right side of the subplots of the figure vbottom = 0.12 # the bottom of the subplots of the figure vtop = 0.95 # the top of the subplots of the figure vwspace = 0.0 # the amount of width reserved for blank space between subplots vhspace = 0.0 # the amount of height reserved for white space between subplots plt.subplots_adjust(left=vleft,right=vright,bottom=vbottom,top=vtop,wspace=vwspace,hspace=vhspace) fileorscreen(title+'.png') return