我们从Python开源项目中,提取了以下6个代码示例,用于说明如何使用matplotlib.pyplot.hist2d()。
def plot_2d_hist(x1, x2, bins=10): plt.hist2d(x1, x2, bins=10, norm=LogNorm()) plt.colorbar() plt.show()
def run_synthetic_SGLD(): theta1 = 0 theta2 = 1 sigma1 = numpy.sqrt(10) sigma2 = 1 sigmax = numpy.sqrt(2) X = load_synthetic(theta1=theta1, theta2=theta2, sigmax=sigmax, num=100) minibatch_size = 1 total_iter_num = 1000000 lr_scheduler = SGLDScheduler(begin_rate=0.01, end_rate=0.0001, total_iter_num=total_iter_num, factor=0.55) optimizer = mx.optimizer.create('sgld', learning_rate=None, rescale_grad=1.0, lr_scheduler=lr_scheduler, wd=0) updater = mx.optimizer.get_updater(optimizer) theta = mx.random.normal(0, 1, (2,), mx.cpu()) grad = nd.empty((2,), mx.cpu()) samples = numpy.zeros((2, total_iter_num)) start = time.time() for i in xrange(total_iter_num): if (i + 1) % 100000 == 0: end = time.time() print "Iter:%d, Time spent: %f" % (i + 1, end - start) start = time.time() ind = numpy.random.randint(0, X.shape[0]) synthetic_grad(X[ind], theta, sigma1, sigma2, sigmax, rescale_grad= X.shape[0] / float(minibatch_size), grad=grad) updater('theta', grad, theta) samples[:, i] = theta.asnumpy() plt.hist2d(samples[0, :], samples[1, :], (200, 200), cmap=plt.cm.jet) plt.colorbar() plt.show()
def prep_2D_hist(ima, gra, discard_zeros=True): """Prepare 2D histogram related variables. Parameters ---------- ima : np.ndarray First image, which is often the intensity image (eg. T1w). gra : np.ndarray Second image, which is often the gradient magnitude image derived from the first image. Returns ------- counts : integer volHistH : TODO d_min : float Minimum of the first image. d_max : float Maximum of the first image. nr_bins : integer Number of one dimensional bins (not the pixels). bin_edges : TODO Notes ----- This function is modularized to be called from the terminal. """ if discard_zeros: gra = gra[~np.isclose(ima, 0)] ima = ima[~np.isclose(ima, 0)] d_min, d_max = np.round(np.nanpercentile(ima, [0, 100])) nr_bins = int(d_max - d_min) bin_edges = np.arange(d_min, d_max+1) counts, _, _, volHistH = plt.hist2d(ima, gra, bins=bin_edges, cmap='Greys') return counts, volHistH, d_min, d_max, nr_bins, bin_edges
def plot(self,keys=None,burn=1000): if keys is None: keys=self.names0 k=0 #plm=putil.Plm1(rows=2,cols=2,xmulti=True,ymulti=True,slabel=False) for i in range(len(keys)): for j in range(len(keys)): k=k+1 if i==j: x=self.chain[keys[i]][burn:] plt.subplot(len(keys),len(keys),k) #sig=np.std(self.chain[keys[i]][burn:]) xmean=np.mean(x) nbins=np.max([20,x.size/1000]) plt.hist(x,bins=nbins,normed=True,histtype='step') plt.axvline(np.mean(self.chain[keys[i]][burn:]),lw=2.0,color='g') if i == (len(keys)-1): plt.xlabel(self.descr[keys[i]][3]) plt.text(0.05,0.7,stat_text(self.chain[keys[i]][burn:]),transform=plt.gca().transAxes) plt.gca().xaxis.set_major_locator(MaxNLocator(3, prune="both")) plt.gca().yaxis.set_major_locator(MaxNLocator(3, prune="both")) plt.gca().set_yticklabels([]) else: if i > j: plt.subplot(len(keys),len(keys),k) x=self.chain[keys[j]][burn:] y=self.chain[keys[i]][burn:] nbins=np.max([32,x.size/1000]) plt.hist2d(x,y,bins=[nbins,nbins],norm=LogNorm()) plt.axvline(np.mean(self.chain[keys[j]][burn:]),lw=2.0) plt.axhline(np.mean(self.chain[keys[i]][burn:]),lw=2.0) if j == 0: plt.ylabel(self.descr[keys[i]][3]) else: plt.gca().set_yticklabels([]) if i == (len(keys)-1): plt.xlabel(self.descr[keys[j]][3]) else: plt.gca().set_xticklabels([]) plt.gca().xaxis.set_major_locator(MaxNLocator(3, prune="both")) plt.gca().yaxis.set_major_locator(MaxNLocator(3, prune="both")) #plt.colorbar(pad=0.0,fraction=0.1) plt.subplots_adjust(hspace=0.15,wspace=0.1)
def inter_rater_variability(y1, y2, figsize=(4, 4), normed=True, raters=None, labels=None, out_file=None): plt.rcParams["font.family"] = "sans-serif" plt.rcParams["font.sans-serif"] = "FreeSans" plt.rcParams['font.size'] = 25 plt.rcParams['axes.labelsize'] = 20 plt.rcParams['axes.titlesize'] = 25 plt.rcParams['xtick.labelsize'] = 15 plt.rcParams['ytick.labelsize'] = 15 # fig = plt.figure(figsize=(3.5, 3)) if raters is None: raters = ['Rater 1', 'Rater 2'] if labels is None: labels = ['exclude', 'doubtful', 'accept'] fig, ax = plt.subplots(figsize=figsize) ax.set_aspect("equal") nbins = len(set(y1 + y2)) if nbins == 2: xlabels = [labels[0], labels[-1]] ylabels = [labels[0], labels[-1]] # Reverse x y1 = (np.array(y1) * -1).tolist() ylabels = labels xlabels = list(reversed(labels)) hist, xbins, ybins, _ = plt.hist2d(y1, y2, bins=nbins, cmap=plt.cm.viridis) xcenters = (xbins[:-1] + xbins[1:]) * 0.5 ycenters = (ybins[:-1] + ybins[1:]) * 0.5 total = np.sum(hist.reshape(-1)) celfmt = '%d%%' if normed else '%d' for i, x in enumerate(xcenters): for j, y in enumerate(ycenters): val = hist[i, j] if normed: val = 100 * hist[i, j] / total ax.text(x, y, celfmt % val, ha="center", va="center", fontweight="bold", color='w' if hist[i, j] < 15 else 'k') # plt.colorbar(pad=0.10) plt.grid(False) plt.xticks(xcenters, xlabels) plt.yticks(ycenters, ylabels, rotation='vertical', va='center') plt.xlabel(raters[0]) plt.ylabel(raters[1]) ax.yaxis.tick_right() ax.xaxis.set_label_position("top") if out_file is not None: fig.savefig(out_file, bbox_inches='tight', pad_inches=0, dpi=300) return fig
def heatmap(x, y, bins=20, zlabel='Anzahl', rasterized=True, ax=None, **kwargs): """Plot a heatmap of given data. Parameters: x (ndarray): x data. y (ndarray): y data. bins (None | int | [int, int] | array_like | [array, array]): The bin specification: - If int, the number of bins for the two dimensions (nx=ny=bins). - If [int, int], the number of bins in each dimension (nx, ny = bins). - If array_like, the bin edges for the two dimensions (x_edges=y_edges=bins). - If [array, array], the bin edges in each dimension (x_edges, y_edges = bins). The default value is 20. zlabel (str): Colobar label. ax (AxesSubplot): Axes to plot in. **kwargs: Additional keyword argumens passed to `plt.hist2d`. Returns: Return values of `plt.hist2d`: counts, xedges, yedges, Image. """ if ax is None: ax = plt.gca() def_kwargs = { 'bins': bins, 'rasterized': rasterized, 'cmap': plt.get_cmap('magma_r', 10), } def_kwargs.update(kwargs) ret = ax.hist2d(x, y, **def_kwargs) cb = ax.get_figure().colorbar(ret[3]) cb.set_label(zlabel) return ret