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 _create_rescale_figure(self): import matplotlib.pyplot as plt from matplotlib.widgets import Slider import matplotlib.colorbar as mcbar self.fig, (self.ax_orig, self.ax_rescale) = plt.subplots( 2, 1, figsize=(8, 12), gridspec_kw=dict(top=1.0, bottom=0.0)) slider_ax, kw = mcbar.make_axes_gridspec( self.ax_rescale, orientation='horizontal', location='bottom') slider_ax.set_aspect('auto') slider_ax._hold = True self.slider = Slider(slider_ax, 'Fraction', 0, 100, valfmt='%1.3g %%') self.slider.set_val(100) self.slider.on_changed(self.rescale_plot) self.im_orig = self.ax_orig.imshow(self.straditizer.image) self.im_rescale = self.ax_rescale.imshow(self.straditizer.image) # connect limits self.ax_orig.callbacks.connect('xlim_changed', self.adjust_rescaled_limits) self.ax_orig.callbacks.connect('ylim_changed', self.adjust_rescaled_limits) self.ax_rescale.callbacks.connect('xlim_changed', self.adjust_orig_limits) self.ax_rescale.callbacks.connect('ylim_changed', self.adjust_orig_limits) self.fig.canvas.mpl_connect('resize_event', self.equalize_axes) self.connect2apply(self.rescale, self.close_figs) self.connect2cancel(self.close_figs) self.raise_figure() self.equalize_axes()
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 _render_on_subplot(self, subplot): """ TESTS: A somewhat random plot, but fun to look at:: sage: x,y = var('x,y') sage: contour_plot(x^2-y^3+10*sin(x*y), (x, -4, 4), (y, -4, 4),plot_points=121,cmap='hsv') Graphics object consisting of 1 graphics primitive """ from sage.rings.integer import Integer options = self.options() fill = options['fill'] contours = options['contours'] if 'cmap' in options: cmap = get_cmap(options['cmap']) elif fill or contours is None: cmap = get_cmap('gray') else: if isinstance(contours, (int, Integer)): cmap = get_cmap([(i, i, i) for i in xsrange(0, 1, 1 / contours)]) else: l = Integer(len(contours)) cmap = get_cmap([(i, i, i) for i in xsrange(0, 1, 1 / l)]) x0, x1 = float(self.xrange[0]), float(self.xrange[1]) y0, y1 = float(self.yrange[0]), float(self.yrange[1]) if isinstance(contours, (int, Integer)): contours = int(contours) CSF = None if fill: if contours is None: CSF = subplot.contourf(self.xy_data_array, cmap=cmap, extent=(x0, x1, y0, y1), label=options['legend_label']) else: CSF = subplot.contourf(self.xy_data_array, contours, cmap=cmap, extent=(x0, x1, y0, y1), extend='both', label=options['legend_label']) linewidths = options.get('linewidths', None) if isinstance(linewidths, (int, Integer)): linewidths = int(linewidths) elif isinstance(linewidths, (list, tuple)): linewidths = tuple(int(x) for x in linewidths) from sage.plot.misc import get_matplotlib_linestyle linestyles = options.get('linestyles', None) if isinstance(linestyles, (list, tuple)): linestyles = [ get_matplotlib_linestyle(l, 'long') for l in linestyles ] else: linestyles = get_matplotlib_linestyle(linestyles, 'long') if contours is None: CS = subplot.contour(self.xy_data_array, cmap=cmap, extent=(x0, x1, y0, y1), linewidths=linewidths, linestyles=linestyles, label=options['legend_label']) else: CS = subplot.contour(self.xy_data_array, contours, cmap=cmap, extent=(x0, x1, y0, y1), linewidths=linewidths, linestyles=linestyles, label=options['legend_label']) if options.get('labels', False): label_options = options['label_options'] label_options['fontsize'] = int(label_options['fontsize']) if fill and label_options is None: label_options['inline'] = False subplot.clabel(CS, **label_options) if options.get('colorbar', False): colorbar_options = options['colorbar_options'] from matplotlib import colorbar cax, kwds = colorbar.make_axes_gridspec(subplot, **colorbar_options) if CSF is None: cb = colorbar.Colorbar(cax, CS, **kwds) else: cb = colorbar.Colorbar(cax, CSF, **kwds) cb.add_lines(CS)
def _render_on_subplot(self, subplot): """ TESTS:: sage: matrix_plot(random_matrix(RDF, 50), cmap='jet') """ options = self.options() cmap = get_cmap(options.pop('cmap', None)) origin = options['origin'] norm = options['norm'] if norm == 'value': import matplotlib norm = matplotlib.colors.NoNorm() if options['subdivisions']: subdiv_options = options['subdivision_options'] if isinstance(subdiv_options['boundaries'], (list, tuple)): rowsub, colsub = subdiv_options['boundaries'] else: rowsub = subdiv_options['boundaries'] colsub = subdiv_options['boundaries'] if isinstance(subdiv_options['style'], (list, tuple)): rowstyle, colstyle = subdiv_options['style'] else: rowstyle = subdiv_options['style'] colstyle = subdiv_options['style'] if rowstyle is None: rowstyle = dict() if colstyle is None: colstyle = dict() # Make line objects for subdivisions from line import line2d lim = self.get_minmax_data() # First draw horizontal lines representing row subdivisions for y in rowsub: l = line2d([(lim['xmin'], y - 0.5), (lim['xmax'], y - 0.5)], **rowstyle)[0] l._render_on_subplot(subplot) for x in colsub: l = line2d([(x - 0.5, lim['ymin']), (x - 0.5, lim['ymax'])], **colstyle)[0] l._render_on_subplot(subplot) if hasattr(self.xy_data_array, 'tocoo'): # Sparse matrix -- use spy opts = options.copy() for opt in [ 'vmin', 'vmax', 'norm', 'origin', 'subdivisions', 'subdivision_options', 'colorbar', 'colorbar_options' ]: del opts[opt] if origin == 'lower': subplot.spy(self.xy_data_array.tocsr()[::-1], **opts) else: subplot.spy(self.xy_data_array, **opts) else: opts = dict(cmap=cmap, interpolation='nearest', aspect='equal', norm=norm, vmin=options['vmin'], vmax=options['vmax'], origin=origin, zorder=options.get('zorder', None)) image = subplot.imshow(self.xy_data_array, **opts) if options.get('colorbar', False): colorbar_options = options['colorbar_options'] from matplotlib import colorbar cax, kwds = colorbar.make_axes_gridspec( subplot, **colorbar_options) cb = colorbar.Colorbar(cax, image, **kwds) if origin == 'upper': subplot.xaxis.tick_top() elif origin == 'lower': subplot.xaxis.tick_bottom() subplot.xaxis.set_ticks_position( 'both') #only tick marks, not tick labels
def _render_on_subplot(self, subplot): """ TESTS: A somewhat random plot, but fun to look at:: sage: x,y = var('x,y') sage: contour_plot(x^2-y^3+10*sin(x*y), (x, -4, 4), (y, -4, 4),plot_points=121,cmap='hsv') """ from sage.rings.integer import Integer options = self.options() fill = options['fill'] contours = options['contours'] if options.has_key('cmap'): cmap = get_cmap(options['cmap']) elif fill or contours is None: cmap = get_cmap('gray') else: if isinstance(contours, (int, Integer)): cmap = get_cmap([(i,i,i) for i in xsrange(0,1,1/contours)]) else: l = Integer(len(contours)) cmap = get_cmap([(i,i,i) for i in xsrange(0,1,1/l)]) x0,x1 = float(self.xrange[0]), float(self.xrange[1]) y0,y1 = float(self.yrange[0]), float(self.yrange[1]) if isinstance(contours, (int, Integer)): contours = int(contours) CSF=None if fill: if contours is None: CSF=subplot.contourf(self.xy_data_array, cmap=cmap, extent=(x0,x1,y0,y1), label=options['legend_label']) else: CSF=subplot.contourf(self.xy_data_array, contours, cmap=cmap, extent=(x0,x1,y0,y1),extend='both', label=options['legend_label']) linewidths = options.get('linewidths',None) if isinstance(linewidths, (int, Integer)): linewidths = int(linewidths) elif isinstance(linewidths, (list, tuple)): linewidths = tuple(int(x) for x in linewidths) linestyles = options.get('linestyles',None) if contours is None: CS = subplot.contour(self.xy_data_array, cmap=cmap, extent=(x0,x1,y0,y1), linewidths=linewidths, linestyles=linestyles, label=options['legend_label']) else: CS = subplot.contour(self.xy_data_array, contours, cmap=cmap, extent=(x0,x1,y0,y1), linewidths=linewidths, linestyles=linestyles, label=options['legend_label']) if options.get('labels', False): label_options = options['label_options'] label_options['fontsize'] = int(label_options['fontsize']) if fill and label_options is None: label_options['inline']=False subplot.clabel(CS, **label_options) if options.get('colorbar', False): colorbar_options = options['colorbar_options'] from matplotlib import colorbar cax,kwds=colorbar.make_axes_gridspec(subplot,**colorbar_options) if CSF is None: cb=colorbar.Colorbar(cax,CS, **kwds) else: cb=colorbar.Colorbar(cax,CSF, **kwds) cb.add_lines(CS)
def _scatter_legends( df, ax, cmap, ck, ondata: bool, onside: bool, fontsize: float, title: str, title_fontsize: float, hide_title: bool, n_per_col: int, scale: float, ls: float, cs: float, cbs: float, ) -> None: """ Args: df: dataframe ax: axis object cmap: color map ck: color key ondata: display legend over scatter plot? onside: display legend on side? fontsize: fontsize of legend text title: Title of subplot/axes hide_title: Whether to hide the title n_per_col: number of legends per column scale: scale legend marker size ls: line spacing cs: column spacing cbs: Cbar shrink factor Returns: """ from matplotlib.colors import Normalize from matplotlib.colorbar import ColorbarBase, make_axes_gridspec x, y, vc = df.columns[:3] v = df[vc] cax = make_axes_gridspec(ax, location="top", shrink=cbs, aspect=25, fraction=0.1)[0] if v.nunique() <= 1: cax.set_axis_off() return None if v.dtype.name == "category": if hide_title is False: if title is not None: ax.title.set_text(title) else: ax.title.set_text(vc) ax.title.set_fontsize(title_fontsize) centers = df[[x, y, vc]].groupby(vc).median().T for i in centers: if ondata: ax.text( centers[i][x], centers[i][y], i, fontsize=fontsize, ha="center", va="center", ) if onside: ax.scatter( [float(centers[i][x])], [float(centers[i][y])], c=ck[i], label=i, alpha=1, s=0.01, ) if onside: n_cols = v.nunique() // n_per_col if v.nunique() % n_per_col > 0: n_cols += 1 ax.legend( ncol=n_cols, loc=(1, 0), frameon=False, fontsize=fontsize, markerscale=scale, labelspacing=ls, columnspacing=cs, ) cax.set_axis_off() else: norm = Normalize(vmin=v.min(), vmax=v.max()) cb = ColorbarBase(cax, cmap=cmap, norm=norm, orientation="horizontal") if hide_title is False: if title is not None: cb.set_label(title, fontsize=title_fontsize) else: cb.set_label(vc, fontsize=title_fontsize) cb.ax.xaxis.set_label_position("bottom") cb.ax.xaxis.set_ticks_position("top") cb.outline.set_visible(False) return None
def _render_on_subplot(self, subplot): """ TESTS:: sage: matrix_plot(random_matrix(RDF, 50), cmap='jet') Graphics object consisting of 1 graphics primitive """ options = self.options() cmap = get_cmap(options.pop('cmap',None)) origin=options['origin'] norm=options['norm'] if norm=='value': import matplotlib norm=matplotlib.colors.NoNorm() if options['subdivisions']: subdiv_options=options['subdivision_options'] if isinstance(subdiv_options['boundaries'], (list, tuple)): rowsub,colsub=subdiv_options['boundaries'] else: rowsub=subdiv_options['boundaries'] colsub=subdiv_options['boundaries'] if isinstance(subdiv_options['style'], (list, tuple)): rowstyle,colstyle=subdiv_options['style'] else: rowstyle=subdiv_options['style'] colstyle=subdiv_options['style'] if rowstyle is None: rowstyle=dict() if colstyle is None: colstyle=dict() # Make line objects for subdivisions from line import line2d lim=self.get_minmax_data() # First draw horizontal lines representing row subdivisions for y in rowsub: l=line2d([(lim['xmin'],y-0.5), (lim['xmax'],y-0.5)], **rowstyle)[0] l._render_on_subplot(subplot) for x in colsub: l=line2d([(x-0.5, lim['ymin']), (x-0.5, lim['ymax'])], **colstyle)[0] l._render_on_subplot(subplot) if hasattr(self.xy_data_array, 'tocoo'): # Sparse matrix -- use spy opts=options.copy() for opt in ['vmin', 'vmax', 'norm', 'origin','subdivisions','subdivision_options', 'colorbar','colorbar_options']: del opts[opt] if origin=='lower': subplot.spy(self.xy_data_array.tocsr()[::-1], **opts) else: subplot.spy(self.xy_data_array, **opts) else: opts = dict(cmap=cmap, interpolation='nearest', aspect='equal', norm=norm, vmin=options['vmin'], vmax=options['vmax'], origin=origin,zorder=options.get('zorder',None)) image=subplot.imshow(self.xy_data_array, **opts) if options.get('colorbar', False): colorbar_options = options['colorbar_options'] from matplotlib import colorbar cax,kwds=colorbar.make_axes_gridspec(subplot,**colorbar_options) cb=colorbar.Colorbar(cax,image, **kwds) if origin=='upper': subplot.xaxis.tick_top() elif origin=='lower': subplot.xaxis.tick_bottom() subplot.xaxis.set_ticks_position('both') #only tick marks, not tick labels
def plot_phase_mag(inputs, outputs, dataset, hb_name, mode): weighted_basin_phase_mag_filename = inputs['weighted'] df_phase_mag = pd.read_hdf(weighted_basin_phase_mag_filename) raster_hb_name = hb_name raster_cube = iris.load_cube(str(inputs['raster_cubes']), f'hydrobasins_raster_{raster_hb_name}') raster = raster_cube.data phase_filename, alpha_phase_filename, mag_filename = outputs print(f'Plot maps - {hb_name}_{mode}: {dataset}') cmap, norm, bounds, cbar_kwargs = load_cmap_data( 'cmap_data/li2018_fig3_cb.pkl') phase_map, mag_map = gen_map_from_basin_values(df_phase_mag, raster) phase_map = iris.cube.Cube(phase_map, long_name='phase_map', units='hr', dim_coords_and_dims=[ (raster_cube.coord('latitude'), 0), (raster_cube.coord('longitude'), 1) ]) mag_map = iris.cube.Cube(mag_map, long_name='magnitude_map', units='-', dim_coords_and_dims=[ (raster_cube.coord('latitude'), 0), (raster_cube.coord('longitude'), 1) ]) extent = get_extent_from_cube(phase_map) plt.figure(figsize=(10, 8)) ax = plt.subplot(projection=ccrs.PlateCarree()) ax.set_title(f'{dataset} {mode} phase') masked_phase_map = np.ma.masked_array(phase_map.data, raster_cube.data == 0) masked_mag_map = np.ma.masked_array(mag_map.data, raster_cube.data == 0) im = ax.imshow(masked_phase_map, cmap=cmap, norm=norm, origin='lower', extent=extent, vmin=0, vmax=24) plt.colorbar(im, orientation='horizontal') configure_ax_asia(ax, extent) # plt.tight_layout() plt.savefig(phase_filename) plt.close() fig = plt.figure(figsize=(10, 8)) ax = plt.subplot(projection=ccrs.PlateCarree()) ax.set_title(f'{dataset} {mode} phase (alpha)') _plot_phase_alpha(ax, masked_phase_map, masked_mag_map, cmap, norm, extent) configure_ax_asia(ax, extent) cax, _ = cbar.make_axes_gridspec(ax, orientation='horizontal') v = np.linspace(0, 1, 24) d = cmap(v)[None, :, :4] * np.ones((3, 24, 4)) d[1, :, 3] = 0.66 d[0, :, 3] = 0.33 cax.imshow(d, origin='lower', extent=(0, 24, 0, 2), aspect='auto') cax.set_yticks([]) cax.set_xticks(np.linspace(0, 24, 9)) # plt.tight_layout() plt.savefig(alpha_phase_filename) plt.close() plt.figure(figsize=(10, 8)) ax = plt.subplot(projection=ccrs.PlateCarree()) ax.set_title(f'{dataset} {mode} strength') im = ax.imshow(masked_mag_map, origin='lower', extent=extent, vmin=1e-2, norm=LogNorm()) plt.colorbar(im, orientation='horizontal') configure_ax_asia(ax, extent) # plt.tight_layout() plt.savefig(mag_filename) plt.close()
def _render_on_subplot(self, subplot): """ TESTS:: sage: matrix_plot(random_matrix(RDF, 50), cmap='jet') """ options = self.options() cmap = get_cmap(options.pop("cmap", None)) origin = options["origin"] norm = options["norm"] if norm == "value": import matplotlib norm = matplotlib.colors.NoNorm() if options["subdivisions"]: subdiv_options = options["subdivision_options"] if isinstance(subdiv_options["boundaries"], (list, tuple)): rowsub, colsub = subdiv_options["boundaries"] else: rowsub = subdiv_options["boundaries"] colsub = subdiv_options["boundaries"] if isinstance(subdiv_options["style"], (list, tuple)): rowstyle, colstyle = subdiv_options["style"] else: rowstyle = subdiv_options["style"] colstyle = subdiv_options["style"] if rowstyle is None: rowstyle = dict() if colstyle is None: colstyle = dict() # Make line objects for subdivisions from line import line2d lim = self.get_minmax_data() # First draw horizontal lines representing row subdivisions for y in rowsub: l = line2d([(lim["xmin"], y - 0.5), (lim["xmax"], y - 0.5)], **rowstyle)[0] l._render_on_subplot(subplot) for x in colsub: l = line2d([(x - 0.5, lim["ymin"]), (x - 0.5, lim["ymax"])], **colstyle)[0] l._render_on_subplot(subplot) if hasattr(self.xy_data_array, "tocoo"): # Sparse matrix -- use spy opts = options.copy() for opt in [ "vmin", "vmax", "norm", "origin", "subdivisions", "subdivision_options", "colorbar", "colorbar_options", ]: del opts[opt] if origin == "lower": subplot.spy(self.xy_data_array.tocsr()[::-1], **opts) else: subplot.spy(self.xy_data_array, **opts) else: opts = dict( cmap=cmap, interpolation="nearest", aspect="equal", norm=norm, vmin=options["vmin"], vmax=options["vmax"], origin=origin, zorder=options.get("zorder", None), ) image = subplot.imshow(self.xy_data_array, **opts) if options.get("colorbar", False): colorbar_options = options["colorbar_options"] from matplotlib import colorbar cax, kwds = colorbar.make_axes_gridspec(subplot, **colorbar_options) cb = colorbar.Colorbar(cax, image, **kwds) if origin == "upper": subplot.xaxis.tick_top() elif origin == "lower": subplot.xaxis.tick_bottom() subplot.xaxis.set_ticks_position("both") # only tick marks, not tick labels
def setColorBar(TT, fig, lax, blw=1.0, cblabel=r"$z$", subs=[1.0], pad=0.01, borders=True, borcol=[], width=1.0, size=1.0, loc='right', fmt=None, label_kw=None, ticks_kw=None): """Produce a color bar for gradient plots.""" import matplotlib.colors as col import matplotlib.colorbar as colbar import matplotlib.ticker as ticker if label_kw is None: label_kw = {} if ticks_kw is None: ticks_kw = {} cax_kw = {'shrink': size, 'aspect': 20.0 / width, 'pad': pad} col_kw = {} if borders is True: col_kw.update({ 'extendfrac': 0.01, 'extend': 'both', 'extendrect': True }) else: col_kw.update({'extend': 'neither'}) if type(TT.norm) == col.LogNorm: cbticks = ticker.LogLocator(base=10.0, subs=subs) col_kw.update({'ticks': cbticks}) try: list(lax) cax, ckw = colbar.make_axes_gridspec([ax for ax in lax.flat], **cax_kw) except TypeError: cax, ckw = colbar.make_axes_gridspec(lax, **cax_kw) col_kw.update(ckw) CB = fig.colorbar(TT, cax=cax, use_gridspec=True, format=fmt, **col_kw) CB.set_label(cblabel, **label_kw) CB.ax.tick_params(which='both', length=0.0, **ticks_kw) CB.outline.set_linewidth(blw) if borders is True: if len(borcol) == 0: CB.cmap.set_under(color='k') CB.cmap.set_over(color='w') else: CB.cmap.set_under(color=borcol[0]) CB.cmap.set_over(color=borcol[1]) CB.outline.set_figure(fig) return CB
def _make_room(self, ax, **kwargs): """Shrink parent axes and make a new axes for widgets.""" cax, _ = make_axes_gridspec(ax, **kwargs) cax.axis('off') cax.set(aspect=1) return cax
def plot3dclassprobs(self, **kwds): """Return 3D plot of class probabilities. Keywords: dGs - Sequence of dG values to plot. Default is all values. highlight - Sequence of dG values to highlight on plot. Default is []. classes - Sequence of indices of classes to plot. Default is all classes. probfilter - [float1, float2]. Only show classes with maximum probability in given range. Default is [0., 1.] class_size - Report the size of each class as a "number" or "fraction". Default is "number". norm - A colors normalization for displaying number/fraction of models in class. Default is "auto". If equal to "full" determined by the total number of models. If equal to "auto" determined by the number of models in displayed classes. cmap - A colormap or registered colormap name. Default is cm.jet. If class_size is "number" and norm is either "auto" or "full" the map is converted to an indexed colormap. highlight_cmap - A colormap or registered colormap name for coloring highlights. Default is cm.gray. title - True, False, or a string. Defaults to True, which displays some basic information about the graph. p_alpha - Probability graph alpha. (Colorbar remains opaque). Default is 0.7. figure - A matplotlib.figure.Figure instance. Default is the current figure. subplot - Specify a subplot. Default is 111. cbpos - Explicit position for colorbar given as (l,b,w,h) in axes coordinates. Does not resize other elements. Note that this overrides all colorbar keywords except orientation. scale - Scales the dG shown on the graph. All other keywords are passed to the colorbar. Returns a dictionary containing the following figure elements: "fig" - The figure "axis" - The image axis "cbaxis" - The colorbar axis, if it exists. "cb" - The colorbar, if it exists.""" from mpl_toolkits.mplot3d import Axes3D from matplotlib.collections import PolyCollection from matplotlib import cm, colors, colorbar fig = kwds.pop("figure", plt.gcf()) ax = fig.add_subplot(kwds.pop("subplot",111), projection='3d') cbkwds = kwds.copy() # Resolve keywords (title resolved later) dGs = kwds.pop("dGs", self.dgs) highlight = kwds.pop("highlight", []) classes = kwds.pop("classes", range(len(self.classes))) probfilter = kwds.pop("probfilter", [0.,1.]) class_size = kwds.pop("class_size", "number") norm = kwds.pop("norm", "auto") cmap = kwds.pop("cmap", cm.jet) highlight_cmap = kwds.pop("highlight_cmap", cm.gray) title = kwds.pop("title", True) p_alpha = kwds.pop("p_alpha", 0.7) scale = kwds.pop("scale", 1.) xs = dGs*scale verts = [] zs = [] zlabels = [] for i in classes: ys = [self.classprobs[dG][i] for dG in dGs] maxys = np.max(ys) if maxys >= probfilter[0] and maxys <= probfilter[1]: p0, p1 = ((xs[0], 0), (xs[-1],0)) # points to close the vertices verts.append(np.concatenate([[p0], zip(xs,ys), [p1], [p0]])) zlabels.append(i) ### Define face colors fc = np.array([len(self.classes[z]) for z in zlabels]) if class_size is "fraction": fc = fc/float(len(self.results)) # Index the colormap if necessary if class_size is "number": if norm is "auto": indexedcolors = cmap(np.linspace(0., 1., np.max(fc))) cmap = colors.ListedColormap(indexedcolors) elif norm is "full": indexedcolors = cmap(np.linspace(0., 1., len(self.results))) cmap = colors.ListedColormap(indexedcolors) # A user-specified norm cannot be used to index a colormap. # Create proper norms for "auto" and "full" types. if norm is "auto": if class_size is "number": mic = np.min(fc) mac = np.max(fc) nc = mac - mic + 1 norm = colors.BoundaryNorm(np.linspace(mic, mac+1, nc+1), nc) if class_size is "fraction": norm = colors.Normalize() norm.autoscale(fc) elif norm is "full": mcolor = len(self.results) if class_size is "number": norm = colors.BoundaryNorm(np.linspace(0, mcolor+1, mcolor+2), mcolor+1) if class_size is "fraction": norm = colors.Normalize(0., 1.) zs = np.arange(len(zlabels)) poly = PolyCollection(verts, facecolors=cmap(norm(fc)), closed=False) poly.set_alpha(p_alpha) cax = ax.add_collection3d(poly, zs=zs, zdir='y') # Highlight values of interest color_idx = np.linspace(0, 1, len(highlight)) for dG, ci in zip(highlight, color_idx): for z_logical, z_plot in zip(zlabels, zs): ax.plot([dG, dG], [z_plot, z_plot], [0, self.classprobs[dG][z_logical]], color=highlight_cmap(ci), alpha=p_alpha) ax.set_xlabel('dG') ax.set_xlim3d(dGs[0]*scale, dGs[-1]*scale) ax.set_ylabel('Class') ax.set_ylim3d(zs[0], zs[-1]) ax.set_yticks(zs) ax.set_yticklabels([str(z) for z in zlabels]) ax.set_zlabel('Akaike probability') ax.set_zlim3d(0, 1) if title is True: title = "Class probabilities\n\ Max probabilities in %s\n\ %i/%i classes with %i/%i models displayed"\ %(probfilter, len(zs), len(self.classes), np.sum([len(self.classes[z]) for z in zlabels]), len(self.results) ) if title is not False: figtitle = fig.suptitle(title) # Add colorbar if "cbpos" in kwds: cbpos = kwds.pop("cbpos") aspect = cbpos[3]/cbpos[2] plt.tight_layout() # do it before cbaxis, so colorbar is ignored. transAtoF = ax.transAxes + fig.transFigure.inverted() rect = transforms.Bbox.from_bounds(*cbpos).transformed(transAtoF).bounds cbaxis = fig.add_axes(rect) # Remove all colorbar.make_axes keywords except orientation kwds = eatkwds("fraction", "pad", "shrink", "aspect", "anchor", "panchor", **kwds) else: kwds.setdefault("shrink", 0.75) # In matplotlib 1.1.0 make_axes_gridspec ignores anchor and panchor keywords. # Eat these keywords for now. kwds = eatkwds("anchor", "panchor", **kwds) cbaxis, kwds = colorbar.make_axes_gridspec(ax, **kwds) # gridspec allows tight_layout plt.tight_layout() # do it after cbaxis, so colorbar isn't ignored cb = colorbar.ColorbarBase(cbaxis, cmap=cmap, norm=norm, **kwds) if class_size is "number": cb.set_label("Models in class") elif class_size is "fraction": cb.set_label("Fraction of models in class") return {"fig":fig, "axis":ax, "cb":cb, "cbaxis": cbaxis}