def _fill_cbar_ax(self): x = np.linspace(0, 1, 50).reshape((50, 1)) ax = self.cbar_ax # Dummy image to get the colorbar self._im = ax.imshow(x, extent=[0, 1, 0, 1], visible=False, aspect='auto') self._im.drawon = False self.cbar = colorbar_factory(ax, self._im) ax.yaxis.set_visible(True) self.update()
def _fill_cbar_ax(self): """Put a colorbar-like image in the axes""" x = np.linspace(0, 1, 50).reshape((50, 1)) ax = self.cbar_ax # Dummy image to get the colorbar self._im = ax.imshow(x, extent=[0, 1, 0, 1], visible=False, aspect='auto') self._im.drawon = False self.cbar = colorbar_factory(ax, self._im) ax.yaxis.set_visible(True) self.update()
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 add_snapshot_subplot(ax, dir, start_file, do_cbar=False, figure_index=0, n_files=3, field='s', horiz_slice=False, plot_label=None, dims='$\mathrm{2D}$ | '): plotter = MovieBuddy(dir, max_files=n_files, start_file=start_file) plotter.add_subplot(field, 0, 0, zlabel="s'", sub_t_avg=True) plotter.analyze_subplots() slices = plotter.grab_whole_profile(plotter.local_files['slices'], plotter.local_writes_per_file, subkey=['tasks'], profile_name=[field]) #max = plotter.ax[0]['mean']+stds*plotter.ax[0]['stdev']/2 #min = plotter.ax[0]['mean']-stds*plotter.ax[0]['stdev']/2 max = plotter.ax[0]['max_val']/3 min = -plotter.ax[0]['max_val']/3 if horiz_slice: xs, ys = plotter.y_xx, plotter.y_yy else: xs, ys = plotter.xs, plotter.zs if type(plotter.y) == type(None): img = ax.pcolormesh(xs, ys, slices[field][figure_index,:,:]-plotter.ax[0]['t_avg'], cmap='RdBu_r', vmin=min, vmax=max) else: if horiz_slice: img = ax.pcolormesh(xs, ys, slices[field][figure_index,:,:][:,:,0]-np.mean(plotter.ax[0]['t_avg']), cmap='RdBu_r', vmin=min, vmax=max) else: img = ax.pcolormesh(xs, ys, slices[field][figure_index,:,:][:,0,:]-plotter.ax[0]['t_avg'], cmap='RdBu_r', vmin=min, vmax=max) ax.set_xlim(np.min(xs), np.max(xs)) ax.set_ylim(np.min(ys), np.max(ys)) xticks = np.array([0, np.max(xs)/2, np.max(xs)]) xticklabels = [r'${:1.1f}$'.format(tick) for tick in xticks] xticklabels[0] = r'${:1d}$'.format(0) plt.xticks(xticks, xticklabels, fontsize=8) yticks = np.array([0, np.max(ys)]) yticklabels = [r'${:1.1f}$'.format(tick) for tick in yticks] yticklabels[0] = r'${:1d}$'.format(0) plt.yticks(yticks, yticklabels, fontsize=8) custom_label=True if type(plot_label) == type(None): custom_label=False small_eps, small_ra = False, False plot_label = '{:s}$\epsilon='.format(dims) if plotter.atmosphere['epsilon'] < 0.1: plot_label += '10^{' plot_label += '{:1.0f}'.format(np.log10(plotter.atmosphere['epsilon'])) plot_label += '}$' else: plot_label += '{:1.1f}$'.format(plotter.atmosphere['epsilon']) small_eps = True ra_log = np.log10(plotter.atmosphere['rayleigh']) plot_label += ' | $\mathrm{Ra} = 10^{' if np.floor(ra_log) == ra_log: plot_label += '{:1.0f}'.format(ra_log) small_ra = True else: plot_label += '{:1.2f}'.format(ra_log) plot_label += '}$' plot_label = r'({:s})'.format(plot_label) else: plot_label = r'(${:s}$)'.format(plot_label) # plt.annotate(plot_label, coords, size=9, color='white', path_effects=[PathEffects.withStroke(linewidth=1.2, foreground='black')]) if max > 0.1: cbar_label = '$\pm {:1.2f}$'.format(max) else: str = '{:1.2e}'.format(max) print(str) if 'e+0' in str: newstr = str.replace('e+0', '\\times 10^{') elif 'e-0' in str: newstr = str.replace('e-0', '\\times 10^{-') else: newstr = str.replace('e', '\\times 10^{') newstr += '}' cbar_label = '$\pm {:s}$'.format(newstr) # cbar_label += ' ({:s})'.format(plot_label) if do_cbar: cax, kw = colorbar.make_axes(ax, fraction=0.15, pad=0.03, aspect=5, anchor=(0,0), location='top') cbar = colorbar.colorbar_factory(cax, img, **kw) for label in cax.xaxis.get_ticklabels(): label.set_visible(False) cax.tick_params(axis=u'both', which=u'both',length=0) trans = cax.get_yaxis_transform() cax.annotate(r'{:s}'.format(cbar_label), (1.02,0.04), size=8, color='black', xycoords=trans) cax.annotate(r'{:s}'.format(plot_label), (2.08,0.04), size=8, color='dimgrey', xycoords=trans) else: divider = make_axes_locatable(ax) if horiz_slice: cax = divider.append_axes('top', size='40%', pad=0.01) cbx = divider.append_axes('bottom', size='30%', pad=0.01) cbx.set_frame_on(False) cbx.get_xaxis().set_visible(False) cbx.get_yaxis().set_visible(False) for xlabel in cbx.xaxis.get_ticklabels(): xlabel.set_visible(False) for ylabel in cbx.yaxis.get_ticklabels(): ylabel.set_visible(False) else: cax = divider.append_axes('top', size='10%', pad=0.06) cax.set_frame_on(False) cax.get_xaxis().set_visible(False) cax.get_yaxis().set_visible(False) for xlabel in cax.xaxis.get_ticklabels(): xlabel.set_visible(False) for ylabel in cax.yaxis.get_ticklabels(): ylabel.set_visible(False) trans = ax.get_xaxis_transform() # x in data untis, y in axes fraction ann = ax.annotate(cbar_label, xy=(-0.05, 1.05 ), size=8, color='black', xycoords=trans) if not custom_label: if np.floor(ra_log) != ra_log: ann = ax.annotate(plot_label, xy=(xticks[-1]*0.48, 1.05 ), size=8, color='dimgrey', xycoords=trans) elif small_eps: ann = ax.annotate(plot_label, xy=(xticks[-1]*0.53, 1.05 ), size=8, color='dimgrey', xycoords=trans) else: ann = ax.annotate(plot_label, xy=(xticks[-1]*0.49, 1.05 ), size=8, color='dimgrey', xycoords=trans) else: ann = ax.annotate(plot_label, xy=(xticks[1]*1.25, 1.05 ), size=8, color='dimgrey', xycoords=trans)
elif species == "all2": fig.subplots_adjust(right=0.8) cax = fig.add_axes([0.9, 0.1, 0.03, 0.8]) elif species == "allRow": fig.subplots_adjust(right=0.87, left=0.055, top=0.96, bottom=0.2, wspace=0.07) cax = fig.add_axes([0.885, 0.2, 0.03, 0.76]) my_levels = np.logspace(10,20,11) #print my_levels CBpos = colorbar.ColorbarBase(cax,cmap=Cu_CS0.cmap,norm=Cu_CS0.norm, boundaries=my_levels, values=my_levels) if species == "all": cax2 = fig.add_axes([0.9, 0.1, 0.03, 0.8]) if qdens_CS2 != None: #Plot empty cbar in case of no negative charge density CBneg = colorbar.colorbar_factory(cax2,qdens_CS2) CBneg.values = my_levels CBneg.boundaries = my_levels CBneg.set_ticks(np.logspace(10,20,6)) # CBneg.update_ticks() CBneg.config_axis() CBneg.draw_all() if species != "allRow": plt.suptitle("Densities, time = %.3f [ns]" % (timestamp[i],)) else: CBpos.set_label("Particle density [cm\\textsuperscript{-3}]") plt.savefig(ofoldername + "/dens_log_%08d.png" %(outIdx,),dpi=DPI) plt.savefig(ofoldername + "/dens_log_%08d.pdf" %(outIdx,)) plt.clf()
def __init__(self, ax, im): AxesWidget.__init__(self, ax) self.cbar = colorbar_factory(ax, im) self.fmt = self.cbar.formatter = OffsetFormatter() self.ax.yaxis.set_visible(True)
def plot_field(self, xs, zs, field, ax, field_name, cmap='RdYlBu_r', min=None, max=None,\ xlims=None, ylims=None, mod=None, plot_title=True, function='colormap', bare=False): ''' Plots a colormap of a given field. xs -- a 2D grid of x-values zs -- a 2D grid of z-values field -- a 2D grid of values in the x-z plane for another parameter. ax -- the Axis subplot on which to plot the field. field_name -- The physical name that the numbers in 'field' represent cmap -- the colormap of the plot min, max -- the min and max values of the colormap to plot xlims, ylims -- the boundaries on the x- and y- coordinates. mod -- A modification on the field to alter the movie. Currently accepts: "up" -- upflows "down" -- downflows "pos" -- Positive parts only "neg" -- Negative parts only bare -- If bare, then don't plot up any axis information (public talks, etc.) ''' print(xs.shape, zs.shape, field.shape) if self.idle: return if max == None: max = np.max(field) if min == None: min = np.min(field) if function == 'colormap': plot = ax.pcolormesh(xs, zs, field, cmap=cmap, vmin=min, vmax=max) if not bare: xticks = np.array([1, np.max(xs)/2, np.max(xs)]) yticks = np.array([1, np.max(zs)/2, np.max(zs)]) plt.xticks(xticks, [r'${:1.2f}$'.format(tick) for tick in xticks], fontsize=11) plt.yticks(yticks, [r'${:1.2f}$'.format(tick) for tick in yticks], fontsize=11) if self.atmosphere['atmosphere_name'] == 'single polytrope': plot_label = '$\epsilon=' if self.atmosphere['epsilon'] < 0.1: plot_label += '10^{' plot_label += '{:1.0f}'.format(np.log10(self.atmosphere['epsilon'])) plot_label += '}$' else: plot_label += '{:1.1f}$'.format(self.atmosphere['epsilon']) small_eps = True ra_log = np.log10(self.atmosphere['rayleigh']) plot_label += ' | $\mathrm{Ra} = 10^{' if np.floor(ra_log) == ra_log: plot_label += '{:1.0f}'.format(ra_log) small_ra = True else: plot_label += '{:1.2f}'.format(ra_log) plot_label += '}$' plot_label = r'{:s}'.format(plot_label) else: print('ERROR: Unknown atmosphere type') plot_label='' if max > 0.1: cbar_label = '$\pm {:1.2f}$'.format(max) else: str = '{:1.2e}'.format(max) if 'e+0' in str: newstr = str.replace('e+0', '\\times 10^{') elif 'e-0' in str: newstr = str.replace('e-0', '\\times 10^{-') else: newstr = str.replace('e', '\\times 10^{') newstr += '}' if min != 0: cbar_label = '$\pm {:s}$'.format(newstr) else: cbar_label = '$min: 0 max: {:s}$'.format(newstr) cbar_label += ' ({:s})'.format(plot_label) cbar_label += ' {:s}'.format(field_name) divider = make_axes_locatable(ax) cax, kw = colorbar.make_axes(ax, fraction=0.07, pad=0.03, aspect=5, anchor=(0,0), location='top') cbar = colorbar.colorbar_factory(cax, plot, **kw) trans = cax.get_yaxis_transform() cax.annotate(r'{:s}'.format(cbar_label), (1.02,0.01), size=11, color='black', xycoords=trans) cax.tick_params(axis=u'both', which=u'both',length=0) cax.set_xticklabels([]) cax.set_xticks([]) # for label in cax.xaxis.get_ticklabels(): # label.set_visible(False) # for label in cax.yaxis.get_ticklabels(): # label.set_visible(False) elif function == 'contour': field[np.where(field > max)] = max field[np.where(field < min)] = min plot = ax.contour(xs, zs, field, 7, cmap=plt.cm.gray) if xlims == None or len(xlims) != 2: ax.set_xlim(np.min(xs), np.max(xs)) else: ax.set_xlim(xlims[0], xlims[1]) if ylims == None or len(ylims) != 2: ax.set_ylim(np.min(zs), np.max(zs)) else: ax.set_ylim(ylims[0], ylims[1]) if bare: ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)
wspace=0.07) cax = fig.add_axes([0.885, 0.2, 0.03, 0.76]) my_levels = np.logspace(10, 20, 11) #print my_levels CBpos = colorbar.ColorbarBase(cax, cmap=Cu_CS0.cmap, norm=Cu_CS0.norm, boundaries=my_levels, values=my_levels) if species == "all": cax2 = fig.add_axes([0.9, 0.1, 0.03, 0.8]) if qdens_CS2 != None: #Plot empty cbar in case of no negative charge density CBneg = colorbar.colorbar_factory(cax2, qdens_CS2) CBneg.values = my_levels CBneg.boundaries = my_levels CBneg.set_ticks(np.logspace(10, 20, 6)) # CBneg.update_ticks() CBneg.config_axis() CBneg.draw_all() if species != "allRow": plt.suptitle("Densities, time = %.3f [ns]" % (timestamp[i], )) else: CBpos.set_label("Particle density [cm\\textsuperscript{-3}]") plt.savefig(ofoldername + "/dens_log_%08d.png" % (outIdx, ), dpi=DPI) plt.savefig(ofoldername + "/dens_log_%08d.pdf" % (outIdx, )) plt.clf()