我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用mpl_toolkits.axes_grid1.make_axes_locatable()。
def add_colorbar(ax, im, side='right', size='5%', pad=0.1, **kwds): """ Add colorbar to the axes *ax* with colors corresponding to the color mappable object *im*. Place the colorbar at the *side* of *ax* (options are `'right'`, `'left'`, `'top'`, or `'bottom'`). The width (or height) of the colorbar is specified by *size* and is relative to *ax*. Add space *pad* between *ax* and the colorbar. The remaining keyword arguments *kwds* are passed to the call to :func:`colorbar`. Return the colorbar instance. Reference: http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html """ divider = make_axes_locatable(ax) cax = divider.append_axes(side, size=size, pad=pad) cb = PL.colorbar(im, cax=cax, **kwds) PL.axes(ax) return cb
def updateGenomicPlotAxes(self, resize=False): if self.genomicPlotAxes is None: return if resize: self.divider = None if self.divider is None: self.divider = make_axes_locatable(self.ax) if resize: for obj in self.genomicPlotAxes: ax = self.divider.append_axes(obj.plotLocation, size=0.6, pad=self.verticalSpace, sharex=self.ax) obj.updatePlot(ax) else: ax = self.divider.append_axes(self.genomicPlotAxes[-1].plotLocation, size=0.6, pad=self.verticalSpace, sharex=self.ax) self.genomicPlotAxes[-1].updatePlot(ax) for obj in self.genomicPlotAxes: if self.lowerMostGenomicPlotAxes != obj.index: obj.axes_props.xLabel['Show Label'] = 'none' obj.axes_props.xTickLabel['Label Position'] = 'none' obj.axes_props.set_to_axes()
def _plot_topomap_multi_cbar(data, pos, ax, title=None, unit=None, vmin=None, vmax=None, cmap='RdBu_r', colorbar=False, cbar_fmt='%3.3f'): """Aux Function""" import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable _hide_frame(ax) vmin = np.min(data) if vmin is None else vmin vmax = np.max(data) if vmax is None else vmax if title is not None: ax.set_title(title, fontsize=10) im, _ = plot_topomap(data, pos, vmin=vmin, vmax=vmax, axes=ax, cmap=cmap, image_interp='bilinear', contours=False, show=False) if colorbar is True: divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="10%", pad=0.25) cbar = plt.colorbar(im, cax=cax, format=cbar_fmt) cbar.set_ticks((vmin, vmax)) if unit is not None: cbar.ax.set_title(unit, fontsize=8) cbar.ax.tick_params(labelsize=8)
def __init__(self, agent, num_options): self.agent = agent self.num_options = num_options fig, self.samples = plt.subplots(1, 1, figsize=(3, 3)) self.subplots = {} fig, subplots = plt.subplots(3, num_options+1, figsize=(22, 12)) self.subplots['reward'] = subplots[0] self.subplots['vf'] = subplots[1] self.subplots['policy'] = subplots[2] self.vf_divs = [] self.reward_divs = [] for i in range(num_options+1): self.vf_divs.append(make_axes_locatable(self.subplots['vf'][i]).append_axes("right", size="5%", pad=0.1)) self.reward_divs.append(make_axes_locatable(self.subplots['reward'][i]).append_axes("right", size="5%", pad=0.1)) self.make_grid_samples() self.set_titles() plt.ion() plt.show()
def ax_imshow(ax, P_h1h2, cmap, label, h1_hat, h2_hat, samplekey, r=4, draw_circle=True, ticks=True): im = ax.imshow(P_h1h2, cmap=cmap, origin="lower") from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=.05) cb = plt.colorbar(im, cax) cb.set_label(label) if not ticks: cb.set_ticks([]) if draw_circle: circle = plt.Circle((h1_hat, h2_hat), r, ec='w', fill=False) ax.add_artist(circle) annotation = "$\hat{h_1}=%d, \hat{h_2}=%d$" % (h1_hat, h2_hat) ax.text(200, 100, annotation, color=lsg, ha="center", va="center") ax.set_xlabel(r"$h_1$") ax.set_ylabel(r"$h_2$") title = "Joint probability density for $h_1$ and $h_2$ ({})"\ .format(samplekey) ax.set_title(title)
def _process_metric(self, ax, metric): if not metric.data.size: ax.tick_params(colors=(0, 0, 0, 0)) ax.set_axis_bgcolor(cm.get_cmap('viridis')(0)) divider = make_axes_locatable(ax) divider.append_axes('right', size='7%', pad=0.1).axis('off') return domain = self._domain(metric) categorical = self._is_categorical(metric.data) if metric.data.shape[1] == 1 and not categorical: self._plot_scalar(ax, domain, metric.data[:, 0]) elif metric.data.shape[1] == 1: indices = metric.data[:, 0].astype(int) min_, max_ = indices.min(), indices.max() count = np.eye(max_ - min_ + 1)[indices - min_] self._plot_distribution(ax, domain, count) elif metric.data.shape[1] > 1: self._plot_counts(ax, domain, metric.data)
def plot_shotrecord(rec, model, t0, tn, colorbar=True): """ Plot a shot record (receiver values over time). :param rec: Receiver data with shape (time, points) :param model: :class:`Model` object that holds the velocity model. :param t0: Start of time dimension to plot :param tn: End of time dimension to plot """ scale = np.max(rec) / 10. extent = [model.origin[0], model.origin[0] + 1e-3*model.domain_size[0], 1e-3*tn, t0] plot = plt.imshow(rec, vmin=-scale, vmax=scale, cmap=cm.gray, extent=extent) plt.xlabel('X position (km)') plt.ylabel('Time (s)') # Create aligned colorbar on the right if colorbar: ax = plt.gca() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(plot, cax=cax) plt.show()
def plot_image(data, vmin=None, vmax=None, colorbar=True, cmap="gray"): """ Plot image data, such as RTM images or FWI gradients. :param data: Image data to plot :param cmap: Choice of colormap, default is gray scale for images as a seismic convention """ plot = plt.imshow(np.transpose(data), vmin=vmin or 0.9 * np.min(data), vmax=vmax or 1.1 * np.max(data), cmap=cmap) # Create aligned colorbar on the right if colorbar: ax = plt.gca() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(plot, cax=cax) plt.show()
def __init_animation(self): masked_array = np.ma.array(self.frames[0], mask=np.isinf(self.frames[0])) vmin = 0 vmax = np.max(np.ma.array(self.frames[-1], mask=np.isinf(self.frames[-1]))) from mpl_toolkits.axes_grid1 import make_axes_locatable div = make_axes_locatable(self.ax2) cax = div.append_axes('right', '5%', '5%') cax.axis('off') div = make_axes_locatable(self.ax3) cax = div.append_axes('right', '5%', '5%') self.img = self.ax3.imshow(masked_array, interpolation='nearest', vmin=vmin, vmax=vmax, alpha=0.7) if self.matrix_labels: self.lables = self.__plot_matrix_labels(self.frames[0], self.ax3) else: self.lables = [] self.fig.colorbar(self.img, cax=cax) self.active_cells.append(self.ax3.add_patch( patches.Rectangle((0, 0), 1, 1, fill=False, linestyle='--', color='k', linewidth=3) )) self.active_cells.append(self.ax3.add_patch( patches.Rectangle((0, 0), 1, 1, fill=False, linestyle='--', color='k', linewidth=3) )) self.active_cells.append(self.ax3.add_patch( patches.Rectangle((0, 0), 1, 1, fill=False, linestyle='-', color='k', linewidth=3) )) return self.lables + [self.img]
def plot_mfcc_feature(vis_mfcc_feature): # plot the MFCC feature fig = plt.figure(figsize=(12,5)) ax = fig.add_subplot(111) im = ax.imshow(vis_mfcc_feature, cmap=plt.cm.jet, aspect='auto') plt.title('Normalized MFCC') plt.ylabel('Time') plt.xlabel('MFCC Coefficient') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax) ax.set_xticks(np.arange(0, 13, 2), minor=False); plt.show()
def plot_spectrogram_feature(vis_spectrogram_feature): # plot the normalized spectrogram fig = plt.figure(figsize=(12,5)) ax = fig.add_subplot(111) im = ax.imshow(vis_spectrogram_feature, cmap=plt.cm.jet, aspect='auto') plt.title('Normalized Spectrogram') plt.ylabel('Time') plt.xlabel('Frequency') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax) plt.show()
def extinction_figure(wave, a_lambda, residual_from, residual_lims=(-0.1, 0.4), title_text='$R_V = 3.1$'): names = list(a_lambda.keys()) # consistent ordering between panels fig = plt.figure(figsize=(8.5, 6.)) ax = plt.axes() for name in names: plt.plot(wave, a_lambda[name], label=name) plt.axvline(x=2700., ls=':', c='k') plt.axvline(x=3030.3030, ls=':', c='k') plt.axvline(x=9090.9091, ls=':', c='k') plt.axvspan(wave[0], 1150., fc='0.8', ec='none', zorder=-1000) plt.axvspan(1150., 1250., fc='0.9', ec='none', zorder=-1000) plt.text(0.65, 0.95, title_text, transform=ax.transAxes, va='top', ha='right', size='x-large') plt.ylabel('Extinction ($A(\lambda)$ / $A_V$)') plt.legend() plt.setp(ax.get_xticklabels(), visible=False) divider = make_axes_locatable(ax) axresid = divider.append_axes("bottom", size=2.0, pad=0.2, sharex=ax) for name in names: plt.plot(wave, a_lambda[name] - a_lambda[residual_from]) plt.axvline(x=2700., ls=':', c='k') plt.axvline(x=3030.3030, ls=':', c='k') plt.axvline(x=9090.9091, ls=':', c='k') plt.axvspan(wave[0], 1150., fc='0.8', ec='none', zorder=-1000) plt.axvspan(1150., 1250., fc='0.9', ec='none', zorder=-1000) plt.xlim(wave[0], wave[-1]) plt.ylim(ymin=residual_lims[0], ymax=residual_lims[1]) plt.ylabel('residual from ' + residual_from) plt.xlabel(r'Wavelength ($\mathrm{\AA}$)') ax.set_xscale('log') axresid.set_xscale('log') plt.tight_layout() return fig
def add_colorbar(img, ax=None): """ TODO: get keywords from **kwargs, i.e. if they're there, then use them, but if not, then don't. This should go for orientation, etc. Some others might have good defaults, so use them! TODO this function is barebones for now """ divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.15) cb=plt.colorbar(img, cax=cax, orientation="vertical") # cb.set_label('probability', labelpad=-10) # cb.set_ticks([0,1]) return cb
def add_cbar(im, ax): divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="10%", pad=0.05) plt.colorbar(im, cax=cax)
def add_colorbar(idx, cm, height, width, colorbar_bins=8, fontsize=None, img_width=1, scale=0.9): axis = plt.subplot(idx) plt.imshow(np.ones((height*scale, img_width)), alpha=0) # colorbar width must be given as a percentage of the img width, # both together should be equal to w/wscale width_factor = 100 * (width - img_width) / float(img_width) divider = make_axes_locatable(axis) cax = divider.append_axes("right", size=str(width_factor)+"%", pad=0.0) create_colorbar(cm, cax, colorbar_bins, fontsize)
def test_plain_axes(self): # supplied ax itself is a SubplotAxes, but figure contains also # a plain Axes object (GH11556) fig, ax = self.plt.subplots() fig.add_axes([0.2, 0.2, 0.2, 0.2]) Series(rand(10)).plot(ax=ax) # suppliad ax itself is a plain Axes, but because the cmap keyword # a new ax is created for the colorbar -> also multiples axes (GH11520) df = DataFrame({'a': randn(8), 'b': randn(8)}) fig = self.plt.figure() ax = fig.add_axes((0, 0, 1, 1)) df.plot(kind='scatter', ax=ax, x='a', y='b', c='a', cmap='hsv') # other examples fig, ax = self.plt.subplots() from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) Series(rand(10)).plot(ax=ax) Series(rand(10)).plot(ax=cax) fig, ax = self.plt.subplots() from mpl_toolkits.axes_grid.inset_locator import inset_axes iax = inset_axes(ax, width="30%", height=1., loc=3) Series(rand(10)).plot(ax=ax) Series(rand(10)).plot(ax=iax)
def plot_matrix(data, ax): im = ax.imshow( data.T, aspect='auto', origin='lower', interpolation='nearest') cax = make_axes_locatable(ax).append_axes("right", size="1%", pad=0.05) cb = pyplot.colorbar(im, cax=cax) tick_locator = ticker.MaxNLocator(nbins=5) cb.locator = tick_locator cb.ax.yaxis.set_major_locator(ticker.AutoLocator()) cb.update_ticks()
def browse_images(images, manual_update=False): from mpl_toolkits.axes_grid1 import make_axes_locatable from ipywidgets import interact n = len(images[list(images.keys())[0]]) def nice_imshow(data, title, ax): im = ax.imshow(data, interpolation="none", cmap="gray") ax.set_title(title, fontsize=18) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) plt.colorbar(im, cax=cax) def view_image(i): fig = plt.figure(figsize=(16, 8)) n_ax = len(images) for j, (label, data) in enumerate(images.items()): ax = plt.subplot(1, n_ax, j+1) if data[i].ndim == 3: nice_imshow(data[i, 0], label, ax) else: nice_imshow(data[i], label, ax) interact(view_image, i=(0, n - 1) , __manual=manual_update)
def drawMembersSpatial(self,data): ax = plt.gca() if isinstance(data,basestring): filename = data data = pyfits.open(filename)[1].data xmin, xmax = -0.25,0.25 ymin, ymax = -0.25,0.25 xx,yy = np.meshgrid(np.linspace(xmin,xmax),np.linspace(ymin,ymax)) x_prob, y_prob = sphere2image(self.ra, self.dec, data['RA'], data['DEC']) sel = (x_prob > xmin)&(x_prob < xmax) & (y_prob > ymin)&(y_prob < ymax) sel_prob = data['PROB'][sel] > 5.e-2 index_sort = numpy.argsort(data['PROB'][sel][sel_prob]) plt.scatter(x_prob[sel][~sel_prob], y_prob[sel][~sel_prob], marker='o', s=2, c='0.75', edgecolor='none') sc = plt.scatter(x_prob[sel][sel_prob][index_sort], y_prob[sel][sel_prob][index_sort], c=data['PROB'][sel][sel_prob][index_sort], marker='o', s=10, edgecolor='none', cmap='jet', vmin=0., vmax=1.) # Spectral_r drawProjImage(xx,yy,None,coord='C') #ax.set_xlim(xmax, xmin) #ax.set_ylim(ymin, ymax) #plt.xlabel(r'$\Delta \alpha_{2000}\,(\deg)$') #plt.ylabel(r'$\Delta \delta_{2000}\,(\deg)$') plt.xticks([-0.2, 0., 0.2]) plt.yticks([-0.2, 0., 0.2]) divider = make_axes_locatable(ax) ax_cb = divider.new_horizontal(size="7%", pad=0.1) plt.gcf().add_axes(ax_cb) pylab.colorbar(sc, cax=ax_cb, orientation='vertical', ticks=[0, 0.2, 0.4, 0.6, 0.8, 1.0], label='Membership Probability') ax_cb.yaxis.tick_right()
def nice_imshow(ax, data, vmin=None, vmax=None, cmap=None): """Wrapper around pl.imshow""" if cmap is None: cmap = cm.jet if vmin is None: vmin = data.min() if vmax is None: vmax = data.max() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest', cmap=cmap) pl.colorbar(im, cax=cax)
def nice_imshow(ax, data, vmin=None, vmax=None, cmap=None): from mpl_toolkits.axes_grid1 import make_axes_locatable """Wrapper around pl.imshow""" if cmap is None: cmap = cm.jet if vmin is None: vmin = data.min() if vmax is None: vmax = data.max() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest', cmap=cmap) pl.colorbar(im, cax=cax)
def add_color_bar(ax, img): divider = make_axes_locatable(ax) cax = divider.append_axes('right', size='7%', pad=0.1) bar = plt.colorbar(img, cax=cax) return bar
def plot_perturbation(model, model1, colorbar=True): """ Plot a two-dimensional velocity difference from two seismic :class:`Model` objects. :param model: :class:`Model` object of first velocity model. :param model1: :class:`Model` object of the second velocity model. :param source: Coordinates of the source point. :param receiver: Coordinates of the receiver points. """ domain_size = 1.e-3 * np.array(model.domain_size) extent = [model.origin[0], model.origin[0] + domain_size[0], model.origin[1] + domain_size[1], model.origin[1]] dv = np.transpose(model.vp) - np.transpose(model1.vp) plot = plt.imshow(dv, animated=True, cmap=cm.jet, vmin=min(dv.reshape(-1)), vmax=max(dv.reshape(-1)), extent=extent) plt.xlabel('X position (km)') plt.ylabel('Depth (km)') # Create aligned colorbar on the right if colorbar: ax = plt.gca() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(plot, cax=cax) cbar.set_label('Velocity perturbation (km/s)') plt.show()
def plot_velocity(model, source=None, receiver=None, colorbar=True): """ Plot a two-dimensional velocity field from a seismic :class:`Model` object. Optionally also includes point markers for sources and receivers. :param model: :class:`Model` object that holds the velocity model. :param source: Coordinates of the source point. :param receiver: Coordinates of the receiver points. """ domain_size = 1.e-3 * np.array(model.domain_size) extent = [model.origin[0], model.origin[0] + domain_size[0], model.origin[1] + domain_size[1], model.origin[1]] plot = plt.imshow(np.transpose(model.vp), animated=True, cmap=cm.jet, vmin=np.min(model.vp), vmax=np.max(model.vp), extent=extent) plt.xlabel('X position (km)') plt.ylabel('Depth (km)') # Plot source points, if provided if receiver is not None: plt.scatter(1e-3*receiver[:, 0], 1e-3*receiver[:, 1], s=25, c='green', marker='D') # Plot receiver points, if provided if source is not None: plt.scatter(1e-3*source[:, 0], 1e-3*source[:, 1], s=25, c='red', marker='o') # Ensure axis limits plt.xlim(model.origin[0], model.origin[0] + domain_size[0]) plt.ylim(model.origin[1] + domain_size[1], model.origin[1]) # Create aligned colorbar on the right if colorbar: ax = plt.gca() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(plot, cax=cax) cbar.set_label('Velocity (km/s)') plt.show()
def plot_line_power(obj, results, hour, ax=None): ''' obj: case or network ''' if ax is None: fig, ax = plt.subplots(1, 1, figsize=(16, 10)) ax.axis('off') case, network = _return_case_network(obj) network.draw_buses(ax=ax) network.draw_loads(ax=ax) network.draw_generators(ax=ax) network.draw_connections('gen_to_bus', ax=ax) network.draw_connections('load_to_bus', ax=ax) edgelist, edge_color, edge_width, edge_labels = _generate_edges(results, case, hour) branches = network.draw_branches(ax=ax, edgelist=edgelist, edge_color=edge_color, width=edge_width, edge_labels=edge_labels) divider = make_axes_locatable(ax) cax = divider.append_axes('right', size='5%', pad=0.05) cb = plt.colorbar(branches, cax=cax, orientation='vertical') cax.yaxis.set_label_position('left') cax.yaxis.set_ticks_position('left') cb.set_label('Loading Factor') return ax
def apply_to_graph(self, show_graph=True): """ Applies the given algorithm to given graph and displays it :param show_graph: Weather to show the graph in final result or not """ # Draw the original matrix if show_graph: if self.pos is None: self.pos = nx.nx_pydot.graphviz_layout(self.graph) nx.draw_networkx_nodes(self.graph, self.pos, ax=self.ax1, node_color='g', alpha=0.8, node_size=self.node_size).set_edgecolor('k') nx.draw_networkx_edges(self.graph, self.pos, ax=self.ax1, alpha=0.5) if self.weights: nx.draw_networkx_edge_labels(self.graph, self.pos, ax=self.ax1, edge_labels=nx.get_edge_attributes(self.graph, 'weight')) if self.lables: nx.draw_networkx_labels(self.graph, self.pos, ax=self.ax1) # Draw its adjacancy matrix result, adj = None, None for i, matrix in enumerate(self.fn(self.graph)): if i == 0: adj = matrix[0] result = matrix[0] # print(adj, result) cmap = plt.get_cmap('jet') cmap.set_bad('white', 1.) vmin = 0 vmax = np.max(result) from mpl_toolkits.axes_grid1 import make_axes_locatable div = make_axes_locatable(self.ax2) cax = div.append_axes('right', '5%', '5%') cax.axis('off') masked_array = np.ma.array(adj, mask=np.isinf(adj)) self.ax2.imshow(masked_array, interpolation='nearest', cmap=cmap, vmin=vmin, vmax=vmax) if self.matrix_labels: self.__plot_matrix_labels(adj, self.ax2) # Now draw the final matrix masked_array = np.ma.array(result, mask=np.isinf(result)) div = make_axes_locatable(self.ax3) cax = div.append_axes('right', '5%', '5%') if self.matrix_labels: self.__plot_matrix_labels(result, self.ax3) self.img = self.ax3.imshow(masked_array, interpolation='nearest', cmap=cmap, vmin=vmin, vmax=vmax) self.fig.colorbar(self.img, cax=cax) plt.show()
def _add_colorbar(self, axis, map_name, image_figure, colorbar_label, colorbar_position): """Add a colorbar to the axis Returns: axis: the image axis colorbar_position (str): one of 'left', 'right', 'top', 'bottom' """ divider = make_axes_locatable(axis) show_colorbar = self._get_map_attr(map_name, 'show_colorbar', self._plot_config.show_colorbars) show_colorbar_global = self._plot_config.show_colorbars if show_colorbar_global: axis_kwargs = dict(size="5%", pad=0.1) if self._plot_config.show_axis and colorbar_position in ['bottom', 'left']: axis_kwargs['pad'] = 0.3 if show_colorbar and colorbar_position in ('left', 'right'): colorbar_axis = divider.append_axes(colorbar_position, **axis_kwargs) else: fake_axis = divider.append_axes('right', **axis_kwargs) fake_axis.axis('off') if show_colorbar and colorbar_position in ('top', 'bottom'): colorbar_axis = divider.append_axes(colorbar_position, **axis_kwargs) else: fake_axis = divider.append_axes('bottom', **axis_kwargs) fake_axis.axis('off') if show_colorbar: kwargs = dict(cax=colorbar_axis, ticks=self._get_tick_locator(map_name)) if colorbar_label: kwargs.update(dict(label=colorbar_label)) if colorbar_position in ['top', 'bottom']: kwargs['orientation'] = 'horizontal' cbar = plt.colorbar(image_figure, **kwargs) cbar.formatter.set_powerlimits((-3, 4)) colorbar_axis.yaxis.set_offset_position('left') if colorbar_position == 'left': colorbar_axis.yaxis.set_ticks_position('left') colorbar_axis.yaxis.set_label_position('left') if colorbar_position == 'top': colorbar_axis.xaxis.set_ticks_position('top') colorbar_axis.xaxis.set_label_position('top') cbar.update_ticks() if cbar.ax.get_yticklabels(): cbar.ax.get_yticklabels()[-1].set_verticalalignment('top') self._apply_font_colorbar_axis(colorbar_axis)
def plot_all_chan_spectrum(spectrum, bins, *, ax=None, **kwargs): def integrate_to_angles(spectrum, bins, lo, hi): lo_ind, hi_ind = bins.searchsorted([lo, hi]) return spectrum[lo_ind:hi_ind].sum(axis=0) if ax is None: fig, ax = plt.subplots(figsize=(13.5, 9.5)) else: fig = ax.figure div = make_axes_locatable(ax) ax_r = div.append_axes('right', 2, pad=0.1, sharey=ax) ax_t = div.append_axes('top', 2, pad=0.1, sharex=ax) ax_r.yaxis.tick_right() ax_r.yaxis.set_label_position("right") ax_t.xaxis.tick_top() ax_t.xaxis.set_label_position("top") im = ax.imshow(spectrum, origin='lower', aspect='auto', extent=(-.5, 383.5, bins[0], bins[-1]), norm=LogNorm()) e_line, = ax_r.plot(spectrum.sum(axis=1), bins[:-1] + np.diff(bins)) p_line, = ax_t.plot(spectrum.sum(axis=0)) label = ax_t.annotate('[0, 70] kEv', (0, 1), (10, -10), xycoords='axes fraction', textcoords='offset pixels', va='top', ha='left') def update(lo, hi): p_data = integrate_to_angles(spectrum, bins, lo, hi) p_line.set_ydata(p_data) ax_t.relim() ax_t.autoscale(axis='y') label.set_text(f'[{lo:.1f}, {hi:.1f}] keV') fig.canvas.draw_idle() span = SpanSelector(ax_r, update, 'vertical', useblit=True, rectprops={'alpha': .5, 'facecolor': 'red'}, span_stays=True) ax.set_xlabel('channel [#]') ax.set_ylabel('E [keV]') ax_t.set_xlabel('channel [#]') ax_t.set_ylabel('total counts') ax_r.set_ylabel('E [keV]') ax_r.set_xlabel('total counts') ax.set_xlim(-.5, 383.5) ax.set_ylim(bins[0], bins[-1]) ax_r.set_xlim(xmin=0) return spectrum, bins, {'center': {'ax': ax, 'im': im}, 'top': {'ax': ax_t, 'p_line': p_line}, 'right': {'ax': ax_r, 'e_line': e_line, 'span': span}}
def nicecolorbar(self, axcb=None, reflevel=None, label=None, vmax=None, vmin=None, data=None, loc='head right', fontsize=8, ticks = None): if not axcb: axcb = matplotlib.pyplot.gca() divider = make_axes_locatable(axcb) # this code is from # http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#axes-grid1 cax = divider.append_axes("right", size="2%", pad=0.15) levels = numpy.asarray([0.001,0.0025,0.005,0.01,0.025,0.05,0.1,0.25,0.5,1,2.5,5,10,25,50,100,250,500,1000]) if vmax!= None and vmin != None: level = levels[numpy.nanargmin(abs((vmax - vmin)/5 - levels))] ticks = numpy.arange(vmin, vmax, level) elif vmax : level = levels[numpy.nanargmin(abs((vmax - numpy.nanmin(data))/5 - levels))] ticks = numpy.arange(numpy.nanmin(data), vmax, level) elif data is not None: level = None #levels[numpy.nanargmin(abs((numpy.nanmax(data) - numpy.nanmin(data))/5 - levels))] ticks = None #numpy.arange(numpy.nanmin(data), numpy.nanmax(data), level) #ticks -= numpy.nanmin(abs(ticks)) cb = matplotlib.pyplot.colorbar(self, cax=cax, label=label, orientation='vertical', extend='both', spacing='uniform', ticks=ticks) if vmax!= None and vmin != None: #print(ticks,vmin,vmax) cb.set_clim(vmin, vmax) cb.ax.yaxis.set_ticks_position('right') cb.ax.yaxis.set_label_position('right') cb.ax.set_yticklabels(cb.ax.get_yticklabels(), rotation='vertical',fontsize=fontsize) #if reflevel: # cb.ax.axhline((reflevel-min(cb.get_clim()))/numpy.diff(cb.get_clim()),zorder=999,color='k',linewidth=2) return cb
def colorbar(self,mappable=None,location='right',size="5%",pad='2%',fig=None,ax=None,**kwargs): """ Add colorbar to axes associated with a map. The colorbar axes instance is created using the axes_grid toolkit. .. tabularcolumns:: |l|L| ============== ==================================================== Keywords Description ============== ==================================================== mappable the Image, ContourSet, etc. to which the colorbar applies. Default None, matplotlib.pyplot.gci() is used to retrieve the current image mappable. location where to put colorbar ('top','bottom','left','right') Default 'right'. size width of colorbar axes (string 'N%', where N is an integer describing the fractional width of the parent axes). Default '5%'. pad Padding between parent axes and colorbar axes in same units as size. Default '2%'. fig Figure instance the map axes instance is associated with. Default None, and matplotlib.pyplot.gcf() is used to retrieve the current active figure instance. ax The axes instance which the colorbar will be associated with. Default None, searches for self.ax, and if None uses matplotlib.pyplot.gca(). \**kwargs extra keyword arguments passed on to colorbar method of the figure instance. ============== ==================================================== Returns a matplotlib colorbar instance. """ # get current axes instance (if none specified). ax = ax or self._check_ax() # get current figure instance (if none specified). if fig is None or mappable is None: import matplotlib.pyplot as plt if fig is None: fig = plt.gcf() # get current mappable if none specified. if mappable is None: mappable = plt.gci() # create colorbar axes uses axes_grid toolkit. divider = make_axes_locatable(ax) if location in ['left','right']: orientation = 'vertical' elif location in ['top','bottom']: orientation = 'horizontal' else: raise ValueError('location must be top,bottom,left or right') cax = divider.append_axes(location, size=size, pad=pad) # create colorbar. cb = fig.colorbar(mappable,orientation=orientation,cax=cax,**kwargs) fig.sca(ax) # reset parent axes as current axes. return cb
def plot_spikes(in_file, in_fft, spikes_list, cols=3, labelfmt='t={0:.3f}s (z={1:d})', out_file=None): from mpl_toolkits.axes_grid1 import make_axes_locatable nii = nb.as_closest_canonical(nb.load(in_file)) fft = nb.load(in_fft).get_data() data = nii.get_data() zooms = nii.header.get_zooms()[:2] tstep = nii.header.get_zooms()[-1] ntpoints = data.shape[-1] if len(spikes_list) > cols * 7: cols += 1 nspikes = len(spikes_list) rows = 1 if nspikes > cols: rows = math.ceil(nspikes / cols) fig = plt.figure(figsize=(7 * cols, 5 * rows)) for i, (t, z) in enumerate(spikes_list): prev = None pvft = None if t > 0: prev = data[..., z, t - 1] pvft = fft[..., z, t - 1] post = None psft = None if t < (ntpoints - 1): post = data[..., z, t + 1] psft = fft[..., z, t + 1] ax1 = fig.add_subplot(rows, cols, i + 1) divider = make_axes_locatable(ax1) ax2 = divider.new_vertical(size="100%", pad=0.1) fig.add_axes(ax2) plot_slice_tern(data[..., z, t], prev=prev, post=post, spacing=zooms, ax=ax2, label=labelfmt.format(t * tstep, z)) plot_slice_tern(fft[..., z, t], prev=pvft, post=psft, vmin=-5, vmax=5, cmap=get_parula(), ax=ax1) plt.tight_layout() if out_file is None: fname, ext = op.splitext(op.basename(in_file)) if ext == '.gz': fname, _ = op.splitext(fname) out_file = op.abspath('%s.svg' % fname) fig.savefig(out_file, format='svg', dpi=300, bbox_inches='tight') return out_file
def make_mutual_info_plot(fn): M.rcParams.update({'font.size': 11}) angleList = N.array([f/f.max() for f in read.extract_arr_from_h5(fn, "/history/angle", n=-1)]) mutualInfoList = read.extract_arr_from_h5(fn, "/history/mutual_info", n=-1) quatList = read.extract_arr_from_h5(fn, "/history/quaternion", n=-1) quatSwitchPos = N.where(quatList[:-1]-quatList[1:] != 0)[0] + 1 angsort = N.argsort(angleList[-1]) misort = N.argsort(mutualInfoList.mean(axis=0)) blkPositions = [0] + list(quatSwitchPos) + [-1] for bp in range(len(blkPositions)-1): (start, end) = (blkPositions[bp], blkPositions[bp+1]) curr_blk = angleList[start:end] curr_blk2 = mutualInfoList[start:end] / N.log(quatSize[quatList[0]]) # curr_blk2 = mutualInfoList[start:end] / N.log(quatSize[quatList[bp]]) if len(curr_blk) == 0: pass else: angsort = N.argsort(curr_blk[-1]) angleList[start:end] = curr_blk[:,angsort] for n,l in enumerate(curr_blk2): misort = N.argsort(l) mutualInfoList[start+n] = l[misort] P.ioff() fig, ax = P.subplots(2, 1, sharex=True, figsize=(7, 10)) fig.subplots_adjust(hspace=0.1) im0 = ax[0].imshow(angleList.transpose(), aspect='auto', interpolation=None, cmap=P.cm.OrRd) ax[0].set_xlabel("iteration") ax[0].set_ylabel("each pattern's most likely orientation\n(sorted by final orientation in each block)") (e_min, e_max) = (1, len(angleList[0])) e_int = 0.1*(e_max-e_min) ax[0].plot([0, 0], [e_min, e_max], 'k-') ax[0].text(1, e_max-e_int, "quat%d"%quatList[0], size=8, rotation=-0, ha='left', va='center', color='w', bbox=dict(boxstyle="larrow,pad=0.1",facecolor='0.1') ) for n,qs in enumerate(quatSwitchPos): ax[0].plot([qs, qs], [e_min, e_max], 'k-') ax[0].text(qs-1, e_max+(-n-1)*e_int, "quat%d"%quatList[qs], size=8, rotation=-0, ha='right', va='center', color='w', bbox=dict(boxstyle="rarrow,pad=0.1",facecolor='0.1') ) div0 = make_axes_locatable(ax[0]) cax0 = div0.append_axes("right", size="5%", pad=0.05) cbar0 = P.colorbar(im0, cax=cax0) ax[0].set_ylim(e_min, e_max) ax[0].set_xlim(0, len(angleList)-1) (e_min, e_max) = (1, len(mutualInfoList[0])) e_int = 0.1*(e_max-e_min) im1 = ax[1].imshow(mutualInfoList.transpose(), vmax=.2, aspect='auto', cmap=P.cm.YlGnBu) ax[1].set_xlabel("iteration") ax[1].set_ylabel("average mutual-information per dataset\n(sorted by average information)") ax[1].plot([0, 0], [e_min, e_max], 'k-') ax[1].text(1, e_max-e_int, "quat%d"%quatList[0], size=8, rotation=-0, ha='left', va='center', color='w', bbox=dict(boxstyle="larrow,pad=0.1",facecolor='0.1') ) for n,qs in enumerate(quatSwitchPos): ax[1].plot([qs, qs], [e_min, e_max], 'k-') ax[1].text(qs-1, e_max+(-n-1)*e_int, "quat%d"%quatList[qs], size=8, rotation=-0, ha='right', va='center', color='w', bbox=dict(boxstyle="rarrow,pad=0.1",facecolor='0.1') ) div1 = make_axes_locatable(ax[1]) cax1 = div1.append_axes("right", size="5%", pad=0.05) cbar1 = P.colorbar(im1, cax=cax1) ax[1].set_ylim(e_min, e_max) ax[1].set_xlim(0, len(mutualInfoList)-1) img_name = "mutual_info_plot.pdf" P.savefig(img_name, bbox_inches='tight') print("Image has been saved as %s" % img_name) P.close(fig)
def get_plot_axes(self, figure=None, ax_xy=None): import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable xmin, xmax, ymin, ymax, zmin, zmax = self.get_extent() if figure is None and ax_xy is None: figure = plt.figure() if figure is None and ax_xy is not None: figure = ax_xy.get_figure() if ax_xy is None: ax_xy = figure.add_subplot(111) ratio = float(xmax - xmin) / (ymax - ymin) plot_xz_size = ((zmax - zmin)/(xmax - xmin))*100 plot_yz_size = plot_xz_size / ratio plot_cbar_size = 5 # percent xz_size = '%f %%' % plot_xz_size yz_size = '%f %%' % plot_yz_size cb_size = '%f %%' % plot_cbar_size # ax_xy divider = make_axes_locatable(ax_xy) plt.setp(ax_xy.get_xticklabels(), visible=False) ax_xy.set_xlim(xmin, xmax) ax_xy.set_ylim(ymin, ymax) ax_xy.set_aspect('equal', 'datalim') plt.setp(ax_xy.get_yticklabels(), rotation=90, fontsize=12) # ax_yz ax_yz = divider.append_axes('right', size=yz_size, pad=0.05, sharey=ax_xy) plt.setp(ax_yz.get_yticklabels(), visible=False) ax_yz.set_xlim(zmin, zmax) ax_yz.set_ylim(ymin, ymax) plt.setp(ax_yz.get_xticklabels(), rotation=90, fontsize=12) plt.setp(ax_yz.get_yticklabels(), rotation=90, fontsize=12) # ax_xz ax_xz = divider.append_axes('bottom', size=xz_size, pad=0.05, sharex=ax_xy) ax_xz.set_xlim(xmin, xmax) ax_xz.set_ylim(zmax, zmin) # color-bar ax_cb = divider.append_axes('bottom', size=cb_size, pad=0.5) return ax_xy, ax_xz, ax_yz, ax_cb
def lblshow(label_img, labels_str=None, f=None, ax=None, cmap=None, *args, **kwargs): ''' display a labeled image with associated legend Parameters ---------- label_img : labeled image [nrows, ncols] = numpy.array.shape labels_str : a complete list of labels f : (optional) a figure handle cmap : the color of each label (optional). like a list of colors, e.g., ['Red','Green',...] or a matplotlib.colors.ListedColormap) ''' if labels_str is None: labels_str = [str(i) for i in np.unique(label_img)] if ax is None: if f is None: f,ax = plt.subplots(1,1) f.set_size_inches(9,6) else: ax = f.gca() elif f is None: f = ax.get_figure() nlabels = len(labels_str) if type(cmap) is mpl.colors.ListedColormap: pass elif hasattr(cmap, '__iter__'): if not kwargs.has_key('norm'): bounds = range(0,len(cmap)+1) kwargs['norm'] = mpl.colors.BoundaryNorm(bounds, len(cmap)) # HACKY cmap = mpl.colors.ListedColormap(cmap) elif cmap is None: colors = mpl.cm.spectral(np.linspace(0, 1, nlabels)) cmap = mpl.colors.ListedColormap(colors) else: assert False, 'invalid color map' im = ax.imshow(label_img, cmap=cmap, *args, **kwargs); ax.axis('off') # create an axes on the right side of ax. The width of cax will be 5% # of ax and the padding between cax and ax will be fixed at 0.05 inch. divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(im, cax=cax) cbar.ax.get_yaxis().set_ticks([]) for j, lab in enumerate(labels_str): cbar.ax.text(1.3, float(2 * j + 1) / (nlabels*2), lab, ha='left', va='center') return f
def plot_all_weights(model, n=64, n_columns=3, **kwargs): """ """ import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable # Set default matplotlib parameters if not 'interpolation' in kwargs.keys(): kwargs['interpolation'] = "none" if not 'cmap' in kwargs.keys(): kwargs['cmap'] = "gray" layers_to_show = [] for i, layer in enumerate(model.layers): if hasattr(layer, "W"): weights = layer.W.get_value() if weights.ndim == 4: layers_to_show.append((i, layer)) n_mosaic = len(layers_to_show) nrows = n_mosaic // n_columns ncols = n_columns if ncols ** 2 < n_mosaic: nrows +=1 fig_w = 15 fig_h = nrows * fig_w / ncols fig = plt.figure(figsize=(fig_w, fig_h)) for i, (layer_id, layer) in enumerate(layers_to_show): mosaic = get_weights_mosaic(model, layer_id=layer_id, n=n) ax = fig.add_subplot(nrows, ncols, i+1) im = ax.imshow(mosaic, **kwargs) ax.set_title("Layer #{} called '{}' \nof type {}".format(layer_id, layer.name, layer.__class__.__name__)) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) plt.colorbar(im, cax=cax) ax.axis('off') for sp in ax.spines.values(): sp.set_visible(False) if ax.is_first_row(): ax.spines['top'].set_visible(True) if ax.is_last_row(): ax.spines['bottom'].set_visible(True) if ax.is_first_col(): ax.spines['left'].set_visible(True) if ax.is_last_col(): ax.spines['right'].set_visible(True) #fig.tight_layout() return fig
def nodes_graph(self, colnum=0, show=False, printout=True): """Plot a 2D map with hexagonal nodes and weights values Args: colnum (int): The index of the weight that will be shown as colormap. show (bool, optional): Choose to display the plot. printout (bool, optional): Choose to save the plot to a file. """ centers = [[node.pos[0],node.pos[1]] for node in self.nodeList] widthP=100 dpi=72 xInch = self.netWidth*widthP/dpi yInch = self.netHeight*widthP/dpi fig=plt.figure(figsize=(xInch, yInch), dpi=dpi) if self.colorEx==True: cols = [[np.float(node.weights[0]),np.float(node.weights[1]),np.float(node.weights[2])]for node in self.nodeList] ax = hx.plot_hex(fig, centers, cols) ax.set_title('Node Grid w Color Features', size=80) printName='nodesColors.png' else: cols = [node.weights[colnum] for node in self.nodeList] ax = hx.plot_hex(fig, centers, cols) ax.set_title('Node Grid w Feature #' + str(colnum), size=80) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.0) cbar=plt.colorbar(ax.collections[0], cax=cax) cbar.set_label('Feature #' + str(colnum)+' value', size=80, labelpad=50) cbar.ax.tick_params(labelsize=60) plt.sca(ax) printName='nodesFeature_'+str(colnum)+'.png' if printout==True: plt.savefig(printName, bbox_inches='tight', dpi=dpi) if show==True: plt.show() if show!=False and printout!=False: plt.clf()
def diff_graph(self, show=False, printout=True): """Plot a 2D map with nodes and weights difference among neighbouring nodes. Args: show (bool, optional): Choose to display the plot. printout (bool, optional): Choose to save the plot to a file. """ neighbours=[] for node in self.nodeList: nodelist=[] for nodet in self.nodeList: if node != nodet and node.get_nodeDistance(nodet) <= 1.001: nodelist.append(nodet) neighbours.append(nodelist) diffs = [] for node, neighbours in zip(self.nodeList, neighbours): diff=0 for nb in neighbours: diff=diff+node.get_distance(nb.weights) diffs.append(diff) centers = [[node.pos[0],node.pos[1]] for node in self.nodeList] widthP=100 dpi=72 xInch = self.netWidth*widthP/dpi yInch = self.netHeight*widthP/dpi fig=plt.figure(figsize=(xInch, yInch), dpi=dpi) ax = hx.plot_hex(fig, centers, diffs) ax.set_title('Nodes Grid w Weights Difference', size=80) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.0) cbar=plt.colorbar(ax.collections[0], cax=cax) cbar.set_label('Weights Difference', size=80, labelpad=50) cbar.ax.tick_params(labelsize=60) plt.sca(ax) printName='nodesDifference.png' if printout==True: plt.savefig(printName, bbox_inches='tight', dpi=dpi) if show==True: plt.show() if show!=False and printout!=False: plt.clf()
def densityPlot(targ_ra, targ_dec, data, iso, g_radius, nbhd, type): """Stellar density plot""" mag_g = data[mag_g_dred_flag] mag_r = data[mag_r_dred_flag] if type == 'stars': filter = star_filter(data) plt.title('Stellar Density') elif type == 'galaxies': filter = galaxy_filter(data) plt.title('Galactic Density') elif type == 'blue_stars': filter = blue_star_filter(data) plt.title('Blue Stellar Density') iso_filter = (iso.separation(mag_g, mag_r) < 0.1) # projection of image proj = ugali.utils.projector.Projector(targ_ra, targ_dec) x, y = proj.sphereToImage(data[filter & iso_filter]['RA'], data[filter & iso_filter]['DEC']) # filter & iso_filter bound = 0.5 #1. steps = 100. bins = np.linspace(-bound, bound, steps) signal = np.histogram2d(x, y, bins=[bins, bins])[0] sigma = 0.01 * (0.25 * np.arctan(0.25*g_radius*60. - 1.5) + 1.3) # full range, arctan convolution = scipy.ndimage.filters.gaussian_filter(signal, sigma/(bound/steps)) plt.pcolormesh(bins, bins, convolution.T, cmap='Greys') plt.xlim(bound, -bound) plt.ylim(-bound, bound) plt.gca().set_aspect('equal') plt.xlabel(r'$\Delta \alpha$ (deg)') plt.ylabel(r'$\Delta \delta$ (deg)') ax = plt.gca() divider = make_axes_locatable(ax) cax = divider.append_axes('right', size = '5%', pad=0) plt.colorbar(cax=cax)
def hessPlot(targ_ra, targ_dec, data, iso, g_radius, nbhd): """Hess plot""" mag_g = data[mag_g_dred_flag] mag_r = data[mag_r_dred_flag] filter_s = star_filter(data) plt.title('Hess') c1 = SkyCoord(targ_ra, targ_dec, unit='deg') r_near = 2.*g_radius # annulus begins at 3*g_radius away from centroid r_far = np.sqrt(5.)*g_radius # annulus has same area as inner area inner = (c1.separation(SkyCoord(data['RA'], data['DEC'], unit='deg')).deg < g_radius) outer = (c1.separation(SkyCoord(data['RA'], data['DEC'], unit='deg')).deg > r_near) & (c1.separation(SkyCoord(data['RA'], data['DEC'], unit='deg')).deg < r_far) xbins = np.arange(-0.5, 1.1, 0.1) ybins = np.arange(16., 24.5, 0.5) foreground = np.histogram2d(mag_g[inner & filter_s] - mag_r[inner & filter_s], mag_g[inner & filter_s], bins=[xbins, ybins]) background = np.histogram2d(mag_g[outer & filter_s] - mag_r[outer & filter_s], mag_g[outer & filter_s], bins=[xbins, ybins]) fg = foreground[0].T bg = background[0].T fg_abs = np.absolute(fg) bg_abs = np.absolute(bg) mask_abs = fg_abs + bg_abs mask_abs[mask_abs == 0.] = np.nan # mask signficiant zeroes signal = fg - bg signal = np.ma.array(signal, mask=np.isnan(mask_abs)) # mask nan cmap = matplotlib.cm.viridis cmap.set_bad('w', 1.) plt.pcolormesh(xbins, ybins, signal, cmap=cmap) plt.colorbar() ugali.utils.plotting.drawIsochrone(iso, lw=2, c='k', zorder=10, label='Isocrhone') plt.axis([-0.5, 1.0, 16, 24]) plt.gca().invert_yaxis() plt.gca().set_aspect(1./4.) plt.xlabel('g-r (mag)') plt.ylabel('g (mag)') #ax = plt.gca() #divider = make_axes_locatable(ax) #cax = divider.append_axes('right', size = '5%', pad=0) #plt.colorbar(cax=cax)
def drawMembersCMD(self,data): ax = plt.gca() if isinstance(data,basestring): filename = data data = pyfits.open(filename)[1].data xmin, xmax = -0.25,0.25 ymin, ymax = -0.25,0.25 mmin, mmax = 16., 24. cmin, cmax = -0.5, 1.0 mbins = np.linspace(mmin, mmax, 150) cbins = np.linspace(cmin, cmax, 150) mag_1 = data[self.config['catalog']['mag_1_field']] mag_2 = data[self.config['catalog']['mag_2_field']] x_prob, y_prob = sphere2image(self.ra, self.dec, data['RA'], data['DEC']) sel = (x_prob > xmin)&(x_prob < xmax) & (y_prob > ymin)&(y_prob < ymax) sel_prob = data['PROB'][sel] > 5.e-2 index_sort = numpy.argsort(data['PROB'][sel][sel_prob]) plt.scatter(data['COLOR'][sel][~sel_prob], mag_1[sel][~sel_prob], marker='o',s=2,c='0.75',edgecolor='none') sc = pylab.scatter(data['COLOR'][sel][sel_prob][index_sort], mag_1[sel][sel_prob][index_sort], c=data['PROB'][sel][sel_prob][index_sort], marker='o', s=10, edgecolor='none', cmap='jet', vmin=0., vmax=1) pylab.xlim(cmin, cmax) pylab.ylim(mmax, mmin) pylab.xlabel(r'$g - r$') pylab.ylabel(r'$g$') #axes[1].yaxis.set_major_locator(MaxNLocator(prune='lower')) pylab.xticks([-0.5, 0., 0.5, 1.]) pylab.yticks(numpy.arange(mmax - 1., mmin - 1., -1.)) ugali.utils.plotting.drawIsochrone(self.isochrone, c='k', zorder=10) pylab.text(0.05, 0.95, r'$\Sigma p_{i} = %i$'%(data['PROB'].sum()), fontsize=10, horizontalalignment='left', verticalalignment='top', color='k', transform=pylab.gca().transAxes, bbox=dict(facecolor='white', alpha=1., edgecolor='none')) divider = make_axes_locatable(pylab.gca()) ax_cb = divider.new_horizontal(size="7%", pad=0.1) plt.gcf().add_axes(ax_cb) pylab.colorbar(sc, cax=ax_cb, orientation='vertical', ticks=[0, 0.2, 0.4, 0.6, 0.8, 1.0], label='Membership Probability') ax_cb.yaxis.tick_right()
def draw_slices(hist, func=np.sum, **kwargs): """ Draw horizontal and vertical slices through histogram """ from mpl_toolkits.axes_grid1 import make_axes_locatable kwargs.setdefault('ls','-') ax = plt.gca() data = hist # Slices vslice = func(data,axis=0) hslice = func(data,axis=1) npix = np.array(data.shape) #xlim,ylim = plt.array(zip([0,0],npix-1)) xlim = ax.get_xlim() ylim = ax.get_ylim() #extent = ax.get_extent() #xlim =extent[:2] #ylim = extent[2:] # Bin centers xbin = np.linspace(xlim[0],xlim[1],len(vslice))#+0.5 ybin = np.linspace(ylim[0],ylim[1],len(hslice))#+0.5 divider = make_axes_locatable(ax) #gh2 = pywcsgrid2.GridHelperSimple(wcs=self.header, axis_nums=[2, 1]) hax = divider.append_axes("right", size=1.2, pad=0.05,sharey=ax, axes_class=axes_divider.LocatableAxes) hax.axis["left"].toggle(label=False, ticklabels=False) #hax.plot(hslice, plt.arange(*ylim)+0.5,'-') # Bin center hax.plot(hslice, ybin, **kwargs) # Bin center hax.xaxis.set_major_locator(MaxNLocator(4,prune='both')) hax.set_ylim(*ylim) #gh1 = pywcsgrid2.GridHelperSimple(wcs=self.header, axis_nums=[0, 2]) vax = divider.append_axes("top", size=1.2, pad=0.05, sharex=ax, axes_class=axes_divider.LocatableAxes) vax.axis["bottom"].toggle(label=False, ticklabels=False) vax.plot(xbin, vslice, **kwargs) vax.yaxis.set_major_locator(MaxNLocator(4,prune='lower')) vax.set_xlim(*xlim) return vax,hax
def full_plot(data, pi, phi, pi_at, save_name=None): # Plot a single example. f, (ax1, ax2, ax3, ax4) = pyplot.subplots(4, 1) std_x = data_std * data + data_mean # std_x = data x = numpy.cumsum(std_x[:, 1]) y = numpy.cumsum(std_x[:, 2]) size_x = x.max() - x.min() + 1. size_y = y.max() - y.min() + 1. f.set_size_inches(5. * size_x / size_y, 20.) cuts = numpy.where(std_x[:, 0] == 1)[0] start = 0 for cut_value in cuts: ax1.plot( x[start:cut_value], y[start:cut_value], 'k-', linewidth=1.5) start = cut_value + 1 ax1.axis('equal') ax1.axes.get_xaxis().set_visible(False) ax1.axes.get_yaxis().set_visible(False) def plot_matrix(data, ax): im = ax.imshow( data.T, aspect='auto', origin='lower', interpolation='nearest') cax = make_axes_locatable(ax).append_axes("right", size="1%", pad=0.05) pyplot.colorbar(im, cax=cax) plot_matrix(phi, ax2) plot_matrix(pi_at, ax3) plot_matrix(pi, ax4) if save_name is None: pyplot.show() else: try: pyplot.savefig( save_name, bbox_inches='tight', pad_inches=0.5) except Exception: print "Error building image!: " + save_name pyplot.close()
def plot_jet_image( ax, image, vmin=1e-9, vmax=1e-2, cmap="jet", title="Intensity", label_axes=True, visible_axes=False, show_colorbar=True, colorbar_inside=False): """Display jet image. Args: ax: matplotlib axes to plot on. image: array representing image to plot. vmin, vmax: min, max intensity values to plot. """ width, height = image.T.shape dw, dh = 1./width, 1./height if not (vmin is None) and not (vmax is None): if vmin < 0: norm = MidPointNorm(vmin=vmin, vmax=vmax) ticks = None else: norm = LogNorm(vmin=vmin, vmax=vmax) ticks = np.logspace( np.log10(vmin), np.log10(vmax), 1 + np.log10(vmax) - np.log10(vmin)) else: norm = None ticks = None p = ax.imshow( image.T, extent=(-(1+dw), 1+dw, -(1+dh), 1+dh), origin='low', interpolation='nearest', norm=norm, cmap=cmap) if show_colorbar: if colorbar_inside: cax = ax.figure.add_axes([0.85, 0.08, 0.03, 0.82]) else: divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(p, cax=cax, ticks=ticks) cbar.set_label(title, rotation=90, fontsize=18) cbar.ax.tick_params(labelsize=12) if colorbar_inside: cbar.ax.yaxis.set_ticks_position('left') if label_axes: ax.set_xlabel(r'$x_1$', fontsize=18) ax.set_ylabel(r'$x_2$', fontsize=18) ax.tick_params(axis='both', which='major', labelsize=12) else: ax.axes.get_xaxis().set_ticks([]) ax.axes.get_yaxis().set_ticks([]) ax.axes.get_xaxis().set_visible(visible_axes) ax.axes.get_yaxis().set_visible(visible_axes) if visible_axes: for spine in ['top', 'bottom', 'left', 'right']: ax.spines[spine].set_linewidth(1) ax.spines[spine].set_color('k') else: for spine in ['top', 'bottom', 'left', 'right']: ax.spines[spine].set_visible(False) ax.axes.grid(False)
def plot_wiring_cs(wiring, den_borders, ax_borders, confidence_lvl, binary, wd, add_fname='_CS'): """Same as plot_wiring, but using all contact sites """ fig = plt.figure() ax = plt.gca() max_val = np.max(wiring) for k, b in enumerate(den_borders): b += k * 1 wiring = np.concatenate((wiring[:b, :], np.ones((1, wiring.shape[1], 1)), wiring[b:, :]), axis=0) for k, b in enumerate(ax_borders): b += k * 1 wiring = np.concatenate((wiring[:, :b], np.ones((wiring.shape[0], 1, 1)), wiring[:, b:]), axis=1) ax.matshow(np.max(wiring.transpose(1, 0, 2), axis=2), interpolation="none", extent=[0, wiring.shape[0], wiring.shape[1], 0], cmap='gray') ax.set_xlabel('Post', fontsize=18) ax.set_ylabel('Pre', fontsize=18) ax.set_xlim(0, wiring.shape[0]) ax.set_ylim(0, wiring.shape[1]) plt.grid(False) plt.axis('off') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) a = np.array([[0, 1]]) plt.figure() plt.imshow(a, cmap='gray') plt.gca().set_visible(False) cb = plt.colorbar(cax=cax, ticks=[0, 1]) if not binary: cb.ax.set_yticklabels(['0', "%0.3g+" % max_val], rotation=90) cb.set_label(u'Area of Synaptic Junctions [µm$^2$]') else: cb.ax.set_yticklabels(['0', '1'], rotation=90) cb.set_label(u'Synaptic Junction') plt.close() if not binary: fig.savefig(wd + '/figures/type_wiring%s_conf' 'lvl%d.png' % (add_fname, int(confidence_lvl*10)), dpi=600) else: fig.savefig(wd + '/figures/type_wiring%s_conf' 'lvl%d_binary.png' % (add_fname, int(confidence_lvl*10)), dpi=600)
def plot_all_weights(model, n=64, n_columns=3, **kwargs): """ """ import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable # Set default matplotlib parameters if not 'interpolation' in kwargs.keys(): kwargs['interpolation'] = "none" if not 'cmap' in kwargs.keys(): kwargs['cmap'] = "gray" layers_to_show = [] for i, layer in enumerate(model.layers): if hasattr(layer, "W"): weights = K.eval(layer.W.value()) if weights.ndim == 4: layers_to_show.append((i, layer)) n_mosaic = len(layers_to_show) nrows = n_mosaic // n_columns ncols = n_columns if ncols ** 2 < n_mosaic: nrows +=1 fig_w = 15 fig_h = nrows * fig_w / ncols fig = plt.figure(figsize=(fig_w, fig_h)) for i, (layer_id, layer) in enumerate(layers_to_show): mosaic = get_weights_mosaic(model, layer_id=layer_id, n=n) ax = fig.add_subplot(nrows, ncols, i+1) im = ax.imshow(mosaic, **kwargs) ax.set_title("Layer #{} called '{}' \nof type {}".format(layer_id, layer.name, layer.__class__.__name__)) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) plt.colorbar(im, cax=cax) ax.axis('off') for sp in ax.spines.values(): sp.set_visible(False) if ax.is_first_row(): ax.spines['top'].set_visible(True) if ax.is_last_row(): ax.spines['bottom'].set_visible(True) if ax.is_first_col(): ax.spines['left'].set_visible(True) if ax.is_last_col(): ax.spines['right'].set_visible(True) #fig.tight_layout() return fig
def get_plot_axes(self, figure=None, ax_xy=None): import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable xmin, xmax, ymin, ymax, zmin, zmax = self.get_extent() if figure is None and ax_xy is None: figure = plt.figure() if figure is None and ax_xy is not None: figure = ax_xy.get_figure() if ax_xy is None: ax_xy = figure.add_subplot(111) ratio = float(xmax - xmin) / (ymax - ymin) plot_xz_size = ((zmax - zmin)/(xmax - xmin))*100 plot_yz_size = plot_xz_size / ratio plot_cbar_size = 5 # percent xz_size = '%f %%' % plot_xz_size yz_size = '%f %%' % plot_yz_size cb_size = '%f %%' % plot_cbar_size # ax_xy divider = make_axes_locatable(ax_xy) plt.setp(ax_xy.get_xticklabels(), visible=False) ax_xy.set_xlim(xmin, xmax) ax_xy.set_ylim(ymin, ymax) ax_xy.set_aspect('equal', 'datalim') plt.setp(ax_xy.get_yticklabels(), rotation=90, fontsize=12) # ax_yz ax_yz = divider.append_axes( 'right', size=yz_size, pad=0.05, sharey=ax_xy) plt.setp(ax_yz.get_yticklabels(), visible=False) ax_yz.set_xlim(zmin, zmax) ax_yz.set_ylim(ymin, ymax) plt.setp(ax_yz.get_xticklabels(), rotation=90, fontsize=12) plt.setp(ax_yz.get_yticklabels(), rotation=90, fontsize=12) # ax_xz ax_xz = divider.append_axes( 'bottom', size=xz_size, pad=0.05, sharex=ax_xy) ax_xz.set_xlim(xmin, xmax) ax_xz.set_ylim(zmax, zmin) # color-bar ax_cb = divider.append_axes('bottom', size=cb_size, pad=0.5) return ax_xy, ax_xz, ax_yz, ax_cb
def main(cstcfile, args): st = pd.HDFStore(cstcfile) keys = st.keys()[:-2] # ignore channel 7 name, ext = os.path.splitext(cstcfile) with PdfPages(name + '.pdf') as pdf: fig, axes = plt.subplots(1, 2, figsize=(12, 6)) for i, n in enumerate(keys): df = st[n] m = df.groupby(['cell', 'sample']).mean() s = df.groupby(['cell', 'sample']).std() m2d = m['adc_counts'].values.reshape(-1, 40) s2d = s['adc_counts'].values.reshape(-1, 40) plots = { 'mean': { 'data': m2d, 'ax_id': 0, 'vmax': 15, 'vmin': -15, 'cmap': 'RdBu_r', }, 'std_dev': { 'data': s2d, 'ax_id': 1, 'vmax': 30, 'vmin': 0, 'cmap': 'viridis', }, } for plot_name, plot in plots.items(): ax = axes[plot['ax_id']] ax.cla() im = ax.imshow( plot['data'], cmap=plot['cmap'], aspect='auto', interpolation='nearest', vmin=plot['vmin'], vmax=plot['vmax'], ) divider = make_axes_locatable(ax) cax = divider.append_axes('right', size='5%', pad=0.05) cb = fig.colorbar(im, cax=cax) cb.set_label(plot_name + ' adc count') ax.set_xlabel('sample') ax.set_ylabel('cell') ax.set_title(n) fig.tight_layout() pdf.savefig(fig)