def create(self): self._fig = Figure(dpi=self.dpi) self._canvas = FigureCanvas(self._fig) self._canvas.setParent(self) self._canvas.setFocusPolicy(QtCore.Qt.ClickFocus) self._canvas.setFocus() axes_kwargs = {} if self.subplotx != 1 or self.subploty != 1: self.numplots = self.subplotx * self.subploty self._axes = [] self._cbaxes = [] self._twinaxes_x = [] self._twinaxes_y = [] for a in range(self.numplots): self._axes.append( self._fig.add_subplot(self.subploty, self.subplotx, a + 1, **axes_kwargs)) if self.do_cbars: cax, kw = make_axes(self._axes[-1], **self.cbar_kwargs) self._cbaxes.append(cax) if self.twinx: self._twinaxes_x.append( self._axes[-1].twiny()) # not a typo! if self.twiny: self._twinaxes_y.append( self._axes[-1].twinx()) # not a typo! # put main ax into foreground, otherwise the primary coords are # the second axes' ones for a in range(self.numplots): self._axes[a].set_zorder(100) else: self.numplots = 1 self._axes = self._fig.add_subplot(1, 1, 1, **axes_kwargs) if self.do_cbars: cax, kw = make_axes(self._axes, **self.cbar_kwargs) self._cbaxes = cax self.mpl_toolbar = CustomToolbar(self._canvas, self) vbox = QtWidgets.QVBoxLayout() vbox.addWidget(self._canvas) vbox.addWidget(self.mpl_toolbar) self.setLayout(vbox)
def _prepare_figure(self): fig, axes = plt.subplots(1, 2, figsize=(15, 7), sharex=True) fig.canvas.set_window_title(self._name) axes = ravel(axes) for ax in axes: ax.set_xlabel('Qubit 2 local rotations') ax.set_ylabel('Qubit 1 local rotations') cax_amps, kw = colorbar.make_axes(axes[0], aspect=40) cax_phas, kw = colorbar.make_axes(axes[1], aspect=40) cax_amps.set_title("$\\operatorname{Re}(S_{21})$", position=(0.5, -0.05)) cax_phas.set_title("$\\operatorname{Im}(S_{21})$", position=(0.5, -0.1)) return fig, axes, (cax_amps, cax_phas)
def colorbar(self, ax=None, **kwargs): if ax is None: ax=self.default_axes class MyFormatter(Formatter): def __init__(self, logscale, vmin, vmax): self.logscale = logscale self.vmin = vmin self.vmax = vmax self.scale = 10 **(_fr10(vmax - vmin)[1] - 1) if vmax != 0 and \ numpy.abs((vmin - vmax) / vmax) < 0.01: self.offset = vmax else: self.offset = 0 def get_offset(self): if self.offset != 0: return '+%.3g\n x%.3g' % (self.offset, self.scale) else: return r'x%.3g' % self.scale def __call__(self, data, pos=None): if self.offset != 0: return '%.3g' % ((data - self.offset) / self.scale) else: return '%.3g' % (data / self.scale) if not hasattr(ax, 'colorbarax'): ca = ax.get_figure().gca() ax.colorbarax, kwargs = mcb.make_axes(ax, **kwargs) ax.get_figure().sca(ca) color = self.last['color'] mcb.ColorbarBase(ax=ax.colorbarax, cmap=self.last['cmap'], norm=mcb.colors.Normalize( vmin=color.vmin, vmax=color.vmax), format = MyFormatter(color.logscale, color.vmin, color.vmax) )
def train_svm(self): width = float(self.sigma.text()) degree = int(self.degree.text()) self.axes.clear() self.axes.grid(True) self.axes.plot(self.data.x1_pos, self.data.x2_pos, 'ro') self.axes.plot(self.data.x1_neg, self.data.x2_neg, 'bo') # train svm labels = self.data.get_labels() print type(labels) lab = BinaryLabels(labels) features = self.data.get_examples() train = RealFeatures(features) kernel_name = self.kernel_combo.currentText() print "current kernel is %s" % (kernel_name) if kernel_name == "LinearKernel": gk = LinearKernel(train, train) gk.set_normalizer(IdentityKernelNormalizer()) elif kernel_name == "PolynomialKernel": gk = PolyKernel(train, train, degree, True) gk.set_normalizer(IdentityKernelNormalizer()) elif kernel_name == "GaussianKernel": gk = GaussianKernel(train, train, width) cost = float(self.cost.text()) print "cost", cost svm = LibSVM(cost, gk, lab) svm.train() svm.set_epsilon(1e-2) x, y, z = util.compute_output_plot_isolines(svm, gk, train) plt=self.axes.pcolor(x, y, z, shading='interp') CS=self.axes.contour(x, y, z, [-1,0,1], linewidths=1, colors='black', hold=True) #CS=self.axes.contour(x, y, z, linewidths=1, colors='black', hold=True) #CS=self.axes.contour(x, y, z, 5, linewidths=1, colors='black', hold=True) matplotlib.pyplot.clabel(CS, inline=1, fontsize=10) self.axes.set_xlim((-5,5)) self.axes.set_ylim((-5,5)) cmap = matplotlib.cm.jet norm = mpl.colors.Normalize(numpy.min(z), numpy.max(z)) print CS.get_clim() if not self.cax: self.cax, kw = make_axes(self.axes) # ColorbarBase derives from ScalarMappable and puts a colorbar # in a specified axes, so it has everything needed for a # standalone colorbar. There are many more kwargs, but the # following gives a basic continuous colorbar with ticks # and labels. cb1 = mpl.colorbar.ColorbarBase(self.cax, cmap=cmap, norm=norm) self.canvas.draw()
def _prepare_figure(self): fig, axes, caxes = super()._prepare_figure() plt.tight_layout(pad=2, h_pad=5, w_pad=0) caxes = [] for ax in axes: caxes.append(colorbar.make_axes(ax)[0]) return fig, axes, caxes
def make_plot(data, output_file): # Set plot parameters. titles = ('Clean Data $(X)$', 'Noisy Data $(Y)$', 'Reconstruction $(\hat{X})$', 'Residual $(|Y-M\hat{X}|)$') # Set vmax when mode = 'obj'. if opts.vmax_mode == 'obj': opts.vmax = np.max(data) # Set the colour levels. if isinstance(opts.levels, type(None)): colourbin = 0.05 else: colourbin = (opts.vmax - opts.vmin) / opts.levels boundaries = np.arange(opts.vmin, opts.vmax, colourbin) norm = BoundaryNorm(boundaries, cm.get_cmap(name=opts.cmap).N) # Make plot. fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True) for ax, x, title in zip(axes.flat, data, titles): if opts.white: x[x == 0.0] = np.nan im = ax.imshow(x, norm=norm, cmap=opts.cmap, interpolation=opts.interp) ax.set_title(title) ax.set_adjustable('box-forced') cax, kw = make_axes([ax for ax in axes.flat]) plt.colorbar(im, cax=cax, **kw) # Output file. plt.savefig(output_file) plt.close(fig) print 'Output saved to:', output_file
def plot_regions(boxes, interests, ax=None, xlabel='', ylabel='', xlim=None, ylim=None, bar=True): ft_off = 15 # Create figure and axes if ax == None: f, ax = plt.subplots(1, 1, figsize=(8, 7)) # Add the patch to the Axes #print(boxes) for b, ints in zip(boxes, interests): # print(b) lx, ly = b.low hx, hy = b.high c = plt.cm.jet(ints) rect = patches.Rectangle([lx, ly], (hx - lx), (hy - ly), linewidth=3, edgecolor='white', facecolor=c) ax.add_patch(rect) # plt.Rectangle([lx,ly],(hx - lx), (hy - ly)) if bar: cax, _ = cbar.make_axes(ax, shrink=0.8) cb = cbar.ColorbarBase(cax, cmap=plt.cm.jet) cb.set_label('Absolute Learning Progress', fontsize=ft_off + 5) cax.tick_params(labelsize=ft_off + 0) ax.set_xlim(left=xlim[0], right=xlim[1]) ax.set_ylim(bottom=ylim[0], top=ylim[1]) ax.set_xlabel(xlabel, fontsize=ft_off + 0) ax.set_ylabel(ylabel, fontsize=ft_off + 0) ax.tick_params(axis='both', which='major', labelsize=ft_off + 5) ax.set_aspect('equal', 'box')
def plot_orient_quiver(data, odata, mask=None, imfile='', fps=1, savename='', figsize=None): """ plot_orient_quiver(data, odata, mask=None, imfile='') """ import matplotlib.colors as mcolors import matplotlib.colorbar as mcolorbar pl.figure(tight_layout=False, figsize=figsize) if imfile is not None: bgimage = Im.open(extdir+prefix+'_0001.tif' if imfile is '' else imfile) pl.imshow(bgimage, cmap=cm.gray, origin='upper') #pl.quiver(X, Y, U, V, **kw) if mask is None: try: mask = np.all(np.isfinite(odata['orient']), axis=1) except ValueError: mask = np.isfinite(odata['orient']) n = odata.shape[-1] if odata.ndim > 1 else 1 ndex = np.repeat(np.arange(mask.sum()), n) nz = mcolors.Normalize() nz.autoscale(data['f'][mask]/fps) qq = pl.quiver( data['y'][mask][ndex], data['x'][mask][ndex], odata['cdisp'][mask][...,1].flatten(), -odata['cdisp'][mask][...,0].flatten(), color=cm.jet(nz(data['f'][mask]/fps)), scale=1, scale_units='xy') #pl.title(', '.join(imfile.split('/')[-1].split('_')[:-1]) if imfile else '') cax,_ = mcolorbar.make_axes(pl.gca()) cb = mcolorbar.ColorbarBase(cax, cmap=cm.jet, norm=nz) cb.set_label('time '+('(s)'if fps > 1 else '(frame)')) if savename: print "saving to", savename pl.savefig(savename) pl.show() return qq, cb
def plot_cmaes(mean, covariance, ints, X, sigma, currX=None, currInts=None, ax=None, xlim=[0., 1.], ylim=[0, 1], xlabel='jkl', ylabel='jhgj'): ax = ax or plt.gca() if len(ints) > 0: colors = [plt.cm.jet(i) for i in ints] #ax.scatter(X[:, 0], X[:, 1],c=colors, s=1, zorder=2, alpha=0.5) #ax.axis('equal') if currX is not None: currColors = [plt.cm.jet(i) for i in currInts] ax.scatter(currX[:, 0], currX[:, 1], c=currColors, s=5, zorder=2) draw_ellipse(mean, (sigma**2) * covariance, alpha=0.5) cax, _ = cbar.make_axes(ax) cb = cbar.ColorbarBase(cax, cmap=plt.cm.jet) cb.set_label('Interest') ax.axis('equal') ax.set_xlim(left=xlim[0], right=xlim[1]) ax.set_ylim(bottom=ylim[0], top=ylim[1])
def _prepare_figure(self): self._last_tr = None self._peaks_last_tr = None fig = plt.figure(figsize=(19, 8)) ax_trace = plt.subplot2grid((4, 8), (0, 0), colspan=4, rowspan=1) ax_map = plt.subplot2grid((4, 8), (1, 0), colspan=4, rowspan=3) ax_peaks = plt.subplot2grid((4, 8), (0, 4), colspan=4, rowspan=4) plt.tight_layout() ax_map.ticklabel_format(axis='x', style='plain', scilimits=(-2, 2)) ax_map.set_ylabel("Frequency, kHz") ax_map.set_xlabel(self._parameter_name[0].upper() + self._parameter_name[1:]) ax_trace.ticklabel_format(axis='x', style='sci', scilimits=(-2, 2)) ax_trace.set_xlabel("Frequency, Hz") ax_trace.set_ylabel("Emission power, dBm") ax_peaks.set_xlabel("Input power, dBm") ax_peaks.set_ylabel("Emission power, dBm") ax_map.autoscale_view(True, True, True) plt.tight_layout() cax, kw = colorbar.make_axes(ax_map, fraction=0.05, anchor=(0.0, 1.0)) cax.set_title("$P$,dBm") return fig, (ax_trace, ax_map, ax_peaks), (cax, )
def my_square_scatter(axes, x_array, y_array, z_array, min_z=None, max_z=None, size=0.5, **kwargs): size = float(size) if min_z is None: min_z = z_array.min() if max_z is None: max_z = z_array.max() normal = pylab.Normalize(min_z, max_z) colors = pylab.cm.jet(normal(z_array)) for x, y, c in zip(x_array, y_array, colors): square = pylab.Rectangle((x - size / 2, y - size / 2), size, size, color=c, **kwargs) axes.add_patch(square) axes.autoscale() cax, _ = cbar.make_axes(axes) cb2 = cbar.ColorbarBase(cax, cmap=pylab.cm.jet, norm=normal) return True
def plot_gmm(weights, means, covariances, X=None, ax=None, xlim=[0,1], ylim=[0,1], xlabel='', ylabel='', bar=True, bar_side='right',no_y=False, color=None): ft_off = 15 ax = ax or plt.gca() cmap = truncate_colormap(plt.cm.autumn_r, minval=0.2,maxval=1.0) #colors = [plt.cm.jet(i) for i in X[:, -1]] if X is not None: colors = [cmap(i) for i in X[:, -1]] sizes = [5+np.interp(i,[0,1],[0,10]) for i in X[:, -1]] ax.scatter(X[:, 0], X[:, 1], c=colors, s=sizes, zorder=2) #ax.axis('equal') w_factor = 0.6 / weights.max() for pos, covar, w in zip(means, covariances, weights): draw_ellipse(pos, covar, alpha=0.6, ax=ax, color=color) #plt.margins(0, 0) ax.set_xlim(left=xlim[0], right=xlim[1]) ax.set_ylim(bottom=ylim[0], top=ylim[1]) if bar: cax, _ = cbar.make_axes(ax, location=bar_side, shrink=0.8) cb = cbar.ColorbarBase(cax, cmap=cmap) cb.set_label('Absolute Learning Progress', fontsize=ft_off + 5) cax.tick_params(labelsize=ft_off + 0) cax.yaxis.set_ticks_position(bar_side) cax.yaxis.set_label_position(bar_side) #ax.yaxis.tick_right() if no_y: ax.set_yticks([]) else: ax.set_ylabel(ylabel, fontsize=ft_off + 5) #ax.yaxis.set_label_position("right") ax.set_xlabel(xlabel, fontsize=ft_off + 5) ax.tick_params(axis='both', which='major', labelsize=ft_off + 5) ax.set_aspect('equal', 'box')
def train_svm(self): width = float(self.sigma.text()) degree = int(self.degree.text()) self.axes.clear() self.axes.grid(True) self.axes.plot(self.data.x1_pos, self.data.x2_pos, 'ro') self.axes.plot(self.data.x1_neg, self.data.x2_neg, 'bo') # train svm labels = self.data.get_labels() print type(labels) lab = BinaryLabels(labels) features = self.data.get_examples() train = RealFeatures(features) kernel_name = self.kernel_combo.currentText() print "current kernel is %s" % (kernel_name) if kernel_name == "LinearKernel": gk = LinearKernel(train, train) gk.set_normalizer(IdentityKernelNormalizer()) elif kernel_name == "PolynomialKernel": gk = PolyKernel(train, train, degree, True) gk.set_normalizer(IdentityKernelNormalizer()) elif kernel_name == "GaussianKernel": gk = GaussianKernel(train, train, width) cost = float(self.cost.text()) print "cost", cost svm = LibSVM(cost, gk, lab) svm.train() svm.set_epsilon(1e-2) x, y, z = util.compute_output_plot_isolines(svm, gk, train) plt=self.axes.pcolor(x, y, z) CS=self.axes.contour(x, y, z, [-1,0,1], linewidths=1, colors='black', hold=True) #CS=self.axes.contour(x, y, z, linewidths=1, colors='black', hold=True) #CS=self.axes.contour(x, y, z, 5, linewidths=1, colors='black', hold=True) matplotlib.pyplot.clabel(CS, inline=1, fontsize=10) self.axes.set_xlim((-5,5)) self.axes.set_ylim((-5,5)) cmap = matplotlib.cm.jet norm = matplotlib.colors.Normalize(numpy.min(z), numpy.max(z)) print CS.get_clim() if not self.cax: self.cax, kw = make_axes(self.axes) # ColorbarBase derives from ScalarMappable and puts a colorbar # in a specified axes, so it has everything needed for a # standalone colorbar. There are many more kwargs, but the # following gives a basic continuous colorbar with ticks # and labels. cb1 = matplotlib.colorbar.ColorbarBase(self.cax, cmap=cmap, norm=norm) self.canvas.draw()
def _plot3DGrid(scores, paramsToPlot, keysToPlot, scoreLabel, greater_is_better, vrange, cmap, to_file): vmin = np.min(scores) vmax = np.max(scores) scoreGrid = np.reshape( scores, (len(paramsToPlot[keysToPlot[0]]), len(paramsToPlot[keysToPlot[1]]), len(paramsToPlot[keysToPlot[2]])) ) smallest_dim = np.argmin(scoreGrid.shape) if smallest_dim != 2: scoreGrid = np.swapaxes(scoreGrid, smallest_dim, 2) keysToPlot[smallest_dim], keysToPlot[2] = keysToPlot[2], keysToPlot[smallest_dim] nelements = scoreGrid.shape[2] nrows = np.floor(nelements ** 0.5).astype(int) ncols = np.ceil(1.0 * nelements / nrows).astype(int) fig, axes = plt.subplots( nrows=nrows, ncols=ncols, sharex="all", sharey="all", figsize=( int(round(len(paramsToPlot[keysToPlot[1]]) * ncols * 1.33)), int(round(len(paramsToPlot[keysToPlot[0]]) * nrows * 1.33)), ), ) if not greater_is_better: if cmap.endswith("_r"): cmap = cmap[:-2] else: cmap = cmap + "_r" i = 0 for ax in axes.flat: if vrange is not None: im = ax.imshow(scoreGrid[:, :, i], cmap=cmap, vmin=vrange[0], vmax=vrange[1]) else: im = ax.imshow(scoreGrid[:, :, i], cmap=cmap, vmin=vmin, vmax=vmax) ax.set_xlabel(keysToPlot[1]) ax.set_xticks(np.arange(len(paramsToPlot[keysToPlot[1]]))) ax.set_xticklabels(paramsToPlot[keysToPlot[1]]) ax.set_ylabel(keysToPlot[0]) ax.set_yticks(np.arange(len(paramsToPlot[keysToPlot[0]]))) ax.set_yticklabels(paramsToPlot[keysToPlot[0]]) ax.set_title(keysToPlot[2] + " = " + str(paramsToPlot[keysToPlot[2]][i])) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.spines["left"].set_visible(False) i += 1 if i == nelements: break if scoreLabel is not None: fig.suptitle(scoreLabel, fontsize=18) else: fig.suptitle("Score", fontsize=18) fig.subplots_adjust(right=0.8) cbar = cb.make_axes(ax, location="right", fraction=0.03) fig.colorbar(im, cax=cbar[0]) plt.savefig(to_file) plt.close()
def plot_distribution2(probabilitydist, data, **kwargs): """ Plot distributions over the time (x-axis) :param probabilitydist: the forecasted probability distributions to plot :param data: the original test sample :keyword start_at: the time index (inside of data) to start to plot the probability distributions :keyword ax: a matplotlib axis. If no value was provided a new axis is created. :keyword cmap: a matplotlib colormap name, the default value is 'Blues' :keyword quantiles: the list of quantiles intervals to plot, e. g. [.05, .25, .75, .95] :keyword median: a boolean value indicating if the median value will be plot. """ import matplotlib.colorbar as cbar import matplotlib.cm as cm ax = kwargs.get('ax', None) if ax is None: fig, ax = plt.subplots(nrows=1, ncols=1, figsize=[15, 5]) l = len(probabilitydist) cmap = kwargs.get('cmap', 'Blues') cmap = plt.get_cmap(cmap) start_at = kwargs.get('start_at', 0) x = [k + start_at for k in range(l + 1)] qt = kwargs.get('quantiles', None) if qt is None: qt = [round(k, 2) for k in np.arange(.05, 1., .05)] qt.insert(0, .01) qt.append(.99) lq = len(qt) normal = plt.Normalize(min(qt), max(qt)) scalarMap = cm.ScalarMappable(norm=normal, cmap=cmap) for ct in np.arange(1, int(lq / 2) + 1): y = [[data[start_at], data[start_at]]] for pd in probabilitydist: qts = pd.quantile([qt[ct - 1], qt[-ct]]) y.append(qts) ax.fill_between(x, [k[0] for k in y], [k[1] for k in y], facecolor=scalarMap.to_rgba(ct / lq)) if kwargs.get('median', True): y = [data[start_at]] for pd in probabilitydist: qts = pd.quantile(.5) y.append(qts[0]) ax.plot(x, y, color='red', label='Median') cax, _ = cbar.make_axes(ax) cb = cbar.ColorbarBase(cax, cmap=cmap, norm=normal) cb.set_label('Density')
def __init__(self, ax_src, ax=None, *args, **kwargs): self.ax_src = ax_src if ax is None: import matplotlib.pyplot as plt fig, ax = plt.subplots() fig.canvas.set_window_title('Figure %i: Zoom of figure %i' % (fig.number, ax_src.figure.number)) self.ax = ax self.point = ax.plot([np.mean(ax.get_xlim())], [np.mean(ax.get_ylim())], 'ro', visible=False, zorder=10)[0] self.make_plot(*args, **kwargs) self.enable_zoom() if isinstance(ax, SubplotBase): slider_ax, kw = mcbar.make_axes_gridspec(ax, orientation='horizontal', location='bottom') else: slider_ax, kw = mcbar.make_axes(ax, position='bottom', orientation='horizontal') slider_ax.set_aspect('auto') slider_ax._hold = True self.slider = Slider(slider_ax, 'Zoom', 0, 99.5, valfmt='%1.2g %%') self.slider.set_val(90) self.slider.on_changed(self.adjust_limits) self.adjust_limits(90)
def makeFrameImage(basename, pixels, outputpath): """ Create the frame image. """ x_min = 0 x_max = 256 y_min = 0 y_max = 256 w = 256 h = 256 ## The maximum count value. C_max = max(pixels.values()) # Create the figure. plt.close('all') figsize = 5.0 #max(radius*0.8, 3.0) ## The figure for the frame. frfig = plt.figure(1, figsize=(figsize*1.27, figsize), dpi=150, facecolor='w', edgecolor='w') ## The frame axes. frfigax = frfig.add_subplot(111, axisbg='#222222') # Add the frame background (blue). frfigax.add_patch(plt.Rectangle((0,0),256,256,facecolor='#82bcff')) # Add a grid. plt.grid(1) # Select the "hot" colour map for the pixel counts. cmap = plt.cm.hot colax, _ = colorbar.make_axes(plt.gca()) col_max = 10*(np.floor(C_max/10.)+1) colorbar.ColorbarBase(colax,cmap=cmap,norm=colors.Normalize(vmin=0,vmax=col_max)) # Loop over the pixels and plot them. for X, C in pixels.iteritems(): x = X % 256; y = X / 256 scaled_C = float(C)/float(col_max) frfigax.add_patch(plt.Rectangle((x,y),1,1,edgecolor=cmap(scaled_C),facecolor=cmap(scaled_C))) # Set the axis limits based on the cluster radius. b = 3 # border frfigax.set_xlim([0 - b, 256 + 3]) frfigax.set_ylim([0 - b, 256 + 3]) # Save the figure. frfig.savefig(outputpath + "/%s.png" % (basename))
def activate(self): """Activate the proxy colorbar.""" # Create matplotlib axes which will hold the colorbar. axes = tuple(self.element.axes.proxy._axes.values())[0] caxes = make_axes(axes, location=self.element.location, aspect=self.element.aspect_ratio)[0] self._caxes = caxes
def plot3DGrid(scores, paramsToPlot, keysToPlot, scoreLabel, vrange): """ Plots a grid of heatmaps of scores, over the paramsToPlot :param scores: A list of scores, estimated using parallelizeScore :param paramsToPlot: The parameters to plot, chosen automatically by plotScores :param scoreLabel: The specified score label (dependent on scoring metric used) :param vrange: The visible range of the heatmap (range you wish the heatmap to be specified over) """ vmin = np.min(scores) vmax = np.max(scores) scoreGrid = np.reshape( scores, (len(paramsToPlot[keysToPlot[0]]), len( paramsToPlot[keysToPlot[1]]), len(paramsToPlot[keysToPlot[2]]))) nelements = scoreGrid.shape[2] nrows = np.floor(nelements**0.5).astype(int) ncols = np.ceil(1. * nelements / nrows).astype(int) fig, axes = plt.subplots( nrows=nrows, ncols=ncols, sharex='all', sharey='all', figsize=(int(round(len(paramsToPlot[keysToPlot[1]]) * ncols * 1.33)), int(round(len(paramsToPlot[keysToPlot[0]]) * nrows * 1.33)))) i = 0 for ax in axes.flat: if vrange is not None: im = ax.imshow(scoreGrid[:, :, i], cmap='jet', vmin=vrange[0], vmax=vrange[1]) else: im = ax.imshow(scoreGrid[:, :, i], cmap='jet', vmin=vmin, vmax=vmax) ax.set_xlabel(keysToPlot[1]) ax.set_xticks(np.arange(len(paramsToPlot[keysToPlot[1]]))) ax.set_xticklabels(paramsToPlot[keysToPlot[1]]) ax.set_ylabel(keysToPlot[0]) ax.set_yticks(np.arange(len(paramsToPlot[keysToPlot[0]]))) ax.set_yticklabels(paramsToPlot[keysToPlot[0]]) ax.set_title(keysToPlot[2] + ' = ' + str(paramsToPlot[keysToPlot[2]][i])) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.spines["left"].set_visible(False) i += 1 if scoreLabel is not None: fig.suptitle(scoreLabel, fontsize=18) else: fig.suptitle('Score', fontsize=18) fig.subplots_adjust(right=0.8) cbar = cb.make_axes(ax, location='right', fraction=0.03) fig.colorbar(im, cax=cbar[0]) plt.show()
def plot_experiment(self, ax): data = self._X_exp, self._Y_exp, np.abs(self._C_exp - self._C_exp[0,0]) img1 = ax.pcolormesh(*data, rasterized=True, vmin=0, vmax=.022, cmap = self._cmap) cbaxes1 = clb.make_axes(ax, location="top", shrink=0.8, aspect=50, pad=0.09, anchor=(0,0))[0] cb = plt.colorbar(img1, ax=ax, cax=cbaxes1, orientation="horizontal") ax.set_xlabel('Current ($10^{-4}$ A)'); ax.set_ylabel('$\omega_d/2\pi$ (GHz)'); cb.ax.set_title(r"$|\Delta S^{exp}_{21}|$", position=(1.125,-2.5)) loc = ticker.MultipleLocator(base=0.01) # this locator puts ticks at regular intervals cb.locator = loc cb.update_ticks() plt.text(-0.15, 1.1, "(a)", fontdict={"name": "STIX"}, fontsize=17, transform=ax.transAxes) plt.text(.53, .815, r"$\omega_2(I)/2\pi$", fontdict={"name": "STIX"}, fontsize=7.5, transform=ax.transAxes, ha='center') plt.text(.54, .355, r"$\omega_1(I)/2\pi$", fontdict={"name": "STIX"}, fontsize=7.5, transform=ax.transAxes, ha='center') ax.annotate('spurious\nresonance', xy=(5, 5.37), xytext=(5.1, 5.45), ha="center", fontsize=10, arrowprops=dict(facecolor='black', width =1, headwidth = 5, headlength = 7, shrink=0.05)) ax.annotate("1", xy=(3.5, 5.2325), xytext=(3.64, 5.2075), ha="right", fontsize=10, arrowprops=dict(facecolor='black', width =.5, headwidth = 3, headlength = 3.5, shrink=0.05)) ax.annotate('2', xy=(5.07, 5.21), xytext=(5.07, 5.18), ha="center", fontsize=10, arrowprops=dict(facecolor='black', width=.5, headwidth=3, headlength=3.5, shrink=0.05)) ax.annotate('3', xy=(3.31, 5.25), xytext=(3.31, 5.265), ha="center", fontsize=10, arrowprops=dict(facecolor='black', width=.5, headwidth=3, headlength=3.5, shrink=0.05)) ax.annotate('4', xy=(4.9, 5.195), xytext=(4.8, 5.195), ha="center", va="top", fontsize=10, arrowprops=dict(facecolor='black', width=.5, headwidth=3, headlength=3.5, shrink=0.05)) ax.annotate("5", xy=(3.516, 5.177), xytext=(3.61, 5.1795), ha="center", va="bottom", fontsize=10, arrowprops=dict(facecolor='black', width=.5, headwidth=3, headlength=3.5, shrink=0.05)) J_eff = 8e-3*np.sqrt(2) lower_branch = 5.283 x_pos = 5.41 bar_size = 5e-2 # ax.plot([x_pos+bar_size]*2, [lower_branch, lower_branch+J_eff], color="black", lw=.5) ax.plot([x_pos, x_pos + bar_size], [lower_branch] * 2, color="black", lw=.5) ax.plot([x_pos, x_pos + bar_size], [lower_branch+J_eff] * 2, color="black", lw=.5) ax.annotate(r"J$\sqrt{2}$", xy=(x_pos+bar_size+.01, lower_branch+J_eff/2), xytext=(x_pos+bar_size+.11, lower_branch+.01), ha="left", va="bottom", fontsize=7, arrowprops=dict(facecolor="black", width=.1, headwidth=3, headlength=3.5, shrink=0.1)) self._zoom(ax, data, vmin=0, vmax = .022)
def _prepare_figure(self): fig, axes = plt.subplots(1, 2, subplot_kw=dict(projection='polar'), figsize=(12, 7)) plt.tight_layout(pad=4) caxes = [] for ax in axes: caxes.append(colorbar.make_axes(ax, locaion="bottom", orientation="horizontal", pad=0.1, shrink=0.7, aspect=40)[0]) return fig, axes, caxes
def _draw_colorbar( stat_map_img, axes, threshold=.1, nb_ticks=5, edge_color="0.5", edge_alpha=1, aspect=40, fraction=0.025, anchor=(10.0, 0.5), ): if isinstance(stat_map_img, str): stat_map_img = path.abspath(path.expanduser(stat_map_img)) stat_map_img = nib.load(stat_map_img) _, _, vmin, vmax, = _get_colorbar_and_data_ranges( _safe_get_data(stat_map_img, ensure_finite=True), None, "auto", "") cbar_ax, p_ax = make_axes( axes, aspect=aspect, fraction=fraction, # pad=-0.5, anchor=anchor, # panchor=(-110.0, 0.5), ) ticks = np.linspace(vmin, vmax, nb_ticks) bounds = np.linspace(vmin, vmax, MYMAP.N) norm = mcolors.Normalize(vmin=vmin, vmax=vmax) # some colormap hacking cmaplist = [MYMAP(i) for i in range(MYMAP.N)] istart = int(norm(-threshold, clip=True) * (MYMAP.N - 1)) istop = int(norm(threshold, clip=True) * (MYMAP.N - 1)) for i in range(istart, istop): cmaplist[i] = (0.5, 0.5, 0.5, 1.) # just an average gray color our_cmap = MYMAP.from_list('Custom cmap', cmaplist, MYMAP.N) cbar = ColorbarBase( cbar_ax, ticks=ticks, norm=norm, orientation="vertical", cmap=our_cmap, boundaries=bounds, spacing="proportional", format="%.2g", ) cbar.outline.set_edgecolor(edge_color) cbar.outline.set_alpha(edge_alpha) cbar_ax.yaxis.tick_left() tick_color = 'k' for tick in cbar_ax.yaxis.get_ticklabels(): tick.set_color(tick_color) cbar_ax.yaxis.set_tick_params(width=0) return cbar_ax, p_ax
def _prepare_figure(self): fig, axes = plt.subplots(1, 2, figsize=(15,7), sharey=True, sharex=True) ax_amps, ax_phas = axes ax_amps.ticklabel_format(axis='x', style='sci', scilimits=(-2,2)) ax_amps.set_ylabel("Frequency [GHz]") xlabel = self._parameter_names[0][0].upper()+self._parameter_names[0][1:] ax_amps.set_xlabel(xlabel) ax_phas.ticklabel_format(axis='x', style='sci', scilimits=(-2,2)) ax_phas.set_xlabel(xlabel) plt.tight_layout(pad=2, h_pad=-10) cax_amps, kw = colorbar.make_axes(ax_amps, aspect=40) cax_phas, kw = colorbar.make_axes(ax_phas, aspect=40) cax_amps.set_title("$|S_{21}|$", position=(0.5,-0.05)) cax_phas.set_title("$\\angle S_{21}$\n [%s]"%self._phase_units, position=(0.5,-0.1)) ax_amps.grid() ax_phas.grid() fig.canvas.set_window_title(self._name) return fig, axes, (cax_amps, cax_phas)
def draw_competence_grid(ax, comp_grid, x_bnds, y_bnds, bar=True): comp_grid[comp_grid == 100] = 1000 ax.pcolor(x_bnds, y_bnds, np.transpose(comp_grid),cmap=plt.cm.gray, edgecolors='k', linewidths=2, alpha=0.3) if bar: cax, _ = cbar.make_axes(ax,location='left') cb = cbar.ColorbarBase(cax, cmap=plt.cm.gray) cb.set_label('Competence') cax.yaxis.set_ticks_position('left') cax.yaxis.set_label_position('left')
def deconvolve(fluor, pos, prctile=10, A0=0.15, lamb0=0.15, do_plot=True): nc, nt = fluor.shape # euclidean distances dist = all_distances(pos) ij, distvec = submission.adjacency2vec(dist) # Pearson correlation coefficients for small fluorescence values corr = threshold_corr(fluor, prctile) ij, corrvec = submission.adjacency2vec(corr) # from Stetter et al 2012 # A = 0.15 # lamb = 0.15 A, lamb = fit_gauss_blur(distvec, corrvec, A0, lamb0) # convolution matrix (nc x nc) C = gauss((A / 2., lamb), dist) # why divide by 2? # # we set the diagonal to zero, since we don't consider a cell's own # # fluorescence # C[np.diag_indices(nc)] = 0 # F + CF = F_sc # (I + C)F = F_sc deconv = np.linalg.solve((np.eye(nc) + C), fluor) if do_plot: corr2 = threshold_corr(deconv, prctile) ij, corrvec2 = submission.adjacency2vec(corr2) A2, lamb2 = fit_gauss_blur(distvec, corrvec2, A0, lamb0) fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, sharey=True, figsize=(8, 8)) plot_hist_fit(distvec, corrvec, (A, lamb), ax=ax1) plot_hist_fit(distvec, corrvec2, (A2, lamb2), ax=ax2) ax1.set_title('Original', fontsize=18) ax2.set_title( 'Deconvolved', fontsize=18) ax2.set_xlabel('Distance (mm)', fontsize=14) ax1.set_ylabel('Correlation coefficient', fontsize=14) ax2.set_ylabel('Correlation coefficient', fontsize=14) cax, kw = colorbar.make_axes((ax1, ax2)) ax2.images[0].set_clim(ax1.images[0].get_clim()) cb = plt.colorbar(ax1.images[0], cax=cax, **kw) cb.set_label('Density') plt.show() return deconv
def loopGenerator(self): # Put the code of your loop here pypdd = self.mainWindow.ppdd for f in self.filenames: self.progress.setValue(self.success + self.fail + 1) try: pypdd.readfile(f) pypdd.find_peaks() pypdd.filt_move() pypdd.find_symmetry_axis() pypdd.abel() outputfile = os.path.join( self.outputpath, os.path.basename(f).rsplit('.', 1)[0] + '.txt') outputfigregion = os.path.join( self.outputpath, os.path.basename(f).rsplit('.', 1)[0] + '-region.png') outputfigdensity = os.path.join( self.outputpath, os.path.basename(f).rsplit('.', 1)[0] + '-density.png') np.savetxt(outputfile, pypdd.AIM, fmt='%1.6f', newline=os.linesep) fig = Figure(figsize=(16, 8)) canvas = FigureCanvas(fig) ax = fig.add_subplot(111) pypdd.plot_raw(ax, region=(pypdd.xmin, pypdd.xmax, pypdd.ymin, pypdd.ymax)) fig.savefig(outputfigregion) fig = Figure(figsize=(16, 8)) canvas = FigureCanvas(fig) ax = fig.add_subplot(111) cax, _ = colorbar.make_axes(ax, fraction=0.05, pad=0.01, aspect=20) pypdd.plot_density(ax, cax) fig.savefig(outputfigdensity) self.status.showMessage( 'Successfully saved file: {0}'.format(outputfile)) self.success += 1 except Exception as e: #error = QErrorMessage(self) #error.showMessage(str(e)) #error.exec_() self.failed_files.append(f) self.fail += 1 yield
def plot3DGrid(scores, paramsToPlot, keysToPlot, scoreLabel, vrange): """ Plots a grid of heatmaps of scores, over the paramsToPlot :param scores: A list of scores, estimated using parallelizeScore :param paramsToPlot: The parameters to plot, chosen automatically by plotScores :param scoreLabel: The specified score label (dependent on scoring metric used) :param vrange: The visible range of the heatmap (range you wish the heatmap to be specified over) """ vmin = np.min(scores) vmax = np.max(scores) scoreGrid = np.reshape(scores, (len(paramsToPlot[keysToPlot[0]]), len( paramsToPlot[keysToPlot[1]]), len(paramsToPlot[keysToPlot[2]]))) smallest_dim = np.argmin(scoreGrid.shape) if smallest_dim != 2: scoreGrid = np.swapaxes(scoreGrid, smallest_dim, 2) keysToPlot[smallest_dim], keysToPlot[2] = keysToPlot[2], keysToPlot[smallest_dim] nelements = scoreGrid.shape[2] nrows = np.floor(nelements ** 0.5).astype(int) ncols = np.ceil(1. * nelements / nrows).astype(int) fig, axes = plt.subplots(nrows=nrows, ncols=ncols, sharex='all', sharey='all', figsize=(int(round(len( paramsToPlot[keysToPlot[1]]) * ncols * 1.33)), int(round(len(paramsToPlot[keysToPlot[0]]) * nrows * 1.33)))) i = 0 for ax in axes.flat: if vrange is not None: im = ax.imshow(scoreGrid[:, :, i], cmap='jet', vmin=vrange[0], vmax=vrange[1]) else: im = ax.imshow(scoreGrid[:, :, i], cmap='jet', vmin=vmin, vmax=vmax) ax.set_xlabel(keysToPlot[1]) ax.set_xticks(np.arange(len(paramsToPlot[keysToPlot[1]]))) ax.set_xticklabels(paramsToPlot[keysToPlot[1]]) ax.set_ylabel(keysToPlot[0]) ax.set_yticks(np.arange(len(paramsToPlot[keysToPlot[0]]))) ax.set_yticklabels(paramsToPlot[keysToPlot[0]]) ax.set_title(keysToPlot[2] + ' = ' + str(paramsToPlot[keysToPlot[2]][i])) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.spines["left"].set_visible(False) i += 1 if i == nelements: break if scoreLabel is not None: fig.suptitle(scoreLabel, fontsize=18) else: fig.suptitle('Score', fontsize=18) fig.subplots_adjust(right=0.8) cbar = cb.make_axes(ax, location='right', fraction=0.03) fig.colorbar(im, cax=cbar[0]) plt.show()
def _create_colorbars(fig, axes, qm, ticks): """ """ for i in range(axes.shape[1]): parents = [ax for ax in axes[:,i].flat] cax, kw = make_axes(parents, location='bottom', pad=0.03, shrink=1.0, fraction=0.01, aspect=20) fig.colorbar(mappable=qm[i], cax=cax, orientation='horizontal', ticks=ticks[i], drawedges=False, spacing='uniform') return
def make_cax_for_given_axes(parent_ax, location='right', fraction=0.15, shrink=0.99, **kws): ''' #Description: This function creates a cax (a colorbar axes) by borrowing space from the parent axes. ### derived from: https://matplotlib.org/3.1.0/api/colorbar_api.html?highlight=colorbar%20make_axes#matplotlib.colorbar.make_axes #Available parameters are: orientation (string): vertical or horizontal fraction (float = 0.15): fraction of original axes to use for colorbar pad (float): fraction of original axes between colorbar and new image axes pad = 0.05 if cax is to be vertical; pad = 0.15 if cax is to be horizontal; shrink (float = 1.0): fraction by which to multiply the size of the colorbar aspect (float = 20): ratio of long to short dimensions anchor ( 2D-tuple): the anchor point of the cax from the parent axes (0.0, 0.5) if cax is to be vertical; (0.5, 1.0) if cax is to be horizontal; panchor (2D-tuple):the anchor point of the colorbar parent axes. If False, the parent axes' anchor will be unchanged (1.0, 0.5) if cax is to be vertical; (0.5, 0.0) if cax is to be horizontal; #returns: cax, cax_kwds ''' cax, cax_kwds = colorbar.make_axes(parent_ax, location=location, fraction=fraction, shrink=shrink, **kws) return cax, cax_kwds
def createColorbar(ax, **kwargs): cbLabel = kwargs.pop('label', '') #orientation = kwargs.get('orientation', 'horizontal') rasterized = kwargs.pop('rasterized', None) labelpad = kwargs.pop('labelpad', None) mappable = kwargs.pop('mappable', None) cax, kwargs = make_axes(ax, **kwargs) globalAxesSettings(cax) fig = ax.figure cb = fig.colorbar(mappable, ax=ax, cax=cax, **kwargs) cb.set_label(cbLabel, labelpad=labelpad) cb.solids.set_rasterized(rasterized) return cax
def dwt_heatmap(coefs, ax, cmap_name, approx, max_level, sig_ax, cbar_limit, xticks, yticks): if xticks: ax.set_xticks( np.array(list(range(0, len(coefs[0]), 5))) / len(coefs[0])) ax.set_xticklabels(range(0, len(coefs[-1]), 5)) else: ax.set_xticks([]) if yticks: ax.set_yticks([(i / len(coefs)) - (1 / (len(coefs) * 2)) for i in range(len(coefs), 0, -1)]) if not approx and len(coefs) == max_level: ax.set_yticklabels(reversed(range(1, max_level + 1))) elif approx and len(coefs) == max_level + 1: labels = ['approx'] + list(reversed(range(1, max_level + 1))) ax.set_yticklabels(labels) elif not approx and len(coefs) != max_level: ax.set_yticklabels(range(max_level - len(coefs) + 1, max_level + 1)) elif approx and len(coefs) != max_level + 1: ax.set_yticklabels(['approx'] + list(reversed(range(1, len(coefs))))) ax.set_ylabel('levels') norm = col.Normalize(vmin=-cbar_limit, vmax=cbar_limit) cmap = plt.get_cmap(cmap_name) colbar_axis = colbar.make_axes([ax, sig_ax], 'right') colbar.ColorbarBase(colbar_axis[0], cmap, norm) height = 1 / len(coefs) for level, coef_level in enumerate(coefs): width = 1 / len(coef_level) for n, coef in enumerate(coef_level): bottom_left = (0 + (n * width), 1 - ((level + 1) * height)) color = cmap(norm(coef)) heat_square = pat.Rectangle(bottom_left, width, height, color=color) ax.add_patch(heat_square)
def xplot(self): self.progressdialog.Update(10) ax = self.axes[0] ax.set_title('RHOB x DT') ax.set_xlabel('DT ($\mu$s/ft)') ax.set_ylabel('RHOB (g/cc)') ax.grid(which='both') cmap = cm.get_cmap('jet') #CREATE COLORBAR normalize = colors.Normalize(vmin=7, vmax=20) color = [ cmap(normalize(value)) for value in self.welllogs[self.filename]['CALI'] ] if self.alllogs: ax.set_xlim(35, 180) ax.set_ylim(1.2, 4.5) n_itens = len(self.welllogs.keys()) i = 1 for key in self.welllogs.keys(): self.progressdialog.Update(10 + int(80 * i / n_itens)) i += 1 color = [ cmap(normalize(value)) for value in self.welllogs[key]['CALI'] ] ax.scatter(self.welllogs[key]['DT'], self.welllogs[key]['RHOB'], color=color, marker='.') #PLOT SCATTER WITH COLORS else: self.progressdialog.Update(50) ax.set_xlim(35, 180) ax.set_ylim(1.2, 3.4) color = [ cmap(normalize(value)) for value in self.welllogs[self.filename]['CALI'] ] ax.scatter(self.welllogs[self.filename]['DT'], self.welllogs[self.filename]['RHOB'], color=color, marker='.') #PLOT SCATTER WITH COLORS cax, _ = colorbar.make_axes(ax) cbar = colorbar.ColorbarBase(cax, cmap=cmap, norm=normalize) cbar.ax.set_ylabel('CALIPER') self.progressdialog.Update(100)
def plot_data(ax): #-- rectangle lower left corner positions h = 0.7 # height of the rectangles Y = np.arange(1-h/2,7+h/2,1) # y-coord X = [1, 2, 1, 2, 4, 0.6, 200] # x-coord W = [200, 14, 3, 2, 564, 1.4, 1e4] # width (+1) of the rectangles vs = [0, -.5, 0.7, 0.8, 0.2, -0.3, 0.4] # [experimental --> theoretical] in [-1,1] normal = pl.Normalize(-1,1) colors = pl.cm.jet(normal(vs)) X_txt = [5, 18, 4, 4, 7, 1.3, 800] txt = ['ICLS/GFM', 'droplet assembly', 'hydrodynamic interaction I', 'hydrodynamic interaction II', 'droplets in turbulence', 'liquid-infused surfaces','DLCD'] for i,y in enumerate(Y): rect = patches.Rectangle( (X[i],y), W[i]-1,h, color=colors[i]) ax.add_patch(rect) ax.text(X_txt[i],y+0.2, txt[i]) cax, _ = cbar.make_axes(ax) cb2 = cbar.ColorbarBase(cax, cmap=pl.cm.jet,norm=normal) ax.plot([1,1],[0,8], linestyle='--',color='C7', alpha=0.5) #-- plot limit xmin = 0.5 xmax = 1.5e4 ymin = 0.4 ymax = 7.6 ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) ax.set_xscale('log') ax.set_xlabel(r'$N$') ax.set_ylabel(r'Paper') return ax
def stripes(values, xlim=None, labels=None, vmin=0, vmax=None, ax=None, cax=None, title=None, cmap=None, cbar_kw=None): ax = ax or plt.gca() x1, x2 = xlim = (xlim or (0, len(values[0])-1)) ax.set_xlim(xlim) if hasattr(x1, 'date'): x1, x2 = date2num(x1), date2num(x2) bar_size = .5 hals_size = bar_size/2 ax.set_ylim((hals_size-1, len(values)-hals_size)) if vmax is None: vmax = np.max([np.max(v) for v in values]) norm = Normalize(vmin, vmax, clip=True) cmap = plt.get_cmap(cmap or 'gist_heat_r') for i, vals in enumerate(reversed(values)): ax.imshow(vals[np.newaxis, :], extent=(x1, x2, i-hals_size, i+hals_size), cmap=cmap, norm=norm) ax.yaxis.set_ticks(range(0, len(values))) labels = reversed(labels) if labels else range(len(values), 0, -1) ax.set_yticklabels(labels) ax.set_aspect('auto') if not cax: # should've used a AxesGrid/cbar.make_axes_gridspec instead of this trickery cax, kw = cbar.make_axes(ax, location='top', shrink=.7, pad=.5/len(values), aspect=40) if title is not None: cax.set_title(title) sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) sm._A = [] cbar_kw_ = dict(orientation='horizontal') cbar_kw_.update(cbar_kw or {}) ax.figure.colorbar(sm, cax=cax, **cbar_kw_) plt.sca(ax) return ax, cax
def add_color_bar(self, label: str or None = None): if self._scores is not None: if self._ax_color_bar is None: # if axis for color bar not yet created # create axis for color bar self._ax_color_bar = mpl_colorbar.make_axes( self._axes, Location='right')[0] self._ax_color_bar.set_ylim( [self._scores_norm_min, self._scores_norm_max]) cb = mpl_colorbar.ColorbarBase( self._ax_color_bar, cmap=self._color_style, norm=self._color_map_norm, orientation='vertical', ) if label: cb.set_label(label) else: raise ValueError('Set scores before adding a color bar.')
def draw_por_colorbar(array3d): # cmap ref: https://matplotlib.org/examples/color/colormaps_reference.html cmap = cm.get_cmap("plasma") normalize = matplotlib.colors.Normalize(vmin=min(array3d[:, 2]), vmax=max(array3d[:, 2])) colors = [cmap(normalize(value)) for value in array3d[:, 2]] fig, ax = pyplot.subplots() ax.scatter(array3d[:, 0], array3d[:, 1], color=colors, marker='.', s=1.5) pyplot.xlabel('Recall') pyplot.ylabel('Precision') pyplot.ylim(0, 1) pyplot.xlim(0, 1) cax, _ = colorbar.make_axes(ax) colorbar.ColorbarBase(cax, cmap=cmap, norm=normalize) pyplot.xlabel('Quota \ngreen') pyplot.ylabel('Quota')
def colorbar(self, mappable, cax=None, ax=None, **kw): """ Create a colorbar for a ScalarMappable instance, *mappable*. Documentation for the pylab thin wrapper: %(colorbar_doc)s """ if ax is None: ax = self.gca() use_gridspec = kw.pop("use_gridspec", True) if cax is None: if use_gridspec and isinstance(ax, SubplotBase): cax, kw = cbar.make_axes_gridspec(ax, **kw) else: cax, kw = cbar.make_axes(ax, **kw) cax.hold(True) cb = cbar.colorbar_factory(cax, mappable, **kw) self.sca(ax) return cb
def _init_plot_eval(self): from panobbgo.ui import NavigationToolbar from matplotlib import colorbar import gtk mx = self.problem.dim vbox = gtk.VBox(False, 0) if mx <= 1: vbox.add(gtk.Label("not enough dimensions")) return self.eval_canvas, fig = self.ui.mk_canvas() self.eval_ax = fig.add_subplot(111) self.eval_cb_ax, _ = colorbar.make_axes(self.eval_ax) spinner_hbox = gtk.HBox(gtk.FALSE, 5) def mk_cb(l): cb = gtk.combo_box_new_text() [cb.append_text('Axis %d' % i) for i in range(0, mx)] cb.set_active(mk_cb.i) mk_cb.i += 1 spinner_hbox.add(gtk.Label(l)) spinner_hbox.add(cb) return cb mk_cb.i = 0 cb_0 = mk_cb("X Coord:") cb_1 = mk_cb("Y Coord:") for cb in [cb_0, cb_1]: cb.connect('changed', self.on_eval_spinner, cb_0, cb_1) self.eval_btn = btn = gtk.Button("Redraw") btn.connect('clicked', self.on_eval_spinner, cb_0, cb_1) spinner_hbox.add(btn) vbox.pack_start(self.eval_canvas, True, True) vbox.pack_start(spinner_hbox, False, False) self.toolbar = NavigationToolbar(self.eval_canvas, self) vbox.pack_start(self.toolbar, False, False) return "Values", vbox
def plotSolution(self, heatExch, axes, var, zmin = None, zmax = None, cmap = cm.jet): vertexIDs = self.mesh._orderedCellVertexIDs vertexCoords = self.mesh.vertexCoords xCoords = np.take(vertexCoords[0], vertexIDs) yCoords = np.take(vertexCoords[1], vertexIDs) polys = [] for x, y in zip(xCoords.swapaxes(0,1), yCoords.swapaxes(0,1)): if hasattr(x, 'mask'): x = x.compressed() if hasattr(y, 'mask'): y = y.compressed() polys.append(zip(x,y)) from matplotlib.collections import PolyCollection # Set limits xmin = xCoords.min() xmax = xCoords.max() ymin = yCoords.min() ymax = yCoords.max() axes.set_xlim(xmin=xmin, xmax=xmax) axes.set_ylim(ymin=ymin, ymax=ymax) Z = var.value if (zmin is None): zmin = np.min(Z) if (zmax is None): zmax = np.max(Z) norm = Normalize(zmin, zmax) collection = PolyCollection(polys, cmap = cmap, norm = norm) collection.set_linewidth(0.) axes.add_collection(collection) cbax, _ = colorbar.make_axes(axes) cb = colorbar.ColorbarBase(cbax, cmap=cmap, norm = norm) cb.set_label('Temperature [K]') collection.set_array(np.array(Z))
def saveDamagePlot(self, folderPath, dataName, channelName, nLevels): import pylab as plt from matplotlib.colors import LogNorm import matplotlib.colorbar as colorbar import matplotlib.cm as cm maxDamage = self.damage.max() levels = np.logspace(np.log10(maxDamage / 100.), np.log10(maxDamage), nLevels ) norm = LogNorm(vmin = maxDamage / 100., vmax = maxDamage) cmap = cm.get_cmap('jet', nLevels) fig = plt.figure() axes = fig.add_subplot(111) axes.contourf(self.damage, extent = (0, 180, 0, 180), norm = norm, cmap = cmap, levels = levels) #axes.contourf(self.damage) cbax, _ = colorbar.make_axes(axes) cb = colorbar.ColorbarBase(cbax, cmap=cmap, norm = norm) cb.set_label('Damage [-]') axes.set_xlabel(r'$\theta$ [deg]') axes.set_ylabel(r'$\varphi$ [deg]') axes.set_title('Damage for {}, channel {}'.format(dataName, channelName)) fig.savefig(os.path.join(folderPath, '{}_{}.png'.format(dataName, channelName)))
def draw( self ): PlotBase.draw( self ) self.x_formatter_cb( self.ax ) if self.gdata.isEmpty(): return None tmp_x = []; tmp_y = [] # Evaluate the bar width width = float( self.width ) offset = 0. if self.gdata.key_type == 'time': width = width / 86400.0 start_plot = 0 end_plot = 0 if "starttime" in self.prefs and "endtime" in self.prefs: start_plot = date2num( datetime.datetime.fromtimestamp( to_timestamp( self.prefs['starttime'] ) ) ) end_plot = date2num( datetime.datetime.fromtimestamp( to_timestamp( self.prefs['endtime'] ) ) ) labels = self.gdata.getLabels() nKeys = self.gdata.getNumberOfKeys() tmp_b = [] tmp_x = [] tmp_y = [] self.bars = [] labels = self.gdata.getLabels() nLabel = 0 labelNames = [] colors = [] xmin = None xmax = None for label, num in labels: labelNames.append( label ) for key, value in self.gdata.getPlotNumData( label ): if xmin is None or xmin > ( key + offset ): xmin = key + offset if xmax is None or xmax < ( key + offset ): xmax = key + offset if value is not None: colors.append( self.getQualityColor( value ) ) tmp_x.append( key + offset ) tmp_y.append( 1. ) tmp_b.append( float( nLabel ) ) nLabel += 1 self.bars += self.ax.bar( tmp_x, tmp_y, bottom = tmp_b, width = width, color = colors ) dpi = self.prefs.get( 'dpi', 100 ) setp( self.bars, linewidth = pixelToPoint( 0.5, dpi ), edgecolor = '#AAAAAA' ) #pivots = keys #for idx in range(len(pivots)): # self.coords[ pivots[idx] ] = self.bars[idx] ymax = float( nLabel ) self.ax.set_xlim( xmin = 0., xmax = xmax + width + offset ) self.ax.set_ylim( ymin = 0., ymax = ymax ) if self.gdata.key_type == 'time': if start_plot and end_plot: self.ax.set_xlim( xmin = start_plot, xmax = end_plot ) else: self.ax.set_xlim( xmin = min( tmp_x ), xmax = max( tmp_x ) ) self.ax.set_yticks( [ i + 0.5 for i in range( nLabel ) ] ) self.ax.set_yticklabels( labelNames ) setp( self.ax.get_xticklines(), markersize = 0. ) setp( self.ax.get_yticklines(), markersize = 0. ) cax, kw = make_axes( self.ax, orientation = 'vertical', fraction = 0.07 ) cb = ColorbarBase( cax, cmap = cm.RdYlGn, norm = self.norms ) cb.draw_all()
def plot(self): """ plot residual phase tensor """ # get residual phase tensor for plotting self._compute_residual_pt() # filter data if desired if self.med_filt_kernel is not None: self._apply_median_filter(kernel=self.med_filt_kernel) # set position properties for the plot plt.rcParams["font.size"] = self.font_size plt.rcParams["figure.subplot.left"] = self.subplot_left plt.rcParams["figure.subplot.right"] = self.subplot_right plt.rcParams["figure.subplot.bottom"] = self.subplot_bottom plt.rcParams["figure.subplot.top"] = self.subplot_top plt.rcParams["figure.subplot.wspace"] = self.subplot_wspace plt.rcParams["figure.subplot.hspace"] = self.subplot_hspace # make figure instance self.fig = plt.figure(self.fig_num, self.fig_size, dpi=self.fig_dpi) self.ax = self.fig.add_subplot(1, 1, 1, aspect="equal") # create empty lists to put things into self.stationlist = [] self.offsetlist = [] minlist = [] maxlist = [] plot_periodlist = None # set local parameters with shorter names es = self.ellipse_size ck = self.ellipse_colorby cmap = self.ellipse_cmap ckmin = float(self.ellipse_range[0]) ckmax = float(self.ellipse_range[1]) try: ckstep = float(self.ellipse_range[2]) except IndexError: ckstep = 3 nseg = float((ckmax - ckmin) / (2 * ckstep)) if cmap == "mt_seg_bl2wh2rd": bounds = np.arange(ckmin, ckmax + ckstep, ckstep) # get largest ellipse emax = self._get_ellipse_size_max() # plot phase tensor ellipses for ii, rpt in enumerate(self.residual_pt_list): self.stationlist.append(rpt.station[self.station_id[0] : self.station_id[1]]) # set the an arbitrary origin to compare distance to all other # stations. if ii == 0: east0 = rpt.lon north0 = rpt.lat offset = 0.0 else: east = rpt.lon north = rpt.lat if self.linedir == "ew": if east0 < east: offset = np.sqrt((east0 - east) ** 2 + (north0 - north) ** 2) elif east0 > east: offset = -1 * np.sqrt((east0 - east) ** 2 + (north0 - north) ** 2) else: offset = 0 elif self.linedir == "ns": if north0 < north: offset = np.sqrt((east0 - east) ** 2 + (north0 - north) ** 2) elif north0 > north: offset = -1 * np.sqrt((east0 - east) ** 2 + (north0 - north) ** 2) else: offset = 0 self.offsetlist.append(offset) periodlist = 1.0 / rpt.freq[::-1] phimax = rpt.residual_pt.phimax[0][::-1] phimin = rpt.residual_pt.phimin[0][::-1] azimuth = rpt.residual_pt.azimuth[0][::-1] # get the properties to color the ellipses by if self.ellipse_colorby == "phimin": colorarray = rpt.residual_pt.phimin[0][::-1] elif self.ellipse_colorby == "phimax": colorarray = rpt.residual_pt.phimin[0][::-1] elif self.ellipse_colorby == "phidet": colorarray = np.sqrt(abs(rpt.residual_pt.det[::-1])) * (180 / np.pi) elif self.ellipse_colorby == "skew" or self.ellipse_colorby == "skew_seg": colorarray = rpt.residual_pt.beta[0][::-1] elif self.ellipse_colorby == "ellipticity": colorarray = rpt.residual_pt.ellipticity[::-1] else: raise NameError(self.ellipse_colorby + " is not supported") # get the number of periods n = len(periodlist) if ii == 0: plot_periodlist = periodlist else: if n > len(plot_periodlist): plot_periodlist = periodlist # get min and max of the color array for scaling later minlist.append(min(colorarray)) maxlist.append(max(colorarray)) for jj, ff in enumerate(periodlist): # make sure the ellipses will be visable eheight = phimin[jj] / emax * es ewidth = phimax[jj] / emax * es # create an ellipse scaled by phimin and phimax and orient # the ellipse so that north is up and east is right # need to add 90 to do so instead of subtracting ellipd = patches.Ellipse( (offset * self.xstretch, np.log10(ff) * self.ystretch), width=ewidth, height=eheight, angle=azimuth[jj] - 90, ) # get ellipse color if cmap.find("seg") > 0: ellipd.set_facecolor( mtcl.get_plot_color(colorarray[jj], self.ellipse_colorby, cmap, ckmin, ckmax, bounds=bounds) ) else: ellipd.set_facecolor(mtcl.get_plot_color(colorarray[jj], self.ellipse_colorby, cmap, ckmin, ckmax)) # == =add the ellipse to the plot == ======== self.ax.add_artist(ellipd) # --> Set plot parameters self._plot_periodlist = plot_periodlist n = len(plot_periodlist) # calculate minimum period and maximum period with a stretch factor pmin = np.log10(plot_periodlist.min()) * self.ystretch pmax = np.log10(plot_periodlist.max()) * self.ystretch # need to sort the offsets and station labels so they plot correctly sdtype = [("offset", np.float), ("station", "|S10")] slist = np.array([(oo, ss) for oo, ss in zip(self.offsetlist, self.stationlist)], dtype=sdtype) offset_sort = np.sort(slist, order="offset") self.offsetlist = offset_sort["offset"] self.stationlist = offset_sort["station"] # set y-ticklabels if self.tscale == "period": yticklabels = [ "{0:>4}".format("{0: .1e}".format(plot_periodlist[ll])) for ll in np.arange(0, n, self.ystep) ] + ["{0:>4}".format("{0: .1e}".format(plot_periodlist[-1]))] self.ax.set_ylabel("Period (s)", fontsize=self.font_size + 2, fontweight="bold") elif self.tscale == "frequency": yticklabels = [ "{0:>4}".format("{0: .1e}".format(1.0 / plot_periodlist[ll])) for ll in np.arange(0, n, self.ystep) ] + ["{0:>4}".format("{0: .1e}".format(1.0 / plot_periodlist[-1]))] self.ax.set_ylabel("Frequency (Hz)", fontsize=self.font_size + 2, fontweight="bold") # set x-axis label self.ax.set_xlabel("Station", fontsize=self.font_size + 2, fontweight="bold") # --> set tick locations and labels # set y-axis major ticks self.ax.yaxis.set_ticks([np.log10(plot_periodlist[ll]) * self.ystretch for ll in np.arange(0, n, self.ystep)]) # set y-axis minor ticks self.ax.yaxis.set_ticks( [np.log10(plot_periodlist[ll]) * self.ystretch for ll in np.arange(0, n, 1)], minor=True ) # set y-axis tick labels self.ax.set_yticklabels(yticklabels) # set x-axis ticks self.ax.set_xticks(self.offsetlist * self.xstretch) # set x-axis tick labels as station names xticklabels = self.stationlist if self.xstep != 1: xticklabels = np.zeros(len(self.stationlist), dtype=self.stationlist.dtype) for xx in range(0, len(self.stationlist), self.xstep): xticklabels[xx] = self.stationlist[xx] self.ax.set_xticklabels(xticklabels) # --> set x-limits if self.xlimits == None: self.ax.set_xlim( self.offsetlist.min() * self.xstretch - es * 2, self.offsetlist.max() * self.xstretch + es * 2 ) else: self.ax.set_xlim(self.xlimits) # --> set y-limits if self.ylimits == None: self.ax.set_ylim(pmax + es * 2, pmin - es * 2) else: pmin = np.log10(self.ylimits[0]) * self.ystretch pmax = np.log10(self.ylimits[1]) * self.ystretch self.ax.set_ylim(pmax + es * 2, pmin - es * 2) # --> set title of the plot if self.plot_title == None: pass else: self.ax.set_title(self.plot_title, fontsize=self.font_size + 2) # put a grid on the plot self.ax.grid(alpha=0.25, which="both", color=(0.25, 0.25, 0.25)) # print out the min an max of the parameter plotted print "-" * 25 print ck + " min = {0:.2f}".format(min(minlist)) print ck + " max = {0:.2f}".format(max(maxlist)) print "-" * 25 # ==> make a colorbar with appropriate colors if self.cb_position == None: self.ax2, kw = mcb.make_axes(self.ax, orientation=self.cb_orientation, shrink=0.35) else: self.ax2 = self.fig.add_axes(self.cb_position) if cmap == "mt_seg_bl2wh2rd": # make a color list self.clist = [(cc, cc, 1) for cc in np.arange(0, 1 + 1.0 / (nseg), 1.0 / (nseg))] + [ (1, cc, cc) for cc in np.arange(1, -1.0 / (nseg), -1.0 / (nseg)) ] # make segmented colormap mt_seg_bl2wh2rd = colors.ListedColormap(self.clist) # make bounds so that the middle is white bounds = np.arange(ckmin - ckstep, ckmax + 2 * ckstep, ckstep) # normalize the colors norms = colors.BoundaryNorm(bounds, mt_seg_bl2wh2rd.N) # make the colorbar self.cb = mcb.ColorbarBase( self.ax2, cmap=mt_seg_bl2wh2rd, norm=norms, orientation=self.cb_orientation, ticks=bounds[1:-1] ) else: self.cb = mcb.ColorbarBase( self.ax2, cmap=mtcl.cmapdict[cmap], norm=colors.Normalize(vmin=ckmin, vmax=ckmax), orientation=self.cb_orientation, ) # label the color bar accordingly self.cb.set_label(mtpl.ckdict[ck], fontdict={"size": self.font_size, "weight": "bold"}) # place the label in the correct location if self.cb_orientation == "horizontal": self.cb.ax.xaxis.set_label_position("top") self.cb.ax.xaxis.set_label_coords(0.5, 1.3) elif self.cb_orientation == "vertical": self.cb.ax.yaxis.set_label_position("right") self.cb.ax.yaxis.set_label_coords(1.5, 0.5) self.cb.ax.yaxis.tick_left() self.cb.ax.tick_params(axis="y", direction="in") plt.show()
def make_frame_image(basename, pixels, outputpath, pixel_mask = {}): """ Create the frame image. """ # The frame limits. x_min = 0; x_max = 256; y_min = 0; y_max = 256 ## The frame width. w = 256 ## The frame height. h = 256 # Remove the masked pixels. for X in pixel_mask.keys(): if X in pixels.keys(): del pixels[X] ## The maximum count value. C_max = max(pixels.values()) # Create the figure. plt.close('all') ## The size of the figure. figsize = 5.0 ## The figure for the frame. frfig = plt.figure(1, figsize=(figsize*1.27, figsize), dpi=150, facecolor='w', edgecolor='w') ## The frame axes. frfigax = frfig.add_subplot(111, axisbg='#222222') # Add the frame background (blue). frfigax.add_patch(plt.Rectangle((0,0),256,256,facecolor='#82bcff')) # Add a grid. plt.grid(1) # Select the "hot" colour map for the pixel counts. ## The colour map. cmap = plt.cm.hot ## The colour bar axis. colax, _ = colorbar.make_axes(plt.gca()) ## The maximum value on the colour axis. col_max = 10*(np.floor(C_max/10.)+1) # colorbar.ColorbarBase(colax,cmap=cmap,norm=colors.Normalize(vmin=0,vmax=col_max)) # Loop over the pixels and plot them. for X, C in pixels.iteritems(): x = X % 256; y = X / 256 scaled_C = float(C)/float(col_max) frfigax.add_patch(plt.Rectangle((x,y),1,1,edgecolor=cmap(scaled_C),facecolor=cmap(scaled_C))) # Loop over the masked pixels and plot them. for X, C in pixel_mask.iteritems(): x = X % 256; y = X / 256 frfigax.add_patch(plt.Rectangle((x,y),1,1,edgecolor='#00CC44',facecolor='#00CC44')) # Set the axis limits based. b = 3 # border # Set the axis limits. frfigax.set_xlim([0 - b, 256 + b]) frfigax.set_ylim([0 - b, 256 + b]) frfigax.set_aspect('equal') # Show the figure. frfig.show() raw_input() # Save the figure. frfig.savefig(outputpath + "/%s.png" % (basename))
def plot(self): """ plot residual phase tensor """ #get residual phase tensor for plotting self._compute_residual_pt() #filter data if desired if self.med_filt_kernel is not None: self._apply_median_filter(kernel=self.med_filt_kernel) #set position properties for the plot plt.rcParams['font.size']=self.font_size plt.rcParams['figure.subplot.left'] = self.subplot_left plt.rcParams['figure.subplot.right'] = self.subplot_right plt.rcParams['figure.subplot.bottom'] = self.subplot_bottom plt.rcParams['figure.subplot.top'] = self.subplot_top plt.rcParams['figure.subplot.wspace'] = self.subplot_wspace plt.rcParams['figure.subplot.hspace'] = self.subplot_hspace #make figure instance if self.tscale == 'period': titlefreq = '{0:.5g} (s)'.format(1./self.plot_freq) else: titlefreq='{0:.5g} (Hz)'.format(self.plot_freq) self.fig = plt.figure(titlefreq, self.fig_size, dpi=self.fig_dpi) #clear the figure if there is already one up plt.clf() #make an axes instance self.ax = self.fig.add_subplot(1, 1, 1, aspect='equal') #--> plot the background image if desired----------------------- try: im = plt.imread(self.image_file) self.ax.imshow(im, origin='lower', extent=self.image_extent, aspect='auto') except AttributeError: pass #get the reference point refpoint = self.plot_reference_point #set some local parameters es = float(self.ellipse_size) cmap = self.ellipse_cmap ckmin = float(self.ellipse_range[0]) ckmax = float(self.ellipse_range[1]) try: ckstep = float(self.ellipse_range[2]) except IndexError: if cmap == 'mt_seg_bl2wh2rd': raise ValueError('Need to input range as (min, max, step)') else: ckstep = 3 nseg = float((ckmax-ckmin)/(2*ckstep)) ck = self.ellipse_colorby #--> set the bounds on the segmented colormap if cmap == 'mt_seg_bl2wh2rd': bounds = np.arange(ckmin, ckmax+ckstep, ckstep) #set tick parameters depending on the mapscale if self.mapscale == 'latlon': self.tickstrfmt = '%.3f' elif self.mapscale == 'eastnorth' or self.mapscale == 'eastnorthkm': self.tickstrfmt = '%.0f' #make some empty arrays elliplist=[] latlist = np.zeros(len(self.residual_pt_list)) lonlist = np.zeros(len(self.residual_pt_list)) self.plot_xarr = np.zeros(len(self.residual_pt_list)) self.plot_yarr = np.zeros(len(self.residual_pt_list)) for ii, rpt in enumerate(self.residual_pt_list): #try to find the freq in the freq list of each file freqfind = [ff for ff, f2 in enumerate(rpt.freq) if f2 > self.plot_freq*(1-self.ftol) and f2 < self.plot_freq*(1+self.ftol)] try: self.jj = freqfind[0] jj = self.jj #--> get size of largest ellipse for this frequency for # normalization to give an indication of the size of # change. emax = self._get_ellipse_size_max(jj) #if map scale is lat lon set parameters if self.mapscale == 'latlon': latlist[ii] = rpt.lat lonlist[ii] = rpt.lon plotx = rpt.lon-refpoint[0] ploty = rpt.lat-refpoint[1] #if map scale is in meters easting and northing elif self.mapscale == 'eastnorth': zone, east, north = utm2ll.LLtoUTM(23, rpt.lat, rpt.lon) #set the first point read in as a refernce other points if ii == 0: zone1 = zone plotx = east-refpoint[0] ploty = north-refpoint[1] #read in all the other point else: #check to make sure the zone is the same this needs #to be more rigorously done if zone1!=zone: print 'Zone change at station '+rpt.station if zone1[0:2] == zone[0:2]: pass elif int(zone1[0:2])<int(zone[0:2]): east += 500000 else: east -= -500000 latlist[ii] = north-refpoint[1] lonlist[ii] = east-refpoint[0] plotx = east-refpoint[0] ploty = north-refpoint[1] else: latlist[ii] = north-refpoint[1] lonlist[ii] = east-refpoint[0] plotx = east-refpoint[0] ploty = north-refpoint[1] #if mapscale is in km easting and northing elif self.mapscale == 'eastnorthkm': zone,east,north = utm2ll.LLtoUTM(23, rpt.lat, rpt.lon) if ii == 0: zone1 = zone plotx = (east-refpoint[0])/1000. ploty = (north-refpoint[1])/1000. else: if zone1!=zone: print 'Zone change at station '+rpt.station if zone1[0:2] == zone[0:2]: pass elif int(zone1[0:2])<int(zone[0:2]): east += 500000 else: east -= 500000 latlist[ii] = (north-refpoint[1])/1000. lonlist[ii] = (east-refpoint[0])/1000. plotx = (east-refpoint[0])/1000. ploty = (north-refpoint[1])/1000. else: latlist[ii] = (north-refpoint[1])/1000. lonlist[ii] = (east-refpoint[0])/1000. plotx = (east-refpoint[0])/1000. ploty = (north-refpoint[1])/1000. else: raise NameError('mapscale not recognized') #put the location of each ellipse into an array in x and y self.plot_xarr[ii] = plotx self.plot_yarr[ii] = ploty #--> set local variables phimin = np.nan_to_num(rpt.residual_pt.phimin[0][jj]) phimax = np.nan_to_num(rpt.residual_pt.phimax[0][jj]) eangle = np.nan_to_num(rpt.residual_pt.azimuth[0][jj]) if cmap == 'mt_seg_bl2wh2rd': bounds = np.arange(ckmin, ckmax+ckstep, ckstep) nseg = float((ckmax-ckmin)/(2*ckstep)) #get the properties to color the ellipses by if self.ellipse_colorby == 'phiminang' or \ self.ellipse_colorby == 'phimin': colorarray = rpt.residual_pt.phimin[0][jj] elif self.ellipse_colorby == 'phidet': colorarray = np.sqrt(abs(rpt.det[0][jj]))*(180/np.pi) elif self.ellipse_colorby == 'skew' or\ self.ellipse_colorby == 'skew_seg': colorarray = rpt.residual_pt.beta[0][jj] elif self.ellipse_colorby == 'ellipticity': colorarray = rpt.residual_pt.ellipticity[0][jj] else: raise NameError(self.ellipse_colorby+' is not supported') #--> get ellipse properties #if the ellipse size is not physically correct make it a dot if phimax == 0 or phimax>100 or phimin == 0 or phimin>100: eheight=.0000001*es ewidth=.0000001*es print rpt.station else: scaling = es/emax eheight = phimin*scaling ewidth = phimax*scaling #make an ellipse ellipd=patches.Ellipse((plotx,ploty), width=ewidth, height=eheight, angle=90-eangle) #get ellipse color if cmap.find('seg')>0: ellipd.set_facecolor(mtcl.get_plot_color(colorarray, self.ellipse_colorby, cmap, ckmin, ckmax, bounds=bounds)) else: ellipd.set_facecolor(mtcl.get_plot_color(colorarray, self.ellipse_colorby, cmap, ckmin, ckmax)) #==> add ellipse to the plot elliplist.append(ellipd) self.ax.add_artist(ellipd) #------------Plot station name------------------------------ try: self.ax.text(plotx, ploty+self.station_pad, rpt.station[self.station_id[0]:self.station_id[1]], horizontalalignment='center', verticalalignment='baseline', fontdict=self.station_font_dict) except AttributeError: pass #==> print a message if couldn't find the freq except IndexError: print 'Did not find {0:.5g} Hz for station {1}'.format( self.plot_freq, rpt.station) #--> set axes properties depending on map scale------------------------ if self.mapscale == 'latlon': self.ax.set_xlabel('longitude', fontsize=self.font_size+2, fontweight='bold') self.ax.set_ylabel('latitude', fontsize=self.font_size+2, fontweight='bold') elif self.mapscale == 'eastnorth': self.ax.set_xlabel('Easting (m)', fontsize=self.font_size+2, fontweight='bold') self.ax.set_ylabel('Northing (m)', fontsize=self.font_size+2, fontweight='bold') elif self.mapscale == 'eastnorthkm': self.ax.set_xlabel('Easting (km)', fontsize=self.font_size+2, fontweight='bold') self.ax.set_ylabel('Northing (km)', fontsize=self.font_size+2, fontweight='bold') #--> set plot limits self.ax.set_xlim(self.plot_xarr.min()-self.xpad, self.plot_xarr.max()+self.xpad) self.ax.set_ylim(self.plot_yarr.min()-self.xpad, self.plot_yarr.max()+self.xpad) #--> set tick label format self.ax.xaxis.set_major_formatter(FormatStrFormatter(self.tickstrfmt)) self.ax.yaxis.set_major_formatter(FormatStrFormatter(self.tickstrfmt)) #--> set title in period or freq if self.tscale == 'period': titlefreq = '{0:.5g} (s)'.format(1./self.plot_freq) else: titlefreq='{0:.5g} (Hz)'.format(self.plot_freq) if not self.plot_title: self.ax.set_title('Phase Tensor Map for '+titlefreq, fontsize=self.font_size+2,fontweight='bold') else: self.ax.set_title(self.plot_title+titlefreq, fontsize=self.font_size+2,fontweight='bold') #make a grid with gray lines self.ax.grid(alpha=.25) #==> make a colorbar with appropriate colors if self.cb_position == None: self.ax2, kw = mcb.make_axes(self.ax, orientation=self.cb_orientation, shrink=.35) else: self.ax2 = self.fig.add_axes(self.cb_position) if cmap == 'mt_seg_bl2wh2rd': #make a color list self.clist = [(cc, cc ,1) for cc in np.arange(0, 1+1./(nseg), 1./(nseg))]+\ [(1, cc, cc) for cc in np.arange(1, -1./(nseg), -1./(nseg))] #make segmented colormap mt_seg_bl2wh2rd = colors.ListedColormap(self.clist) #make bounds so that the middle is white bounds = np.arange(ckmin-ckstep, ckmax+2*ckstep, ckstep) #normalize the colors norms = colors.BoundaryNorm(bounds, mt_seg_bl2wh2rd.N) #make the colorbar self.cb=mcb.ColorbarBase(self.ax2, cmap=mt_seg_bl2wh2rd, norm=norms, orientation=self.cb_orientation, ticks=bounds[1:-1]) else: self.cb=mcb.ColorbarBase(self.ax2, cmap=mtcl.cmapdict[cmap], norm=colors.Normalize(vmin=ckmin, vmax=ckmax), orientation=self.cb_orientation) #label the color bar accordingly self.cb.set_label(mtpl.ckdict[ck], fontdict={'size':self.font_size,'weight':'bold'}) #place the label in the correct location if self.cb_orientation == 'horizontal': self.cb.ax.xaxis.set_label_position('top') self.cb.ax.xaxis.set_label_coords(.5, 1.3) elif self.cb_orientation == 'vertical': self.cb.ax.yaxis.set_label_position('right') self.cb.ax.yaxis.set_label_coords(1.25, .5) self.cb.ax.yaxis.tick_left() self.cb.ax.tick_params(axis='y', direction='in') plt.show()
def plot(self): """ plot residual phase tensor """ # get residual phase tensor for plotting self._get_plot_freq_data() # filter data if desired if self.med_filt_kernel is not None: self._apply_median_filter() # set position properties for the plot plt.rcParams["font.size"] = self.font_size plt.rcParams["figure.subplot.left"] = self.subplot_left plt.rcParams["figure.subplot.right"] = self.subplot_right plt.rcParams["figure.subplot.bottom"] = self.subplot_bottom plt.rcParams["figure.subplot.top"] = self.subplot_top plt.rcParams["figure.subplot.wspace"] = self.subplot_wspace plt.rcParams["figure.subplot.hspace"] = self.subplot_hspace # make figure instance if self.tscale == "period": titlefreq = "{0:.5g} (s)".format(1.0 / self.plot_freq) else: titlefreq = "{0:.5g} (Hz)".format(self.plot_freq) self.fig = plt.figure(titlefreq, self.fig_size, dpi=self.fig_dpi) # clear the figure if there is already one up plt.clf() # make an axes instance self.ax = self.fig.add_subplot(1, 1, 1, aspect="equal") # --> plot the background image if desired----------------------- try: im = plt.imread(self.image_file) self.ax.imshow(im, origin="lower", extent=self.image_extent, aspect="auto") except AttributeError: pass # get the reference point refpoint = self.plot_reference_point # set some local parameters es = float(self.ellipse_size) cmap = self.ellipse_cmap ckmin = float(self.ellipse_range[0]) ckmax = float(self.ellipse_range[1]) try: ckstep = float(self.ellipse_range[2]) except IndexError: if cmap == "mt_seg_bl2wh2rd": raise ValueError("Need to input range as (min, max, step)") else: ckstep = 3 nseg = float((ckmax - ckmin) / (2 * ckstep)) ck = self.ellipse_colorby # --> set the bounds on the segmented colormap if cmap == "mt_seg_bl2wh2rd": bounds = np.arange(ckmin, ckmax + ckstep, ckstep) nseg = float((ckmax - ckmin) / (2 * ckstep)) # set tick parameters depending on the map_scale if self.map_scale == "deg": self.tickstrfmt = "%.3f" elif self.map_scale == "m" or self.map_scale == "km": self.tickstrfmt = "%.0f" # make some empty arrays elliplist = [] self.plot_xarr = np.zeros(len(self.plot_data)) self.plot_yarr = np.zeros(len(self.plot_data)) # --> get size of largest ellipse for this frequency for # normalization to give an indication of the size of # change. emax = self.plot_data[self.ellipse_colorby].max() for ii, rpt in enumerate(self.plot_data): # if map scale is lat lon set parameters if self.map_scale == "deg": plotx = rpt["lon"] - refpoint[0] ploty = rpt["lat"] - refpoint[1] # if map scale is in meters easting and northing elif self.map_scale == "m": zone, east, north = utm2ll.LLtoUTM(23, rpt["lat"], rpt["lon"]) # set the first point read in as a refernce other points if ii == 0: zone1 = zone plotx = east - refpoint[0] ploty = north - refpoint[1] # read in all the other point else: # check to make sure the zone is the same this needs # to be more rigorously done if zone1 != zone: print "Zone change at station {0}".format(rpt["station"]) if zone1[0:2] == zone[0:2]: pass elif int(zone1[0:2]) < int(zone[0:2]): east += 500000 else: east -= -500000 plotx = east - refpoint[0] ploty = north - refpoint[1] else: plotx = east - refpoint[0] ploty = north - refpoint[1] # if map_scale is in km easting and northing elif self.map_scale == "km": zone, east, north = utm2ll.LLtoUTM(23, rpt["lat"], rpt["lon"]) if ii == 0: zone1 = zone plotx = (east - refpoint[0]) / 1000.0 ploty = (north - refpoint[1]) / 1000.0 else: if zone1 != zone: print "Zone change at station {0}".format(rpt["station"]) if zone1[0:2] == zone[0:2]: pass elif int(zone1[0:2]) < int(zone[0:2]): east += 500000 else: east -= 500000 plotx = (east - refpoint[0]) / 1000.0 ploty = (north - refpoint[1]) / 1000.0 else: plotx = (east - refpoint[0]) / 1000.0 ploty = (north - refpoint[1]) / 1000.0 # put the location of each ellipse into an array in x and y self.plot_xarr[ii] = plotx self.plot_yarr[ii] = ploty # --> get ellipse properties # if the ellipse size is not physically correct make it a dot if rpt["phimax"] == 0 or rpt["phimax"] > 100 or rpt["phimin"] == 0 or rpt["phimin"] > 100: eheight = 0.0000001 * es ewidth = 0.0000001 * es print "Bad data at {0}".format(rpt["station"]) else: scaling = es / emax eheight = rpt["phimin"] * scaling ewidth = rpt["phimax"] * scaling # make an ellipse ellipd = patches.Ellipse((plotx, ploty), width=ewidth, height=eheight, angle=self.rot90 - rpt["azimuth"]) # get ellipse color if cmap.find("seg") > 0: ellipd.set_facecolor( mtcl.get_plot_color( rpt[self.ellipse_colorby], self.ellipse_colorby, cmap, ckmin, ckmax, bounds=bounds ) ) else: ellipd.set_facecolor( mtcl.get_plot_color(rpt[self.ellipse_colorby], self.ellipse_colorby, cmap, ckmin, ckmax) ) # ==> add ellipse to the plot elliplist.append(ellipd) self.ax.add_artist(ellipd) # ------------Plot station name------------------------------ try: self.ax.text( plotx, ploty + self.station_pad, rpt["station"][self.station_id[0] : self.station_id[1]], horizontalalignment="center", verticalalignment="baseline", fontdict=self.station_font_dict, ) except AttributeError: pass # --> set axes properties depending on map scale------------------------ if self.map_scale == "deg": self.ax.set_xlabel("Longitude", fontsize=self.font_size + 2, fontweight="bold") self.ax.set_ylabel("Latitude", fontsize=self.font_size + 2, fontweight="bold") elif self.map_scale == "m": self.ax.set_xlabel("Easting (m)", fontsize=self.font_size + 2, fontweight="bold") self.ax.set_ylabel("Northing (m)", fontsize=self.font_size + 2, fontweight="bold") elif self.map_scale == "km": self.ax.set_xlabel("Easting (km)", fontsize=self.font_size + 2, fontweight="bold") self.ax.set_ylabel("Northing (km)", fontsize=self.font_size + 2, fontweight="bold") # --> set plot limits self.ax.set_xlim(self.plot_xarr.min() - self.xpad, self.plot_xarr.max() + self.xpad) self.ax.set_ylim(self.plot_yarr.min() - self.xpad, self.plot_yarr.max() + self.xpad) # --> set tick label format self.ax.xaxis.set_major_formatter(FormatStrFormatter(self.tickstrfmt)) self.ax.yaxis.set_major_formatter(FormatStrFormatter(self.tickstrfmt)) # --> set title in period or freq if self.tscale == "period": titlefreq = "{0:.5g} (s)".format(1.0 / self.plot_freq) else: titlefreq = "{0:.5g} (Hz)".format(self.plot_freq) if not self.plot_title: self.ax.set_title( "Phase Tensor Map for {0}".format(titlefreq), fontsize=self.font_size + 2, fontweight="bold" ) else: self.ax.set_title(self.plot_title + titlefreq, fontsize=self.font_size + 2, fontweight="bold") # make a grid with gray lines self.ax.grid(alpha=0.25) # ==> make a colorbar with appropriate colors if self.cb_position == None: self.ax2, kw = mcb.make_axes(self.ax, orientation=self.cb_orientation, shrink=0.35) else: self.ax2 = self.fig.add_axes(self.cb_position) if cmap == "mt_seg_bl2wh2rd": # make a color list self.clist = [(cc, cc, 1) for cc in np.arange(0, 1 + 1.0 / (nseg), 1.0 / (nseg))] + [ (1, cc, cc) for cc in np.arange(1, -1.0 / (nseg), -1.0 / (nseg)) ] # make segmented colormap mt_seg_bl2wh2rd = colors.ListedColormap(self.clist) # make bounds so that the middle is white bounds = np.arange(ckmin - ckstep, ckmax + 2 * ckstep, ckstep) # normalize the colors norms = colors.BoundaryNorm(bounds, mt_seg_bl2wh2rd.N) # make the colorbar self.cb = mcb.ColorbarBase( self.ax2, cmap=mt_seg_bl2wh2rd, norm=norms, orientation=self.cb_orientation, ticks=bounds[1:-1] ) else: self.cb = mcb.ColorbarBase( self.ax2, cmap=mtcl.cmapdict[cmap], norm=colors.Normalize(vmin=ckmin, vmax=ckmax), orientation=self.cb_orientation, ) # label the color bar accordingly self.cb.set_label(mtpl.ckdict[ck], fontdict={"size": self.font_size, "weight": "bold"}) # place the label in the correct location if self.cb_orientation == "horizontal": self.cb.ax.xaxis.set_label_position("top") self.cb.ax.xaxis.set_label_coords(0.5, 1.3) elif self.cb_orientation == "vertical": self.cb.ax.yaxis.set_label_position("right") self.cb.ax.yaxis.set_label_coords(1.25, 0.5) self.cb.ax.yaxis.tick_left() self.cb.ax.tick_params(axis="y", direction="in") plt.show()
def _plot_unit(self, pinfo, ax): x = pinfo.pop('x') y = pinfo.pop('y') fill = pinfo.pop('fill') # TODO: Fix this hack! # Currently, if the fill is specified in the ggplot aes wrapper, ggplot # will assign colors without regard to the fill values. This is okay for # categorical maps but not heatmaps. At this stage in the pipeline the # geom can't recover the original values. # # However, if the fill is specified in the geom_tile aes wrapper, the # original fill values are sent unaltered, so we can make a heat map # with the values. # Was the fill specified in geom wrapper only? (i.e. not in ggplot) if 'fill' in self.aes_unique_to_geom: # Determine if there are non-numeric values. if False in [isinstance(v, (int, long, float, complex)) for v in set(fill)]: # No need to handle this case. Instruct the user to put categorical # values in the ggplot wrapper. raise Exception('For categorical fill values specify fill in the ggplot aes instead of the geom_tile aes.') # All values are numeric so determine fill using colormap. else: fill_min = np.min(fill) fill_max = np.max(fill) if np.isnan(fill_min): raise Exception('Fill values cannot contain NaN values.') fill_rng = float(fill_max - fill_min) fill_vals = (fill - fill_min) / fill_rng cmap = self.gg.colormap(fill_vals.tolist()) fill = [colors.rgb2hex(c) for c in cmap[::, :3]] df = pd.DataFrame( {'x': x, 'y': y, 'fill': fill}).set_index(['x', 'y']).unstack(0) # Setup axes. x_ticks = range(2*len(set(x)) + 1) y_ticks = range(2*len(set(y)) + 1) x_indices = sorted(set(x)) y_indices = sorted(set(y)) # Setup box plotting parameters. x_start = 0 y_start = 0 x_step = 2 y_step = 2 # Plot grid. on_y = y_start for yi in xrange(len(y_indices)): on_x = x_start for xi in xrange(len(x_indices)): color = df.iloc[yi,xi] if not isinstance(color, float): ax.add_patch(Rectangle((on_x, on_y), x_step, y_step, facecolor=color)) on_x += x_step on_y += y_step # Draw the colorbar scale if drawing a heat map. if 'cmap' in locals(): norm = colors.Normalize(vmin = fill_min, vmax = fill_max) cax, kw = colorbar.make_axes(ax) cax.hold(True) colorbar.ColorbarBase(cax, cmap = self.gg.colormap, norm = norm) # Set axis labels and ticks. x_labels = ['']*(len(x_indices)+1) for i,v in enumerate(x_indices): x_labels.insert(2*i+1, v) y_labels = ['']*(len(y_indices)+1) for i,v in enumerate(y_indices): y_labels.insert(2*i+1, v) ax.set_xticklabels(x_labels) ax.set_xticks(x_ticks) ax.set_yticklabels(y_labels) ax.set_yticks(y_ticks)
def plot_file(filename, outdir, dpi=50, debug=False, verbose=False): """ """ # Set figure parameters rcParams['font.size'] = 14 rcParams['font.weight'] = 'bold' rcParams['axes.titlesize'] = 14 rcParams['axes.titleweight'] = 'bold' rcParams['axes.labelsize'] = 14 rcParams['axes.labelweight'] = 'bold' rcParams['axes.linewidth'] = 1.5 rcParams['xtick.major.size'] = 4 rcParams['xtick.major.width'] = 1 rcParams['xtick.minor.size'] = 2 rcParams['xtick.minor.width'] = 1 rcParams['ytick.major.size'] = 4 rcParams['ytick.major.width'] = 1 rcParams['ytick.minor.size'] = 2 rcParams['ytick.minor.width'] = 1 if verbose: print 'Plotting file: {}'.format(os.path.basename(filename)) # Read gridded data grid = Dataset(filename, mode='r') # Initialize figure and axes subs = {'xlim': (-20, 20), 'ylim': (-20, 20)} figs = {'figsize': (73, 59)} fig, ax = plt.subplots( nrows=len(HEIGHTS), ncols=9, subplot_kw=subs, **figs) # Loop over all heights for k, height in enumerate(HEIGHTS): if verbose: print 'Plotting height index: {}'.format(height) # (a) Reflectivity qma = _plot_cappi( grid, REFL_FIELD, height=height, cmap=CMAP_REFL, norm=NORM_REFL, fig=fig, ax=ax[k,0]) # (b) Uncorrected Doppler velocity qmb = _plot_cappi( grid, VDOP_FIELD, height=height, cmap=CMAP_VDOP, norm=NORM_VDOP, fig=fig, ax=ax[k,1]) # (c) Corrected Doppler velocity qmc = _plot_cappi( grid, CORR_VDOP_FIELD, height=height, cmap=CMAP_VDOP, norm=NORM_VDOP, fig=fig, ax=ax[k,2]) # (d) Spectrum width qmd = _plot_cappi( grid, WIDTH_FIELD, height=height, cmap=CMAP_WIDTH, norm=NORM_WIDTH, fig=fig, ax=ax[k,3]) # (e) Copolar correlation ratio qme = _plot_cappi( grid, RHOHV_FIELD, height=height, cmap=CMAP_RHOHV, norm=NORM_RHOHV, fig=fig, ax=ax[k,4]) # (f) Differential reflectivity qmf = _plot_cappi( grid, ZDR_FIELD, height=height, cmap=CMAP_ZDR, norm=NORM_ZDR, fig=fig, ax=ax[k,5]) # (g) Differential phase qmg = _plot_cappi( grid, PHIDP_FIELD, height=height, cmap=CMAP_PHIDP, norm=NORM_PHIDP, fig=fig, ax=ax[k,6]) # Grid quality index qmh = _plot_cappi( grid, GQI_FIELD, height=height, cmap=CMAP_GQI, norm=NORM_GQI, fig=fig, ax=ax[k,7]) # (i) Nearest neighbour distance qmi = _plot_cappi( grid, DIST_FIELD, height=height, scale=1.0e-3, cmap=CMAP_DIST, norm=NORM_DIST, fig=fig, ax=ax[k,8]) # Create colour bars cax = [] for i in range(ax.shape[1]): cax.append( make_axes([axis for axis in ax[:,i].flat], location='bottom', pad=0.02, fraction=0.01, shrink=1.0, aspect=20)) fig.colorbar(mappable=qma, cax=cax[0][0], orientation='horizontal', ticks=TICKS_REFL) fig.colorbar(mappable=qmb, cax=cax[1][0], orientation='horizontal', ticks=TICKS_VDOP) fig.colorbar(mappable=qmc, cax=cax[2][0], orientation='horizontal', ticks=TICKS_VDOP) fig.colorbar(mappable=qmd, cax=cax[3][0], orientation='horizontal', ticks=TICKS_WIDTH) fig.colorbar(mappable=qme, cax=cax[4][0], orientation='horizontal', ticks=TICKS_RHOHV) fig.colorbar(mappable=qmf, cax=cax[5][0], orientation='horizontal', ticks=TICKS_ZDR) fig.colorbar(mappable=qmg, cax=cax[6][0], orientation='horizontal', ticks=TICKS_PHIDP) fig.colorbar(mappable=qmh, cax=cax[7][0], orientation='horizontal', ticks=TICKS_GQI) fig.colorbar(mappable=qmi, cax=cax[8][0], orientation='horizontal', ticks=TICKS_DIST) # Format axes for i, j in np.ndindex(ax.shape): ax[i,j].xaxis.set_major_locator(MultipleLocator(4)) ax[i,j].xaxis.set_minor_locator(MultipleLocator(1)) ax[i,j].yaxis.set_major_locator(MultipleLocator(4)) ax[i,j].yaxis.set_minor_locator(MultipleLocator(1)) ax[i,j].set_xlabel('Eastward Distance from Origin (km)') ax[i,j].set_ylabel('Northward Distance from Origin (km)') ax[i,j].grid(which='major') # Define image file name date = num2date(grid.variables['time'][:].min(), grid.variables['time'].units) fname = '{}.png'.format(date.strftime('%Y%m%d.%H%M%S')) # Save figure fig.savefig(os.path.join(outdir, fname), format='png', dpi=dpi, bbox_inches='tight') # Close figure to free memory plt.close(fig) return
def plot(self): """ plot residual phase tensor """ #get residual phase tensor for plotting self._compute_residual_pt() #filter data if desired if self.med_filt_kernel is not None: self._apply_median_filter(kernel=self.med_filt_kernel) #set position properties for the plot plt.rcParams['font.size']=self.font_size plt.rcParams['figure.subplot.left'] = self.subplot_left plt.rcParams['figure.subplot.right'] = self.subplot_right plt.rcParams['figure.subplot.bottom'] = self.subplot_bottom plt.rcParams['figure.subplot.top'] = self.subplot_top plt.rcParams['figure.subplot.wspace'] = self.subplot_wspace plt.rcParams['figure.subplot.hspace'] = self.subplot_hspace #make figure instance self.fig = plt.figure(self.fig_num, self.fig_size, dpi=self.fig_dpi) #create axis instance, be sure to make aspect equal or ellipses will #look funny. self.ax = self.fig.add_subplot(1, 1, 1, aspect='equal') #set local parameters with shorter names es = self.ellipse_size ck = self.ellipse_colorby cmap = self.ellipse_cmap ckmin = float(self.ellipse_range[0]) ckmax = float(self.ellipse_range[1]) try: ckstep = float(self.ellipse_range[2]) except IndexError: ckstep = 3 #set the number of segments in case a segmented map is desired nseg = float((ckmax-ckmin)/(2*ckstep)) if cmap == 'mt_seg_bl2wh2rd': bounds = np.arange(ckmin, ckmax+ckstep, ckstep) #get largest ellipse emax = self.ellipse_scale #emax = self.rpt_array['phimax'].max() #plot phase tensor ellipses for ii, rpt in enumerate(self.rpt_array): phimax = rpt['phimax'] phimin = rpt['phimin'] azimuth = rpt['azimuth'] #get the properties to color the ellipses by try: color_array = rpt[self.ellipse_colorby] except ValueError: raise NameError('{0} is not supported'.format( self.ellipse_colorby)) for jj, ff in enumerate(self.freq_list): if phimin[jj] == 0.0 or phimax[jj] == 0.0: pass else: #make sure the ellipses will be visable eheight = phimin[jj]/emax*es ewidth = phimax[jj]/emax*es #create an ellipse scaled by phimin and phimax and orient #the ellipse so that north is up and east is right #need to add 90 to do so instead of subtracting if self.rot90 == True: ellipd = patches.Ellipse((rpt['offset']*self.xstretch, np.log10(ff)*self.ystretch), width=ewidth, height=eheight, angle=azimuth[jj]-90) else: ellipd = patches.Ellipse((rpt['offset']*self.xstretch, np.log10(ff)*self.ystretch), width=ewidth, height=eheight, angle=azimuth[jj]) #get ellipse color if cmap.find('seg')>0: ellipd.set_facecolor(mtcl.get_plot_color(color_array[jj], self.ellipse_colorby, cmap, ckmin, ckmax, bounds=bounds)) else: ellipd.set_facecolor(mtcl.get_plot_color(color_array[jj], self.ellipse_colorby, cmap, ckmin, ckmax)) # == =add the ellipse to the plot == ======== self.ax.add_artist(ellipd) #--> Set plot parameters #need to sort the offsets and station labels so they plot correctly sdtype = [('offset', np.float), ('station','|S10')] slist = np.array([(oo, ss) for oo, ss in zip(self.rpt_array['offset'], self.rpt_array['station'])], dtype=sdtype) offset_sort = np.sort(slist, order='offset') self.offset_list = offset_sort['offset'] self.station_list = offset_sort['station'] #min and max frequency of the plot pmin = int(np.floor(np.log10(self.freq_list.min()))) pmax = int(np.ceil(np.log10(self.freq_list.max()))) #set y-axis major ticks to be on each power of 10 self.ax.yaxis.set_ticks(np.arange(pmin*self.ystretch, (pmax+1)*self.ystretch, self.ystretch)) #set y-ticklabels to coincide with the desired label if self.tscale == 'period': #make tick labels that will represent period yticklabels = [mtpl.labeldict[-ii] for ii in range(pmin, pmax+1, 1)] self.ax.set_ylabel('Period (s)', fontsize=self.font_size+2, fontweight='bold') elif self.tscale == 'frequency': yticklabels = [mtpl.labeldict[ii] for ii in range(pmin, pmax+1, 1)] self.ax.set_ylabel('Frequency (Hz)', fontsize=self.font_size+2, fontweight='bold') #--> set y-limits if self.ylimits == None: self.ax.set_ylim(pmin*self.ystretch, pmax*self.ystretch) else: pmin = np.log10(self.ylimits[0])*self.ystretch pmax = np.log10(self.ylimits[1])*self.ystretch self.ax.set_ylim(pmin, pmax) #--> set y-axis tick labels self.ax.set_yticklabels(yticklabels) #--> set x-axis label self.ax.set_xlabel('Station', fontsize=self.font_size+2, fontweight='bold') #set x-axis ticks self.ax.set_xticks(self.offset_list*self.xstretch) #set x-axis tick labels as station names xticklabels = self.station_list if self.xstep != 1: xticklabels = np.zeros(len(self.station_list), dtype=self.station_list.dtype) for xx in range(0,len(self.station_list),self.xstep): xticklabels[xx] = self.station_list[xx] self.ax.set_xticklabels(xticklabels) #--> set x-limits if self.xlimits == None: self.ax.set_xlim(self.offset_list.min()*self.xstretch-es*2, self.offset_list.max()*self.xstretch+es*2) else: self.ax.set_xlim(self.xlimits) #--> set title of the plot if self.plot_title == None: pass else: self.ax.set_title(self.plot_title, fontsize=self.font_size+2) #put a grid on the plot self.ax.grid(alpha=.25, which='both', color=(.25, .25, .25)) #==> make a colorbar with appropriate colors if self.cb_position == None: self.ax2, kw = mcb.make_axes(self.ax, orientation=self.cb_orientation, shrink=.35) else: self.ax2 = self.fig.add_axes(self.cb_position) if cmap == 'mt_seg_bl2wh2rd': #make a color list self.clist = [(cc, cc, 1) for cc in np.arange(0, 1+1./(nseg), 1./(nseg))]+\ [(1, cc, cc) for cc in np.arange(1, -1./(nseg), -1./(nseg))] #make segmented colormap mt_seg_bl2wh2rd = colors.ListedColormap(self.clist) #make bounds so that the middle is white bounds = np.arange(ckmin-ckstep, ckmax+2*ckstep, ckstep) #normalize the colors norms = colors.BoundaryNorm(bounds, mt_seg_bl2wh2rd.N) #make the colorbar self.cb = mcb.ColorbarBase(self.ax2, cmap=mt_seg_bl2wh2rd, norm=norms, orientation=self.cb_orientation, ticks=bounds[1:-1]) else: self.cb = mcb.ColorbarBase(self.ax2, cmap=mtcl.cmapdict[cmap], norm=colors.Normalize(vmin=ckmin, vmax=ckmax), orientation=self.cb_orientation) #label the color bar accordingly self.cb.set_label(mtpl.ckdict[ck], fontdict={'size':self.font_size,'weight':'bold'}) #place the label in the correct location if self.cb_orientation == 'horizontal': self.cb.ax.xaxis.set_label_position('top') self.cb.ax.xaxis.set_label_coords(.5, 1.3) elif self.cb_orientation == 'vertical': self.cb.ax.yaxis.set_label_position('right') self.cb.ax.yaxis.set_label_coords(1.5, .5) self.cb.ax.yaxis.tick_left() self.cb.ax.tick_params(axis='y', direction='in') #--> add reference ellipse ref_ellip = patches.Ellipse((0, .0), width=es, height=es, angle=0) ref_ellip.set_facecolor((0, 0, 0)) ref_ax_loc = list(self.ax2.get_position().bounds) ref_ax_loc[0] *= .95 ref_ax_loc[1] -= .17 ref_ax_loc[2] = .1 ref_ax_loc[3] = .1 self.ref_ax = self.fig.add_axes(ref_ax_loc, aspect='equal') self.ref_ax.add_artist(ref_ellip) self.ref_ax.set_xlim(-es/2.*1.05, es/2.*1.05) self.ref_ax.set_ylim(-es/2.*1.05, es/2.*1.05) plt.setp(self.ref_ax.xaxis.get_ticklabels(), visible=False) plt.setp(self.ref_ax.yaxis.get_ticklabels(), visible=False) self.ref_ax.set_title(r'$\Delta \Phi$ = 1') # put the grid lines behind # [line.set_zorder(10000) for line in self.ax.lines] self.ax.set_axisbelow(True) plt.show()
def make_frame_image(xs, ys, Cs): """ Create a figure displaying the frame data. """ ## The minimum x value. x_min = 0 ## The maximum x value. x_max = 256 ## The minimum y value. y_min = 0 ## The maximum y value. y_max = 256 ## The width of the frame. w = 256 ## The height of the frame. h = 256 ## The maximum count value. C_max = 1 # We add this just in case there are no pixels supplied. if len(Cs) > 0: C_max = max(Cs) # Create the figure. plt.close('all') ## The default size of the figure [inches]. fig_size = 5.0 ## The figure for the frame. fig = plt.figure(1, figsize=(fig_size*1.27, fig_size), dpi=150, facecolor='w', edgecolor='w') ## The frame axes. figax = fig.add_subplot(111, axisbg='#222222') # Add the frame background (blue). figax.add_patch(plt.Rectangle((0,0),256,256,facecolor='#82bcff')) # Add a grid. plt.grid(1) # Select the "hot" colour map for the pixel counts and add a # colour bar to indicate the count value for each pixel. # cmap = plt.cm.hot # colax, _ = colorbar.make_axes(plt.gca()) # col_max = 10*(np.floor(C_max/10.)+1) # colorbar.ColorbarBase(colax,cmap=cmap,norm=colors.Normalize(vmin=0,vmax=col_max)) # Loop over the pixels and add them to the figure. for i, x in enumerate(xs): ## The scaled count value (for the colour map). scaled_C = float(Cs[i])/float(col_max) # Rather than use, say, a 2D histogram for the pixels, we add # a coloured square to the plot for each pixel. figax.add_patch(plt.Rectangle((xs[i],ys[i]),1,1,edgecolor=cmap(scaled_C),facecolor=cmap(scaled_C))) ## The frame border width [pixels]. b = 3 # Set the axis limits based on the cluster radius. figax.set_xlim([0 - b, 256 + b]) figax.set_ylim([0 - b, 256 + b])
# get rid of all ticks on plots axH.xaxis.set_ticks([]) axH.yaxis.set_ticks([]) axJ.xaxis.set_ticks([]) axJ.yaxis.set_ticks([]) axK.xaxis.set_ticks([]) axK.yaxis.set_ticks([]) # create wavelength annotations axH.text(10, 35, r'1.63$\mu$m', fontsize=12, color='white',weight='bold') axJ.text(10, 35, r'1.25$\mu$m', fontsize=12, color='white',weight='bold') axK.text(10, 35, r'2.20$\mu$m', fontsize=12, color='white',weight='bold') # create & customize colorbars for each plot kwH={'orientation':'vertical','fraction':0.04,'anchor':(0,.5),'pad':0} axHbar, kwH = colorbar.make_axes(axH,**kwH) cbH = colorbar.Colorbar(axHbar, H) cbH.set_label('counts') cbH.set_ticks(linspace(0,300,4)) kwJ={'orientation':'vertical','fraction':0.04,'anchor':(0,0.5),'pad':0} axJbar, kwJ = colorbar.make_axes(axJ,**kwJ) cbJ = colorbar.Colorbar(axJbar, J) cbJ.set_label('counts') cbJ.set_ticks(linspace(0,507,4)) kwK={'orientation':'vertical','fraction':0.04,'anchor':(0,0.5),'pad':0} axKbar, kwK = colorbar.make_axes(axK,**kwK) cbK = colorbar.Colorbar(axKbar, K) cbK.set_label('counts') cbK.set_ticks(linspace(0,750,4))
riac.update(xys[i], mss[i]) fig1 = plt.figure() ax = fig1.add_subplot(111, aspect='equal') plt.xlim((riac.tree.bounds_x[0, 0], riac.tree.bounds_x[1, 0])) plt.ylim((riac.tree.bounds_x[0, 1], riac.tree.bounds_x[1, 1])) plt.xlabel('X') plt.ylabel('Y') plt.title('R-IAC tiling') riac.tree.plot(ax, True, True, True, riac.progress()) print "Max nb of children:", riac.tree.fold_up(lambda fl,fg:max(fl,fg), lambda leaf:leaf.children) print "Max leaf progress: ", riac.tree.progress import matplotlib.colorbar as cbar cax, _ = cbar.make_axes(ax) cb = cbar.ColorbarBase(cax, cmap=plt.cm.jet) cb.set_label('Normalized Competence Progress') plt.show(block=False) ###################################### ###### TEST PROGRESSING SAMPLING ##### ###################################### if True: print "\n###### TEST PROGRESSING SAMPLING #####" np.random.seed(1)
def plot_surf(surf_mesh, surf_map=None, bg_map=None, hemi='left', view='lateral', cmap=None, colorbar=False, avg_method='mean', threshold=None, alpha='auto', bg_on_data=False, darkness=1, vmin=None, vmax=None, cbar_vmin=None, cbar_vmax=None, title=None, output_file=None, axes=None, figure=None, **kwargs): """ Plotting of surfaces with optional background and data .. versionadded:: 0.3 Parameters ---------- surf_mesh: str or list of two numpy.ndarray Surface mesh geometry, can be a file (valid formats are .gii or Freesurfer specific files such as .orig, .pial, .sphere, .white, .inflated) or a list of two Numpy arrays, the first containing the x-y-z coordinates of the mesh vertices, the second containing the indices (into coords) of the mesh faces. surf_map: str or numpy.ndarray, optional. Data to be displayed on the surface mesh. Can be a file (valid formats are .gii, .mgz, .nii, .nii.gz, or Freesurfer specific files such as .thickness, .curv, .sulc, .annot, .label) or a Numpy array with a value for each vertex of the surf_mesh. bg_map: Surface data object (to be defined), optional, Background image to be plotted on the mesh underneath the surf_data in greyscale, most likely a sulcal depth map for realistic shading. hemi : {'left', 'right'}, default is 'left' Hemisphere to display. view: {'lateral', 'medial', 'dorsal', 'ventral', 'anterior', 'posterior'}, default is 'lateral' View of the surface that is rendered. cmap: matplotlib colormap, str or colormap object, default is None To use for plotting of the stat_map. Either a string which is a name of a matplotlib colormap, or a matplotlib colormap object. If None, matplotlib default will be chosen colorbar : bool, optional, default is False If True, a colorbar of surf_map is displayed. avg_method: {'mean', 'median'}, default is 'mean' How to average vertex values to derive the face value, mean results in smooth, median in sharp boundaries. threshold : a number or None, default is None. If None is given, the image is not thresholded. If a number is given, it is used to threshold the image, values below the threshold (in absolute value) are plotted as transparent. alpha: float, alpha level of the mesh (not surf_data), default 'auto' If 'auto' is chosen, alpha will default to .5 when no bg_map is passed and to 1 if a bg_map is passed. bg_on_data: bool, default is False If True, and a bg_map is specified, the surf_data data is multiplied by the background image, so that e.g. sulcal depth is visible beneath the surf_data. NOTE: that this non-uniformly changes the surf_data values according to e.g the sulcal depth. darkness: float, between 0 and 1, default is 1 Specifying the darkness of the background image. 1 indicates that the original values of the background are used. .5 indicates the background values are reduced by half before being applied. vmin, vmax: lower / upper bound to plot surf_data values If None , the values will be set to min/max of the data title : str, optional Figure title. output_file: str, or None, optional The name of an image file to export plot to. Valid extensions are .png, .pdf, .svg. If output_file is not None, the plot is saved to a file, and the display is closed. axes: instance of matplotlib axes, None, optional The axes instance to plot to. The projection must be '3d' (e.g., `figure, axes = plt.subplots(subplot_kw={'projection': '3d'})`, where axes should be passed.). If None, a new axes is created. figure: instance of matplotlib figure, None, optional The figure instance to plot to. If None, a new figure is created. See Also -------- nilearn.datasets.fetch_surf_fsaverage : For surface data object to be used as background map for this plotting function. nilearn.plotting.plot_surf_roi : For plotting statistical maps on brain surfaces. nilearn.plotting.plot_surf_stat_map : for plotting statistical maps on brain surfaces. """ # load mesh and derive axes limits mesh = load_surf_mesh(surf_mesh) coords, faces = mesh[0], mesh[1] limits = [coords.min(), coords.max()] # set view if hemi == 'right': if view == 'lateral': elev, azim = 0, 0 elif view == 'medial': elev, azim = 0, 180 elif view == 'dorsal': elev, azim = 90, 0 elif view == 'ventral': elev, azim = 270, 0 elif view == 'anterior': elev, azim = 0, 90 elif view == 'posterior': elev, azim = 0, 270 else: raise ValueError('view must be one of lateral, medial, ' 'dorsal, ventral, anterior, or posterior') elif hemi == 'left': if view == 'medial': elev, azim = 0, 0 elif view == 'lateral': elev, azim = 0, 180 elif view == 'dorsal': elev, azim = 90, 0 elif view == 'ventral': elev, azim = 270, 0 elif view == 'anterior': elev, azim = 0, 90 elif view == 'posterior': elev, azim = 0, 270 else: raise ValueError('view must be one of lateral, medial, ' 'dorsal, ventral, anterior, or posterior') else: raise ValueError('hemi must be one of right or left') # set alpha if in auto mode if alpha == 'auto': if bg_map is None: alpha = .5 else: alpha = 1 # if no cmap is given, set to matplotlib default if cmap is None: cmap = plt.cm.get_cmap(plt.rcParamsDefault['image.cmap']) else: # if cmap is given as string, translate to matplotlib cmap if isinstance(cmap, _basestring): cmap = plt.cm.get_cmap(cmap) # initiate figure and 3d axes if axes is None: if figure is None: figure = plt.figure() axes = Axes3D(figure, rect=[0, 0, 1, 1], xlim=limits, ylim=limits) else: if figure is None: figure = axes.get_figure() axes.set_xlim(*limits) axes.set_ylim(*limits) axes.set_aspect(.74) axes.view_init(elev=elev, azim=azim) axes.set_axis_off() # plot mesh without data p3dcollec = axes.plot_trisurf(coords[:, 0], coords[:, 1], coords[:, 2], triangles=faces, linewidth=0., antialiased=False, color='white') # reduce viewing distance to remove space around mesh axes.dist = 8 # set_facecolors function of Poly3DCollection is used as passing the # facecolors argument to plot_trisurf does not seem to work face_colors = np.ones((faces.shape[0], 4)) if bg_map is None: bg_data = np.ones(coords.shape[0]) * 0.5 else: bg_data = load_surf_data(bg_map) if bg_data.shape[0] != coords.shape[0]: raise ValueError('The bg_map does not have the same number ' 'of vertices as the mesh.') bg_faces = np.mean(bg_data[faces], axis=1) if bg_faces.min() != bg_faces.max(): bg_faces = bg_faces - bg_faces.min() bg_faces = bg_faces / bg_faces.max() # control background darkness bg_faces *= darkness face_colors = plt.cm.gray_r(bg_faces) # modify alpha values of background face_colors[:, 3] = alpha * face_colors[:, 3] # should it be possible to modify alpha of surf data as well? if surf_map is not None: surf_map_data = load_surf_data(surf_map) if len(surf_map_data.shape) is not 1: raise ValueError('surf_map can only have one dimension but has' '%i dimensions' % len(surf_map_data.shape)) if surf_map_data.shape[0] != coords.shape[0]: raise ValueError('The surf_map does not have the same number ' 'of vertices as the mesh.') # create face values from vertex values by selected avg methods if avg_method == 'mean': surf_map_faces = np.mean(surf_map_data[faces], axis=1) elif avg_method == 'median': surf_map_faces = np.median(surf_map_data[faces], axis=1) # if no vmin/vmax are passed figure them out from data if vmin is None: vmin = np.nanmin(surf_map_faces) if vmax is None: vmax = np.nanmax(surf_map_faces) # treshold if inidcated if threshold is None: kept_indices = np.arange(surf_map_faces.shape[0]) else: kept_indices = np.where(np.abs(surf_map_faces) >= threshold)[0] surf_map_faces = surf_map_faces - vmin surf_map_faces = surf_map_faces / (vmax - vmin) # multiply data with background if indicated if bg_on_data: face_colors[kept_indices] = cmap(surf_map_faces[kept_indices])\ * face_colors[kept_indices] else: face_colors[kept_indices] = cmap(surf_map_faces[kept_indices]) if colorbar: our_cmap = get_cmap(cmap) norm = Normalize(vmin=vmin, vmax=vmax) nb_ticks = 5 ticks = np.linspace(vmin, vmax, nb_ticks) bounds = np.linspace(vmin, vmax, our_cmap.N) if threshold is not None: cmaplist = [our_cmap(i) for i in range(our_cmap.N)] # set colors to grey for absolute values < threshold istart = int(norm(-threshold, clip=True) * (our_cmap.N - 1)) istop = int(norm(threshold, clip=True) * (our_cmap.N - 1)) for i in range(istart, istop): cmaplist[i] = (0.5, 0.5, 0.5, 1.) our_cmap = LinearSegmentedColormap.from_list( 'Custom cmap', cmaplist, our_cmap.N) # we need to create a proxy mappable proxy_mappable = ScalarMappable(cmap=our_cmap, norm=norm) proxy_mappable.set_array(surf_map_faces) cax, kw = make_axes(axes, location='right', fraction=.1, shrink=.6, pad=.0) cbar = figure.colorbar( proxy_mappable, cax=cax, ticks=ticks, boundaries=bounds, spacing='proportional', format='%.2g', orientation='vertical') _crop_colorbar(cbar, cbar_vmin, cbar_vmax) p3dcollec.set_facecolors(face_colors) if title is not None: axes.set_title(title, position=(.5, .95)) # save figure if output file is given if output_file is not None: figure.savefig(output_file) plt.close(figure) else: return figure
def _draw_colorbar(stat_map_img, axes, threshold=.1, nb_ticks=5, edge_color="0.5", edge_alpha=1, aspect=40, fraction=0.025, anchor=(10.0,0.5), cut_coords=None, positive_only=False, negative_only=False, cmap=None, ): if isinstance(stat_map_img, str): stat_map_img = path.abspath(path.expanduser(stat_map_img)) stat_map_img = nib.load(stat_map_img) stat_map_img_dat = _safe_get_data(stat_map_img, ensure_finite=True) if cmap: cmap = plt.cm.get_cmap(cmap) colors = cmap(np.linspace(0,1,256)) cmap_minus = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors[0:128,:]) cmap_plus = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors[128:255,:]) else: cmap_minus = MYMAP_MINUS cmap_plus = MYMAP_PLUS cmap = MYMAP cbar_vmin,cbar_vmax,vmin, vmax = _get_colorbar_and_data_ranges(stat_map_img_dat,None,"auto","") if cbar_vmin is not None or positive_only: vmin = 0 colmap = cmap_plus elif cbar_vmax is not None or negative_only: vmax = 0 colmap = cmap_minus else: colmap = cmap cbar_ax, p_ax = make_axes(axes, aspect=aspect, fraction=fraction, # pad=-0.5, anchor=anchor, # panchor=(-110.0, 0.5), ) ticks = np.linspace(vmin, vmax, nb_ticks) bounds = np.linspace(vmin, vmax, colmap.N) norm = mcolors.Normalize(vmin=vmin, vmax=vmax) # some colormap hacking cmaplist = [colmap(i) for i in range(colmap.N)] istart = int(norm(-threshold, clip=True) * (colmap.N - 1)) istop = int(norm(threshold, clip=True) * (colmap.N - 1)) for i in range(istart, (istop+1)): # just an average gray color cmaplist[i] = (0.5, 0.5, 0.5, 1.) our_cmap = colmap.from_list('Custom cmap', cmaplist, colmap.N) cbar = ColorbarBase( cbar_ax, ticks=ticks, norm=norm, orientation="vertical", cmap=our_cmap, boundaries=bounds, spacing="proportional", format="%.2g", ) cbar.outline.set_edgecolor(edge_color) cbar.outline.set_alpha(edge_alpha) cbar_ax.yaxis.tick_left() tick_color = 'k' for tick in cbar_ax.yaxis.get_ticklabels(): tick.set_color(tick_color) cbar_ax.yaxis.set_tick_params(width=0) return cbar_ax, p_ax,vmin,vmax,colmap
def plot_complex_function(f, re=(-2, 2), im=(-2, 2), n=600, title='', contours=True, numCtr=15, figsize=(5.5, 5.5), **kwargs): """plots complex functions in 2D using domain mapping technique Parameters ---------- f : function object the function re : tuple 2-tuple to indicate the bounds of real axis im : list 2-tuple to indicate the bounds of imaginary axis n : integer number of grid points is n**2 title : string title for the plot contours : bool if True (default), contours lines are drawn numCtr : integer number of contour lines figsize : tuple 2-tuple figure size as (width, height) in inches Returns ------- None Examples -------- >>> plot_complex_function(lambda z:np.sqrt(z), title='$f(z)=\sqrt{z}$') >>> plot_complex_function(lambda z:1/np.tan(z), re=[-3, 3], im=[-2, 2], title='$f(z)=ctan(z)$', figsize=(8,5)) >>> plot_complex_function(lambda z:np.log(z), title='$f(z)=log(z)$') Notes ----- 1. The phase/angle/argument is continuously mapped to hue such that the mathematically significant phase values, specifically the multiples of π/2 correponding to the real and imaginary axes, are mapped to more immediately recognizable colors as follows: | hue | phase (radians) | ------------------------------- | red | 0 mod 2π (+1) | | yellow | π/2 mod 2π (+i) | | cyan | π mod 2π (-1) | | blue | 3π/2 mod 2π (-i) | | orange | π/4 mod 2π | | green | 3π/4 mod 2π | | magenta | 7π/4 mod 2π | 2. |z| is mapped to show the direction of growth of the magnitude (from dark to bright within each ring), and the absolute value doubles for each ring. discontinuity in the intensity 3. The grids/contours helps to see whether the function is conformal or not (a conformal function preserves the angles between two smooth curves) 4. A discontinuity in hue represents a branch cut References ---------- 1. Visualizing complex-valued functions with Matplotlib and Mayavi, E. Petrisor, 2014 2. About color maps (NIST Digital Library of Mathematical Functions). http://dlmf.nist.gov/help/vrml/aboutcolor 3. Trigonometry Is a Complex Subject. Revisiting inverse, complex, hyperbolic, floating-point trig functions, Cleve Moler, 1998 4. Visualizing complex analytic functions using domain coloring, Hans Lundmark """ w = _eval_func(f, re, im, n) domc = _domain_map(w, satu=0.7) fig = _plt.figure(figsize=figsize) ax = fig.add_axes([0.15, 0.0, 0.85, 1.0]) ax.set_xlabel("Re(z)") ax.set_ylabel("Im(z)") tfs = 16 # title font size could be a **kwargs input later ax.set_title(title, fontsize=tfs, y=1.02) if contours: levelsX = _np.linspace(2.0*re[0], 2.0*re[1], 2.0*numCtr + 1) levelsY = _np.linspace(2.0*im[0], 2.0*im[1], 2.0*numCtr + 1) ax.contour(_np.real(w), levels=levelsX, origin="lower", extent=[re[0], re[1], im[0], im[1]], colors='k', lw=1.5, linestyles='solid') ax.contour(_np.imag(w), levels=levelsY, origin="lower", extent=[re[0], re[1], im[0], im[1]], colors='k', lw=1.5, linestyles='solid') ax.imshow(domc, origin="lower", extent=[re[0], re[1], im[0], im[1]], interpolation="hermite", zorder=20, alpha=0.9) norm = _mplc.Normalize(vmin=0, vmax=2.0*_np.pi) cbTickLocs = [0.0, _np.pi/2, _np.pi, 3*_np.pi/2, 2*_np.pi] cbTicLbls = ['$0$', '$\pi/2$', '$\pi$' , '$3\pi/2$', '$2\pi$'] cbax, kw = _mplcbar.make_axes(parents=ax, location='right', aspect=40, shrink=0.66, pad=0.08) cb = _mplcbar.ColorbarBase(ax=cbax, cmap=cplotHSVcm, norm=norm,) cb.set_alpha(0.9) cb.set_ticks(cbTickLocs) cb.set_ticklabels(cbTicLbls) _plt.show()
def makeKlusterImage(klusterid, kl, outputpath): """ Create the kluster image. """ # FIXME: Make configurable. pixels = kl.getPixelMap() x_min = kl.getXMin() x_max = kl.getXMax() y_min = kl.getYMin() y_max = kl.getYMax() w = kl.getWidth() h = kl.getHeight() ## The maximum count value. C_max = kl.getMaxCountValue() x_bar = kl.getXUW() y_bar = kl.getYUW() radius = kl.getRadiusUW() m, c, sumR = kl.getLineOfBestFitValues() # Create the figure. plt.close('all') figsize = 5.0 ## The figure for the cluster image. blobfig = plt.figure(1, figsize=(figsize*1.27, figsize), dpi=150, facecolor='w', edgecolor='w') # Set the beyond-frame background colour. blobfigax = blobfig.add_subplot(111, axisbg='#222222') # Add the frame background (blue). blobfigax.add_patch(plt.Rectangle((0,0),256,256,facecolor='#82bcff')) # Add a grid. plt.grid(1) # Select the "hot" colour map for the pixel counts. cmap = plt.cm.hot colax, _ = colorbar.make_axes(plt.gca()) col_max = 10*(np.floor(C_max/10.)+1) colorbar.ColorbarBase(colax,cmap=cmap,norm=colors.Normalize(vmin=0,vmax=col_max)) # Add the line of best fit. addLineOfBestFit(blobfigax, m, c) # Add the radius circle. addRadiusCircle(blobfigax, x_bar, y_bar, radius) # Loop over the pixels and plot them. for X, C in pixels.iteritems(): x = X % 256; y = X / 256 scaled_C = float(C)/float(col_max) blobfigax.add_patch(plt.Rectangle((x,y),1,1,facecolor=cmap(scaled_C))) # Set the axis limits based on the cluster radius. b = 3 # border xlim_min = x_bar - (np.floor(radius)+b) xlim_max = x_bar + (np.floor(radius)+b) ylim_min = y_bar - (np.floor(radius)+b) ylim_max = y_bar + (np.floor(radius)+b) blobfigax.set_xlim([xlim_min, xlim_max]) blobfigax.set_ylim([ylim_min, ylim_max]) # Set the axis tick mark spacing. blobfigax.xaxis.set_major_locator(MultipleLocator(10)) blobfigax.yaxis.set_major_locator(MultipleLocator(10)) # Save the figure. blobfig.savefig(outputpath + "/%s.png" % (klusterid))
def _corr2d4fig(spec, a1_label=r'$\bar{A}(\nu_1)$', a2_label=r'$\bar{A}(\nu_2)$', **contourkwds): """ Abstract layout for 2d correlation analysis plot. **contourkwds Passed directly to _gencontour; includes keywords like xlabel, ylabel and so forth. """ # Maybe this should take X, Y, Z not ts #fig, ax #how to handle these in general 2d # Maybe it's helpful to have args for top plots (ie ax1,2,3) title = contourkwds.pop('title', '') cbar = contourkwds.pop('cbar', False) grid = contourkwds.setdefault('grid', True) #Adds grid to plot and side plots # REFACTOR THIS cbar_nticks = 5 # This will create a fig ax1 = plt.subplot2grid((5,5), (0,0), colspan=1) # top left plt.subplots_adjust(hspace = 0, wspace=0) # Remove whitespace ax1.plot([0,-1], color='black') ax1.text(.18, -.78, a1_label, size=12) ax1.text(.55, -.35, a2_label, size=12) ax2 = plt.subplot2grid((5,5), (0,1), colspan=4) # top ax3 = plt.subplot2grid((5,5), (1,0), colspan=1, rowspan=4) #left ax4 = plt.subplot2grid((5,5), (1, 1), colspan=4, rowspan=4) #main contour ax3.invert_xaxis() ax4.yaxis.tick_right() ax4.xaxis.tick_bottom() #remove top xticks ax4.yaxis.set_label_position('right') ax4, contours = _gen2d3d(spec, ax=ax4, **contourkwds) # Bisecting line pvutil.diag_line(ax4) # Fig is created by _gen2d in ax4 _gen2d3d fig = plt.gcf() # Hide axis labels for ax in [ax2, ax3]: if grid: pvutil.hide_axis(ax, axis='both', axislabel=True, ticklabels=True) else: pvutil.hide_axis(ax, axis='both', hide_everything = True) pvutil.hide_axis(ax1, axis='both', hide_everything=True) #plt.colorbar() doesn't work # Handles its own colorbar (See links below; important) # http://stackoverflow.com/questions/13784201/matplotlib-2-subplots-1-colorbar # http://matplotlib.org/api/colorbar_api.html#matplotlib.colorbar.make_axes if cbar: if cbar in ['left', 'right', 'top', 'bottom']: # if bottom or right, should repad this location = cbar else: location = 'top' cax,kw = mplcbar.make_axes([ax1, ax2, ax3, ax4], location=location, pad = 0.05, aspect = 30, #make skinnier shrink=0.75) cb = fig.colorbar(contours, cax=cax,**kw)# ticks=[0,zz.max().max()], **kw) cb.locator = mplticker.MaxNLocator(nbins=cbar_nticks+1) #Cuts off one usually cb.set_label(spec.iunit) cb.update_ticks() #ax1 will take care of itself in contour if grid: if grid == True: ax2.grid() ax3.grid() else: ax2.grid(color=grid) ax3.grid(color=grid) fig.suptitle(title, fontsize='large') # Still overpads return (ax1, ax2, ax3, ax4)
def plot_matrix(mat, title=None, labels=None, figure=None, axes=None, colorbar=True, cmap=plt.cm.RdBu_r, tri='full', auto_fit=True, grid=False, **kwargs): """ Plot the given matrix. Parameters ---------- mat : 2-D numpy array Matrix to be plotted. title : string or None, optional A text to add in the upper left corner. labels : list of strings, optional The label of each row and column figure : figure instance, figsize tuple, or None Sets the figure used. This argument can be either an existing figure, or a pair (width, height) that gives the size of a newly-created figure. Specifying both axes and figure is not allowed. axes : None or Axes, optional Axes instance to be plotted on. Creates a new one if None. Specifying both axes and figure is not allowed. colorbar : boolean, optional If True, an integrated colorbar is added. cmap : matplotlib colormap, optional The colormap for the matrix. Default is RdBu_r. tri : {'lower', 'diag', 'full'}, optional Which triangular part of the matrix to plot: 'lower' is the lower part, 'diag' is the lower including diagonal, and 'full' is the full matrix. auto_fit : boolean, optional If auto_fit is True, the axes are dimensioned to give room for the labels. This assumes that the labels are resting against the bottom and left edges of the figure. grid : color or False, optional If not False, a grid is plotted to separate rows and columns using the given color. kwargs : extra keyword arguments Extra keyword arguments are sent to pylab.imshow Returns Matplotlib AxesImage instance """ if tri == 'lower': mask = np.tri(mat.shape[0], k=-1, dtype=np.bool) ^ True mat = np.ma.masked_array(mat, mask) elif tri == 'diag': mask = np.tri(mat.shape[0], dtype=np.bool) ^ True mat = np.ma.masked_array(mat, mask) if axes is not None and figure is not None: raise ValueError("Parameters figure and axes cannot be specified " "together. You gave 'figure=%s, axes=%s'" % (figure, axes)) if figure is not None: if isinstance(figure, plt.Figure): fig = figure else: fig = plt.figure(figsize=figure) axes = plt.gca() own_fig = True else: if axes is None: fig, axes = plt.subplots(1, 1, figsize=(7, 5)) own_fig = True else: fig = axes.figure own_fig = False display = axes.imshow(mat, aspect='equal', interpolation='nearest', cmap=cmap, **kwargs) axes.set_autoscale_on(False) ymin, ymax = axes.get_ylim() if labels is False: axes.xaxis.set_major_formatter(plt.NullFormatter()) axes.yaxis.set_major_formatter(plt.NullFormatter()) elif labels is not None: axes.set_xticks(np.arange(len(labels))) axes.set_xticklabels(labels, size='x-small') for label in axes.get_xticklabels(): label.set_ha('right') label.set_rotation(50) axes.set_yticks(np.arange(len(labels))) axes.set_yticklabels(labels, size='x-small') for label in axes.get_yticklabels(): label.set_ha('right') label.set_va('top') label.set_rotation(10) if grid is not False: size = len(mat) # Different grids for different layouts if tri == 'lower': for i in range(size): # Correct for weird mis-sizing i = 1.001 * i axes.plot([i + 0.5, i + 0.5], [size - 0.5, i + 0.5], color='grey') axes.plot([i + 0.5, -0.5], [i + 0.5, i + 0.5], color='grey') elif tri == 'diag': for i in range(size): # Correct for weird mis-sizing i = 1.001 * i axes.plot([i + 0.5, i + 0.5], [size - 0.5, i - 0.5], color='grey') axes.plot([i + 0.5, -0.5], [i - 0.5, i - 0.5], color='grey') else: for i in range(size): # Correct for weird mis-sizing i = 1.001 * i axes.plot([i + 0.5, i + 0.5], [size - 0.5, -0.5], color='grey') axes.plot([size - 0.5, -0.5], [i + 0.5, i + 0.5], color='grey') axes.set_ylim(ymin, ymax) if auto_fit: if labels is not None and labels is not False: fit_axes(axes) elif own_fig: plt.tight_layout(pad=.1, rect=((0, 0, .95, 1) if colorbar else (0, 0, 1, 1))) if colorbar: cax, kw = make_axes(axes, location='right', fraction=0.05, shrink=0.8, pad=.0) fig.colorbar(mappable=display, cax=cax) # make some room fig.subplots_adjust(right=0.8) # change current axis back to matrix plt.sca(axes) if title is not None: # Adjust the size text_len = np.max([len(t) for t in title.split('\n')]) size = axes.bbox.size[0] / text_len axes.text(0.95, 0.95, title, horizontalalignment='right', verticalalignment='top', transform=axes.transAxes, size=size) return display
sf_Mars = [ -1.1543080271930637, 1.1829009876408623, 0.053135194791245115, -0.55153781990867767, -0.49893099728963686, 0.0030938241872008818, ] Earth_traj = get_traj_from_ic(s0_Earth, t[0], t[-1], len(t), mu) x_Earth = [val[0][0] for val in Earth_traj] y_Earth = [val[0][1] for val in Earth_traj] Mars_traj = get_traj_from_ic(sf_Mars, t[-1], t[0], len(t), mu) x_Mars = [val[0][0] for val in Mars_traj] y_Mars = [val[0][1] for val in Mars_traj] axarr[0, 0].plot(x_Earth, y_Earth, color="blue") axarr[0, 0].plot(x_Mars, y_Mars, color="red") # add control quiver to orbit XY f2, axarr2 = plt.subplots(1, 1) axarr2.plot(x, y, color="black") axarr2.plot(x_Earth, y_Earth, color="blue") axarr2.plot(x_Mars, y_Mars, color="red") axarr2.set_title("Orbit XY") axarr2.grid() axarr2.set_aspect(1) uz_color = colors.Normalize(vmin=-1, vmax=1) axarr2.quiver(x, y, ux, uy, width=0.004, color=cm.jet(uz_color(uz))) cax, _ = colorbar.make_axes(plt.gca()) cb = colorbar.ColorbarBase(cax, cmap=cm.jet, norm=uz_color) cb.set_label("u$_z$", rotation=0)