我们从Python开源项目中,提取了以下26个代码示例,用于说明如何使用matplotlib.pyplot.sca()。
def make_artifact_plots(data, outname, pos_arts, neg_arts, stds): colors = [cm.Dark2(x) for x in np.linspace(0, 1, len(stds))] f, (ax1, ax2, ax3) = plt.subplots(3, 1) if len(pos_arts) == 0 and len(neg_arts) == 0: # nothing to do plt.savefig(outname + ".png") return for c, (poss, negs) in enumerate(zip(pos_arts, neg_arts)): extrema = np.array(poss + negs, dtype=int) for i in extrema: ax1.plot(data[i - 10:i + 10, c] / stds[c], linewidth=0.5, color=colors[c]) plt.sca(ax2) plt.hist(data[extrema, c] / stds[c], bins=20, fill=None, edgecolor=colors[c]) ax3.vlines(extrema, 0, 1, color=colors[c]) ax1.set_ylabel("standard deviation") ax1.set_title("artifacts") ax2.set_title("amplitude distribution") ax3.set_title("artifact locations") plt.savefig(outname + ".png")
def plot_sub_joint(self, func, subsample, **kwargs): """Draw a bivariate plot of `x` and `y`. Parameters ---------- func : plotting callable This must take two 1d arrays of data as the first two positional arguments, and it must plot on the "current" axes. kwargs : key, value mappings Keyword argument are passed to the plotting function. Returns ------- self : JointGrid instance Returns `self`. """ if subsample > 0 and subsample < len(self.x): indexes = np.random.choice(range(len(self.x)), subsample, replace=False) plot_x = np.array([self.x[i] for i in indexes]) plot_y = np.array([self.y[i] for i in indexes]) plt.sca(self.ax_joint) func(plot_x, plot_y, **kwargs) else: plt.sca(self.ax_joint) func(self.x, self.y, **kwargs) return self
def plot_pull(data, func): import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator ax, bx = make_split(0.8) plt.sca(ax) x, y, norm = histpoints(data) lower, upper = ax.get_xlim() xs = np.linspace(lower, upper, 200) plt.plot(xs, norm * func(xs), 'b-') #plt.gca().yaxis.set_major_locator(MaxNLocator(prune='lower')) plt.sca(bx) resid = y[1] - norm * func(x) err = np.zeros_like(resid) err[resid >= 0] = y[0][resid >= 0] err[resid < 0] = y[2][resid < 0] pull = resid / err plt.errorbar(x, pull, yerr=1, color='k', fmt='o') plt.ylim(-5, 5) plt.axhline(0, color='b') plt.sca(ax) return ax, bx
def multi_plot(): plt.figure(1) plt.figure(2) ax1 = plt.subplot(211) ax2 = plt.subplot(212) x = np.linspace(0, 3, 100) print x for i in xrange(5): plt.figure(1) plt.plot(x, np.exp(i * x / 3)) plt.sca(ax1) plt.plot(x, np.sin(i * x)) plt.sca(ax2) plt.plot(x, np.cos(i * x)) plt.show()
def multi_plot_rocky(): plt.figure(1) #plt.figure(2) #plt.figure(3) #plt.figure(4) #plt.figure(1) ax1=plt.subplot(2,2,1) ax2=plt.subplot(2,2,2) ax3=plt.subplot(2,2,3) ax4=plt.subplot(2,2,4) x1=range(0,10) x2=range(0,20) x3=range(0,30) x4=range(0,40) plt.plot(x1,'o') plt.sca(ax1) plt.plot(x2) plt.sca(ax2) plt.plot(x3) plt.sca(ax3) plt.plot(x4) plt.sca(ax4) plt.show()
def multi_plot_rocky2(): plt.figure(1) #plt.figure(2) #plt.figure(3) #plt.figure(4) #plt.figure(1) #ax1=plt.subplot(2,2,1) #ax2=plt.subplot(2,2,2) #ax3=plt.subplot(2,2,3) #ax4=plt.subplot(2,2,4) x1=range(0,10) x2=range(0,20) x3=range(0,30) x4=range(0,40) plt.subplot(2,2,1) plt.title('x1') plt.plot(x1,'o') #plt.sca(ax1) plt.subplot(2,2,2) plt.title('x2') plt.plot(x2) #plt.sca(ax2) plt.subplot(2,2,3) plt.title('x3') plt.plot(x3) #plt.sca(ax3) plt.subplot(2,2,4) plt.title('x4') plt.plot(x4) #plt.sca(ax4) #plt.subplot(2,1,1) #plt.title('x1') plt.show()
def _BorderPlot(time, x, color, kind, alpha, legend, linewidth, axes): npts, dev = x.shape # Get the deviation/sem : xStd = np.std(x, axis=1) if kind is 'sem': xStd = xStd/np.sqrt(npts-1) xMean = np.mean(x, 1) xLow, xHigh = xMean-xStd, xMean+xStd # Plot : if axes is None: axes = plt.gca() plt.sca(axes) ax = plt.plot(time, xMean, color=color, label=legend, linewidth=linewidth) plt.fill_between(time, xLow, xHigh, alpha=alpha, color=ax[0].get_color())
def visualize_predictions(prediction_seqs, label_seqs, num_classes, fig_width=6.5, fig_height_per_seq=0.5): """ Visualize predictions vs. ground truth. Args: prediction_seqs: A list of int NumPy arrays, each with shape `[duration, 1]`. label_seqs: A list of int NumPy arrays, each with shape `[duration, 1]`. num_classes: An integer. fig_width: A float. Figure width (inches). fig_height_per_seq: A float. Figure height per sequence (inches). Returns: A tuple of the created figure, axes. """ num_seqs = len(label_seqs) max_seq_length = max([seq.shape[0] for seq in label_seqs]) figsize = (fig_width, num_seqs*fig_height_per_seq) fig, axes = plt.subplots(nrows=num_seqs, ncols=1, sharex=True, figsize=figsize) for pred_seq, label_seq, ax in zip(prediction_seqs, label_seqs, axes): plt.sca(ax) plot_label_seq(label_seq, num_classes, 1) plot_label_seq(pred_seq, num_classes, -1) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.xlim(0, max_seq_length) plt.ylim(-2.75, 2.75) plt.tight_layout() return fig, axes
def create_pseudo_random_code(clen=10000,rseed=0,verbose=False): """ Create waveform files for hfradar Juha Vierinen """ Npt = 200 # number of points to plot, just for plotting, arbitrary """ seed is a way of reproducing the random code without having to store all actual codes. the seed can then act as a sort of station_id. """ seed(rseed) """ generate a uniform random phase modulated (complex) signal 'sig". It's single precision floating point for SDR, since DAC is typically <= 16 bits! """ sig = np.exp(1j*2.0*np.pi*random(clen)).astype('complex64') if stuffr is not None: stuffr.plot_cts(sig[:Npt]) if verbose and hist is not None: fg,ax = subplots(3,1) sca(ax[0]) hist(sig.real)#,50) sca(ax[1]) hist(sig.imag) #hist(random(clen)) return sig
def Degree_function(G): Nodes = G.nodes() Degree_List = [] Degree_Dic = {} for i in Nodes: Degree_List.append(G.degree(i)) Degree_List = sorted(Degree_List, reverse = False) Flag = Degree_List[0] Count = 1 for i in Degree_List[1:]: if i !=Flag: Degree_Dic[Flag] = Count Count = 1 Flag = i else: Count = Count + 1 #end for #print Degree_Dic n = G.number_of_nodes() plt.figure(1) ax1 = plt.subplot(111) plt.sca(ax1) #x = list([(i+1) for i in range(0,len(Degree_List))]) x = sorted(Degree_Dic.keys(), reverse = False) y = [] for i in x: y.append(float(Degree_Dic[i])/n) #end for plt.plot(x, y, "rs-") plt.ylabel("Probability") plt.xlabel("Degree K") plt.title("degree distribution") plt.show() #************************************************************************
def Degree_distribution(G): Nodes = G.nodes() Degree_List = [] Degree_Dic = {} for i in Nodes: Degree_List.append(G.degree(i)) Degree_List = sorted(Degree_List, reverse = False) Flag = Degree_List[0] Count = 1 for i in Degree_List[1:]: if i !=Flag: Degree_Dic[Flag] = Count Count = 1 Flag = i else: Count = Count + 1 #end for #print Degree_Dic n = G.number_of_nodes() plt.figure(1) ax1 = plt.subplot(111) plt.sca(ax1) #x = list([(i+1) for i in range(0,len(Degree_List))]) x = sorted(Degree_Dic.keys(), reverse = False) y = [] for i in x: y.append(float(Degree_Dic[i])/n) #end for plt.plot(x, y, "rs-") plt.ylabel("Probability") plt.xlabel("Degree K") plt.title("Degree distribution of networks") plt.show() #************************************************************************
def plot_algo_overview(self, algorithms, subdir="algo_overview", fs=6): accv_metrics = [MSE(), BadPix(0.07), BumpinessPlanes(), BumpinessContinSurf(), Discontinuities(), FineFattening(), FineThinning()] metrics_low_res = [m for m in self.get_applicable_metrics_low_res() if m in accv_metrics] metrics_high_res = [m for m in self.get_applicable_metrics_high_res() if m in accv_metrics] # prepare figure rows = len(metrics_low_res + metrics_high_res) + 1 cols = len(algorithms) + 1 fig = plt.figure(figsize=(cols, rows*1.1)) grids = self._get_grids(fig, rows, cols, axes_pad=-0.2) # center view on top left grid cell self.set_high_gt_scale() plt.sca(grids[0][0]) plt.imshow(self.get_center_view()) plt.title("Center View", fontsize=fs) plt.ylabel("Disparity Map", fontsize=fs) # mask visualizations + algorithm disparity maps + metric visualizations log.info("Computing scores and visualizations for low resolution metrics.") self.set_low_gt_scale() self.plot_metric_rows(grids, algorithms, metrics_low_res, offset=0, fontsize=fs) log.info("Computing scores and visualizations for high resolution metrics.") self.set_high_gt_scale() self.plot_metric_rows(grids, algorithms, metrics_high_res, offset=len(metrics_low_res), fontsize=fs) # finalize figure for grid in grids: plotting.remove_ticks_from_axes(grid.axes_all) plotting.remove_frames_from_axes(grid.axes_all) plt.suptitle(self.get_display_name(), fontsize=fs+2) fig_path = plotting.get_path_to_figure("algo_overview_%s" % self.get_name(), subdir=subdir) plotting.save_fig(fig, fig_path, pad_inches=0.1)
def plot_metric_rows(self, grids, algorithms, metrics, offset, fontsize): gt = self.get_gt() center_view = self.get_center_view() for idx_a, algorithm in enumerate(algorithms): log.info("Algorithm: %s" % algorithm) algo_result = misc.get_algo_result(algorithm, self) # add algorithm disparity map plt.sca(grids[0][idx_a + 1]) cm = plt.imshow(algo_result, **settings.disp_map_args(self)) plt.title(algorithm.get_display_name(), fontsize=fontsize) # add colorbar to last disparity map in row if idx_a == (len(algorithms) - 1): plotting.create_colorbar(cm, cax=grids[0].cbar_axes[0], colorbar_bins=7, fontsize=fontsize) # add algorithm metric visualizations for idx_m, metric in enumerate(metrics): log.info(metric.get_display_name()) mask = metric.get_evaluation_mask(self) plt.sca(grids[idx_m + offset + 1][idx_a + 1]) cm = self.plot_algo_vis_for_metric(metric, algo_result, gt, mask, self.hidden_gt(), fontsize) # add colorbar to last metric visualization in row if idx_a == len(algorithms) - 1: plotting.create_colorbar(cm, cax=grids[idx_m + offset + 1].cbar_axes[0], colorbar_bins=metric.colorbar_bins, fontsize=fontsize) # add mask visualizations as 1st column if idx_a == 0: plt.sca(grids[idx_m + offset + 1][0]) plotting.plot_img_with_transparent_mask(center_view, mask, alpha=0.7, color=settings.MASK_COLOR) plt.ylabel(metric.get_short_name(), fontsize=fontsize) plt.title("Region Mask", fontsize=fontsize)
def plotChart(self, costList, misRateList, saveFigPath): ''' ???????????? epoch ?????? :param costList: ???????epoch??????? :param misRateList: ???????epoch?????? :return: ''' # ????? import matplotlib.pyplot as plt # ???? plt.figure('Perceptron Cost and Mis-classification Rate',figsize=(8, 9)) # ??????????? ax1 = plt.subplot(211) ax2 = plt.subplot(212) # ????1????????????????? plt.sca(ax1) plt.plot(xrange(1, len(costList)+1), costList, '--b*') plt.xlabel('Epoch No.') plt.ylabel('Cost') plt.title('Plot of Cost Function') plt.grid() ax1.legend(u"Cost", loc='best') # ????2??????????????? plt.sca(ax2) plt.plot(xrange(1, len(misRateList)+1), misRateList, '-r*') plt.xlabel('Epoch No.') plt.ylabel('Mis-classification Rate') plt.title('Plot of Mis-classification Rate') plt.grid() ax2.legend(u'Mis-classification Rate', loc='best') # ?????????? # ??????????????????????????? plt.savefig(saveFigPath) plt.show() ################################### PART3 TEST ######################################## # ??
def plotChart(self, costList, misRateList, saveFigPath): ''' ???????????? epoch ?????? :param costList: ???????epoch??????? :param misRateList: ???????epoch?????? :return: ''' # ????? import matplotlib.pyplot as plt # ???? plt.figure('Perceptron Cost and Mis-classification Rate', figsize=(8, 9)) # ??????????? ax1 = plt.subplot(211) ax2 = plt.subplot(212) # ????1????????????????? plt.sca(ax1) plt.plot(xrange(1, len(costList) + 1), costList, '--b*') plt.xlabel('Epoch No.') plt.ylabel('Cost') plt.title('Plot of Cost Function') plt.grid() ax1.legend(u"Cost", loc='best') # ????2??????????????? plt.sca(ax2) plt.plot(xrange(1, len(misRateList) + 1), misRateList, '-r*') plt.xlabel('Epoch No.') plt.ylabel('Mis-classification Rate') plt.title('Plot of Mis-classification Rate') plt.grid() ax2.legend(u'Mis-classification Rate', loc='best') # ?????????? # ??????????????????????????? plt.savefig(saveFigPath) plt.show() ################################### PART3 TEST ######################################## # ??
def plot(self,axs=None,ls="-",marker="None",xlim=[None,None],label="",**plotargs): if axs is None: fig, axs = plt.subplots(nrows=4,ncols=1,sharex=True) ax = axs[0] plt.sca(ax) plt.plot(self["RM"],self["P"],ls=ls,marker=marker,**plotargs) plt.ylabel("$P$ (Jy rad$^{-1}$ m$^{2}$)") plt.xlim(xlim) plt.ylim(0,) ymax = np.max(ax.get_ylim()) ax = axs[1] plt.sca(ax) chi = self["chi"] chi[self["P"] < np.max(self["P"]) * 0.01]=0 plt.plot(self["RM"],chi,ls=ls,marker=marker,**plotargs) plt.ylabel("$\chi$ (deg)") plt.xlim(xlim) plt.ylim(-90,90) ax.set_yticks(np.arange(-90,91,10), minor=True) ax.set_yticks(np.arange(-90,91,30), minor=False) ax = axs[2] plt.sca(ax) plt.plot(self["RM"],self["Q"],ls=ls,marker=marker,**plotargs) plt.axhline(0, ls="--", color="black") plt.ylabel("$Q$ (Jy rad$^{-1}$ m$^{2}$)") plt.xlim(xlim) plt.ylim(-ymax,ymax) # ax = axs[3] plt.sca(ax) plt.plot(self["RM"],self["U"],ls=ls,marker=marker,**plotargs) plt.axhline(0, ls="--", color="black") plt.ylabel("$U$ (Jy rad$^{-1}$ m$^{2}$)") plt.xlabel("$\phi$ (rad m$^{-2}$)") plt.xlim(xlim) plt.ylim(-ymax,ymax) return axs
def plotInOneSubFigure(i,x,y,files): plt.figure() if len(files)==2: ax1 = plt.subplot(211) ax2 = plt.subplot(212) plt.sca(ax1) plt.plot(x, y[0], color="blue", linewidth=2.5, linestyle="-", label=files[0].split(".")[0]) plt.ylabel("TrafficVolume") # Y??? plt.title(i) # ?? plt.legend(loc='upper right') plt.sca(ax2) plt.plot(x, y[1], color="red", linewidth=2.5, linestyle="-", label=files[1].split(".")[0]) plt.ylabel("TrafficVolume") # Y??? plt.legend(loc='upper right') else: ax1 = plt.subplot(311) ax2 = plt.subplot(312) ax3 = plt.subplot(313) plt.sca(ax1) plt.plot(x,y[0],color="blue", linewidth=2.5, linestyle="-",label=files[0].split(".")[0]) plt.ylabel("TrafficVolume") # Y??? plt.title(i) # ?? plt.legend(loc='upper right') plt.sca(ax2) plt.plot(x,y[1],color="red", linewidth=2.5, linestyle="-",label=files[1].split(".")[0]) plt.ylabel("TrafficVolume") # Y??? plt.legend(loc='upper right') plt.sca(ax3) plt.plot(x,y[2],color="green", linewidth=2.5, linestyle="-", label=files[2].split(".")[0]) plt.xlabel("time") # X??? plt.ylabel("TrafficVolume") # Y??? plt.legend(loc='upper right') plt.show()
def main(): """ Create a standardized data file from raw data. """ args = define_and_process_args() print('Standardizing JIGSAWS..') print() print('%d classes:' % NUM_CLASSES) print(CLASSES) print() user_to_trial_names = {} for user, trials in USER_TO_TRIALS.items(): user_to_trial_names[user] = [get_trial_name(user, trial) for trial in trials] print('Users and corresponding trial names:') for user in ALL_USERS: print(user, ' ', user_to_trial_names[user]) print() all_trial_names = sorted(list( itertools.chain(*user_to_trial_names.values()) )) print('All trial names, sorted:') print(all_trial_names) print() # Original data is at 30 Hz. all_data = {trial_name: downsample( load_kinematics_and_new_labels(args.data_dir, trial_name), factor=6) for trial_name in all_trial_names} print('Downsampled to 5 Hz.') print() fig, ax_list = plt.subplots(nrows=len(all_data), ncols=1, sharex=True, figsize=(15, 50)) for ax, (trial_name, data_mat) in zip(ax_list, sorted(all_data.items())): plt.sca(ax) data.plot_label_seq(data_mat[:, -1:], NUM_CLASSES, 0) plt.title(trial_name) plt.tight_layout() vis_path = os.path.join(args.data_dir, 'standardized_data_labels.png') plt.savefig(vis_path) plt.close(fig) print('Saved label visualization to %s.' % vis_path) print() export_dict = dict( dataset_name=DATASET_NAME, classes=CLASSES, num_classes=NUM_CLASSES, col_names=STANDARDIZED_COL_NAMES, all_users=ALL_USERS, user_to_trial_names=user_to_trial_names, all_trial_names=all_trial_names, all_data=all_data) standardized_data_path = os.path.join(args.data_dir, args.data_filename) with open(standardized_data_path, 'w') as f: cPickle.dump(export_dict, f) print('Saved standardized data file %s.' % standardized_data_path) print()
def draw_contour(fn, bounds, nodes=None, points=None, title=None, **options): """Plot a contour of a function. Experimental, only 2D supported. Parameters ---------- fn : callable bounds : list[arraylike] Bounds for the plot, e.g. [(0, 1), (0,1)]. nodes : list[str], optional points : arraylike, optional Additional points to plot. title : str, optional """ ax = get_axes(**options) x, y = np.meshgrid(np.linspace(*bounds[0]), np.linspace(*bounds[1])) z = fn(np.c_[x.reshape(-1), y.reshape(-1)]) if ax: plt.sca(ax) plt.cla() if title: plt.title(title) try: plt.contour(x, y, z.reshape(x.shape)) except ValueError: logger.warning('Could not draw a contour plot') if points is not None: plt.scatter(points[:-1, 0], points[:-1, 1]) if options.get('interactive'): plt.scatter(points[-1, 0], points[-1, 1], color='r') plt.xlim(bounds[0]) plt.ylim(bounds[1]) if nodes: plt.xlabel(nodes[0]) plt.ylabel(nodes[1])
def Optimal_Influence_Spreaders(G): #?????top l????????influence???????????centrality measures???????? print "Degree_centrality" Gn = G.copy() Degree_Infected_Num_List = Optimal_Spreaders.Optimal_Influence_Spreading(Gn, "degree_centrality") print "Between_centrality" Gn = G.copy() Bet_Infected_Num_List = Optimal_Spreaders.Optimal_Influence_Spreading(Gn, "between_centrality") print "KShell_centrality" Gn = G.copy() KShell_Infected_Num_List = Optimal_Spreaders.Optimal_Influence_Spreading(Gn, "kshell_centrality") print "Eigen_Centrality" Gn = G.copy() Eigen_Infected_Num_List = Optimal_Spreaders.Optimal_Influence_Spreading(Gn, "eigen_centrality") print "Collective_influence" Gn = G.copy() CI_Infected_Num_List = Optimal_Spreaders.Optimal_Influence_Spreading(Gn, "collective_influence") print "PIR_Centrality" Gn = G.copy() PIR_Infected_Num_List = Optimal_Spreaders.Optimal_Influence_Spreading(Gn, "PIR_Centrality") '''Infected & Recoveried node number ??''' print "Degree_Infected_Num_List:", Degree_Infected_Num_List print "Bet_Infected_Num_List:", Bet_Infected_Num_List print "KShell_Infected_Num_List:", KShell_Infected_Num_List print "Eigen_Infected_Num_List:", Eigen_Infected_Num_List print "CI_Infected_Num_List:", CI_Infected_Num_List print "PIR_Infected_Num_List:", PIR_Infected_Num_List #=================================================== plt.figure(1) ax1 = plt.subplot(111) plt.sca(ax1) x = list([(i+1) for i in range(0,len(Degree_Infected_Num_List))]) plt.plot(x, Degree_Infected_Num_List, "ms-") x = list([(i+1) for i in range(0,len(Bet_Infected_Num_List))]) plt.plot(x, Bet_Infected_Num_List, "c+-") x = list([(i+1) for i in range(0,len(KShell_Infected_Num_List))]) plt.plot(x, KShell_Infected_Num_List, "y^-") x = list([(i+1) for i in range(0,len(Eigen_Infected_Num_List))]) plt.plot(x, Eigen_Infected_Num_List, "gp-") x = list([(i+1) for i in range(0,len(CI_Infected_Num_List))]) plt.plot(x, CI_Infected_Num_List, "k.-") x = list([(i+1) for i in range(0,len(PIR_Infected_Num_List))]) plt.plot(x, PIR_Infected_Num_List, "r8-") plt.title("Optimal Spreading under node ranking") plt.ylabel("Infected scale F(t) at time t") plt.xlabel("time t") leg = plt.legend(('Degree', 'Bet', 'KShell', 'Eigen', 'CI', 'PIR'), 'upper right') for t in leg.get_texts(): t.set_fontsize(12) plt.title("Optimal Spreaders") plt.show()
def nodes_graph(self, colnum=0, show=False, printout=True): """Plot a 2D map with hexagonal nodes and weights values Args: colnum (int): The index of the weight that will be shown as colormap. show (bool, optional): Choose to display the plot. printout (bool, optional): Choose to save the plot to a file. """ centers = [[node.pos[0],node.pos[1]] for node in self.nodeList] widthP=100 dpi=72 xInch = self.netWidth*widthP/dpi yInch = self.netHeight*widthP/dpi fig=plt.figure(figsize=(xInch, yInch), dpi=dpi) if self.colorEx==True: cols = [[np.float(node.weights[0]),np.float(node.weights[1]),np.float(node.weights[2])]for node in self.nodeList] ax = hx.plot_hex(fig, centers, cols) ax.set_title('Node Grid w Color Features', size=80) printName='nodesColors.png' else: cols = [node.weights[colnum] for node in self.nodeList] ax = hx.plot_hex(fig, centers, cols) ax.set_title('Node Grid w Feature #' + str(colnum), size=80) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.0) cbar=plt.colorbar(ax.collections[0], cax=cax) cbar.set_label('Feature #' + str(colnum)+' value', size=80, labelpad=50) cbar.ax.tick_params(labelsize=60) plt.sca(ax) printName='nodesFeature_'+str(colnum)+'.png' if printout==True: plt.savefig(printName, bbox_inches='tight', dpi=dpi) if show==True: plt.show() if show!=False and printout!=False: plt.clf()
def diff_graph(self, show=False, printout=True): """Plot a 2D map with nodes and weights difference among neighbouring nodes. Args: show (bool, optional): Choose to display the plot. printout (bool, optional): Choose to save the plot to a file. """ neighbours=[] for node in self.nodeList: nodelist=[] for nodet in self.nodeList: if node != nodet and node.get_nodeDistance(nodet) <= 1.001: nodelist.append(nodet) neighbours.append(nodelist) diffs = [] for node, neighbours in zip(self.nodeList, neighbours): diff=0 for nb in neighbours: diff=diff+node.get_distance(nb.weights) diffs.append(diff) centers = [[node.pos[0],node.pos[1]] for node in self.nodeList] widthP=100 dpi=72 xInch = self.netWidth*widthP/dpi yInch = self.netHeight*widthP/dpi fig=plt.figure(figsize=(xInch, yInch), dpi=dpi) ax = hx.plot_hex(fig, centers, diffs) ax.set_title('Nodes Grid w Weights Difference', size=80) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.0) cbar=plt.colorbar(ax.collections[0], cax=cax) cbar.set_label('Weights Difference', size=80, labelpad=50) cbar.ax.tick_params(labelsize=60) plt.sca(ax) printName='nodesDifference.png' if printout==True: plt.savefig(printName, bbox_inches='tight', dpi=dpi) if show==True: plt.show() if show!=False and printout!=False: plt.clf()
def iplt(fdic, key, cut=None, ax=None, cbar=None, smth=None, nolabels=None, lblsz='small', **kwargs): """ A wrapper function for imshow to do most tedious stuff for my simulations """ old_ax = plt.gca() # Get Current Axis if ax is None: ax = old_ax else: plt.sca(ax) # Set Current Axis if type(key) is str: plt_val = fdic[key] else : plt_val = key if cut is None: if len(plt_val.shape) == 1: IDX=np.s_[:] elif len(plt_val.shape) == 2: IDX=np.s_[:,0] else: IDX=np.s_[:,0,0] else: if len(plt_val.shape) == 1: IDX=compute1didx([fdic['xx']],cut) elif len(plt_val.shape) == 2: IDX=compute1didx([fdic['xx'],fdic['yy']],cut) else: IDX=compute1didx([fdic['xx'],fdic['yy'],fdic['zz']],cut) im = ax.plot(fdic['xx'],plt_val[IDX], **kwargs) ax.autoscale(False) if nolabels is None: ax.set_xlabel(r'$X (d_i)$',size=lblsz) ax.set_ylabel(key,size=lblsz) ax.xaxis.set_tick_params(which='both',labelsize=lblsz) ax.yaxis.set_tick_params(which='both',labelsize=lblsz) plt.minorticks_on() plt.sca(old_ax) return im
def rating_distributions(): ''' Display histogram of rating counts ''' con = sqlite3.connect(database) cur = con.cursor() user_summary = cur.execute('Select Uid, Count(Uid),Sum(Score) FROM UserData \ WHERE Score>0 GROUP BY Uid ').fetchall() user_summary = np.array([[x[0], x[1], x[2], float(x[2])/x[1]] for x in user_summary]) all_ratings = [x[0] for x in cur.execute('Select Score FROM \ UserData WHERE Score>0 ').fetchall()] # Determine whether those who rate more anime have a different average rating. bin_size, avg_ratings = 50, [] num_ratings = np.arange(bin_size/2,1000,bin_size) for mid_bin in num_ratings: rel_data = user_summary[np.multiply(user_summary[:,1]>=mid_bin-bin_size/2,user_summary[:,1]<mid_bin+bin_size/2),1:3] avg_ratings.append( float(sum(rel_data[:,1]))/float(sum(rel_data[:,0]))) #avg_ratings.append(np.mean(user_summary[np.multiply(user_summary[:,1]>=mid_bin-bin_size/2,user_summary[:,1]<mid_bin+bin_size/2),3])) # Plot these exploratory figures: f, axarr = plt.subplots(2,2) axarr[0,0].set_xlabel('Number of ratings (per user)',size=10) axarr[0,0].set_ylabel('Number of users',size=10) #axarr[0,0].text(-0.3, 1.05, 'A.', transform=axarr[0,0].transAxes, size=10) axarr[0,0].hist(user_summary[:,1],bins=np.arange(0,np.max(user_summary[:,1])+50,50)) axarr[0,0].set_xlim([0,1000]) axarr[0,0].yaxis.set_major_formatter(FuncFormatter(shorten_numbers)) axarr[1,0].set_xlabel('Number of ratings (per user)',size=10) axarr[1,0].set_ylabel('Average rating',size=10) axarr[1,0].plot(num_ratings,avg_ratings) axarr[1,0].set_xlim([0,1000]) axarr[1,0].set_yticks(range(0,11)) axarr[1,0].set_yticklabels(['0','','2','','4','','6','','8','','10']) axarr[1,0].set_ylim([1,10]) #axarr[1,0].text(-0.3, 1.05, 'B.', transform=axarr[1,0].transAxes, size=10) axarr[0,1].set_xlabel('Ratings',size=10) axarr[0,1].set_ylabel('Number of ratings ',size=10) axarr[0,1].hist(all_ratings,bins=np.arange(0.5,11.5)) axarr[0,1].set_xlim([0.5,10.5]) axarr[0,1].yaxis.set_major_formatter(FuncFormatter(shorten_numbers)) #axarr[0,1].text(-0.3, 1.05, 'C.', transform=axarr[0,1].transAxes, size=10) plt.sca(axarr[0, 1]) plt.xticks(range(1,11)) axarr[1,1].set_xlabel('Average ratings (per user)',size=10) axarr[1,1].set_ylabel('Number of users',size=10) axarr[1,1].hist(user_summary[:,3],bins=np.arange(0.5,11.5)) axarr[1,1].set_xlim([0.5,10.5]) axarr[1,1].yaxis.set_major_formatter(FuncFormatter(shorten_numbers)) #axarr[1,1].text(-0.3, 1.05, 'D.', transform=axarr[1,1].transAxes, size=10) plt.sca(axarr[1, 1]) plt.xticks(range(1,11)) f.tight_layout() for (i,j) in ((0,0),(0,1),(1,0),(1,1)): axarr[i,j].xaxis.set_ticks_position('none') axarr[i,j].yaxis.set_ticks_position('none') plt.savefig('results\\User_ratings.png',dpi=300,format='png') print([np.mean(all_ratings), np.std(all_ratings)]) con.close()
def good_colorbar(vmin,vmax,cmap,title='',ax=None,sideways=False, border=True,spacing=5,fontsize=12): ''' Matplotlib's colorbar function is pretty bad. This is less bad. r'$\mathrm{\mu V}^2$' Parameters: vmin (number): min value for colormap vmax (number): mac value for colormap cmap (colormap): what colormap to use ax (axis): optional, defaults to plt.gca(). axis to which to add colorbar title (string): Units for colormap sideways (bool): Flips the axis label sideways spacing (int): distance from axis in pixels. defaults to 5 Returns: axis: colorbar axis ''' oldax = plt.gca() #remember previously active axis if ax==None: ax=plt.gca() # WIDTH = 0.05 SPACING = pixels_to_xfigureunits(spacing,ax=ax) CWIDTH = pixels_to_xfigureunits(15,ax=ax) # manually add colorbar axes bb = ax.get_position() x,y,w,h = bb.xmin,bb.ymin,bb.width,bb.height # ax.set_position((x,y,w-WIDTH,h)) bb = ax.get_position() right,bottom = bb.xmax,bb.ymax cax = plt.axes((right+SPACING,bottom-h,CWIDTH,h),facecolor='w',frameon=border) plt.sca(cax) plt.imshow(np.array([np.linspace(vmax,vmin,100)]).T, extent=(0,1,vmin,vmax), aspect='auto', cmap=cmap) nox() nicey() cax.yaxis.tick_right() if sideways: plt.text( xlim()[1]+pixels_to_xunits(5,ax=cax), np.mean(ylim()), title, fontsize=fontsize, rotation=0, horizontalalignment='left', verticalalignment ='center') else: plt.ylabel(title,fontsize=fontsize) cax.yaxis.set_label_position("right") plt.sca(oldax) #restore previously active axis return cax
def plot(self,axs=None,ls="none",marker=".",xlim=[None,None],ploterror=False,**plotargs): if axs is None: fig, axs = plt.subplots(nrows=4,ncols=1,sharex=True) ax = axs[0] plt.sca(ax) if ploterror: plt.errorbar(self["lambsq"],self["P"],self["sigma"]/np.sqrt(2), ls=ls,marker=marker,**plotargs) else: plt.plot(self["lambsq"],self["P"],ls=ls,marker=marker,**plotargs) plt.ylabel("$P$ (Jy)") plt.xlim(xlim) plt.ylim(0,) ymax = np.max(ax.get_ylim()) # ax = axs[1] plt.sca(ax) if ploterror: plt.errorbar(self["lambsq"],self["chi"],np.rad2deg(self["sigma"]/self["P"])/2, ls=ls,marker=marker,**plotargs) else: plt.plot(self["lambsq"],self["chi"],ls=ls,marker=marker,**plotargs) plt.ylabel("$\chi$ (deg)") plt.xlim(xlim) plt.ylim(-90,90) ax.set_yticks(np.arange(-90,91,10), minor=True) ax.set_yticks(np.arange(-90,91,30), minor=False) # ax = axs[2] plt.sca(ax) if ploterror: plt.errorbar(self["lambsq"],self["Q"],self["sigma"], ls=ls,marker=marker,**plotargs) else: plt.plot(self["lambsq"],self["Q"],ls=ls,marker=marker,**plotargs) plt.axhline(0, ls="--", color="black") plt.ylabel("$Q$ (Jy)") plt.xlim(xlim) plt.ylim(-ymax,ymax) # ax = axs[3] plt.sca(ax) if ploterror: plt.errorbar(self["lambsq"],self["U"],self["sigma"], ls=ls,marker=marker,**plotargs) else: plt.plot(self["lambsq"],self["U"], ls=ls,marker=marker,**plotargs) plt.axhline(0, ls="--", color="black") plt.ylabel("$U$ (Jy)") plt.xlabel("$\lambda ^2$ (m$^{2}$)") plt.xlim(xlim) plt.ylim(-ymax,ymax) return axs