def Histo(x, mean, sigma_mean, std, stderr, P, orient='horizontal', xlabel='', ylabel=''): ''' Function that plot the histogramm of the distribution given in x imputs: -x is the distrib itself (array) -mean is the mean of the distrib (float) -sigma_mean : the error on the average (float) -std : the standard deviation (RMS) of the distribution (float) -stderr : the errot on the RMS (float) -P is the figure where the histogram will be plotted. -xylabel and y label are the name ofthe axis. ''' numBins = 20 P.hist(x, numBins, color='blue', alpha=0.8, orientation=orient, label='average = ' + str("%.5f" % mean) + '$\pm$' + str("%.5f" % sigma_mean) + '\n' + 'rms =' + str("%.5f" % std) + '$\pm$' + str("%.5f" % stderr)) if xlabel == '': P.set_xlabel('number of SNe') else: P.set_xlabel(xlabel) if ylabel == '': P.set_ylabel('number of SNe') else: P.set_ylabel(ylabel) P.set_title('Residuals') P.legend(bbox_to_anchor=(0.95, 1.0), prop={'size': 10})
def image(sim, qty='rho', width="10 kpc", resolution=500, units=None, log=True, vmin=None, vmax=None, av_z=False, filename=None, z_camera=None, clear=True, cmap=None, title=None, qtytitle=None, show_cbar=True, subplot=False, noplot=False, ret_im=False, fill_nan=True, fill_val=0.0, linthresh=None, **kwargs): """ Make an SPH image of the given simulation. **Keyword arguments:** *qty* (rho): The name of the array to interpolate *width* (10 kpc): The overall width and height of the plot. If ``width`` is a float or an int, then it is assumed to be in units of ``sim['pos']``. It can also be passed in as a string indicating the units, i.e. '10 kpc', in which case it is converted to units of ``sim['pos']``. *resolution* (500): The number of pixels wide and tall *units* (None): The units of the output *av_z* (False): If True, the requested quantity is averaged down the line of sight (default False: image is generated in the thin plane z=0, unless output units imply an integral down the line of sight). If a string, the requested quantity is averaged down the line of sight weighted by the av_z array (e.g. use 'rho' for density-weighted quantity; the default results when av_z=True are volume-weighted). *z_camera* (None): If set, a perspective image is rendered. See :func:`pynbody.sph.image` for more details. *filename* (None): if set, the image will be saved in a file *clear* (True): whether to call clf() on the axes first *cmap* (None): user-supplied colormap instance *title* (None): plot title *qtytitle* (None): colorbar quantity title *show_cbar* (True): whether to plot the colorbar *subplot* (False): the user can supply a AxesSubPlot instance on which the image will be shown *noplot* (False): do not display the image, just return the image array *ret_im* (False): return the image instance returned by imshow *num_threads* (None) : if set, specify the number of threads for the multi-threaded routines; otherwise the pynbody.config default is used *fill_nan* (True): if any of the image values are NaN, replace with fill_val *fill_val* (0.0): the fill value to use when replacing NaNs *linthresh* (None): if the image has negative and positive values and a log scaling is requested, the part between `-linthresh` and `linthresh` is shown on a linear scale to avoid divergence at 0 """ if not noplot: import matplotlib.pylab as plt global config if not noplot: if subplot: p = subplot else: p = plt if isinstance(units, str): units = _units.Unit(units) if isinstance(width, str) or issubclass(width.__class__, _units.UnitBase): if isinstance(width, str): width = _units.Unit(width) width = width.in_units(sim['pos'].units, **sim.conversion_context()) width = float(width) kernel = sph.Kernel() perspective = z_camera is not None if perspective and not av_z: kernel = sph.Kernel2D() if units is not None: try: sim[qty].units.ratio(units, **sim[qty].conversion_context()) # if this fails, perhaps we're requesting a projected image? except _units.UnitsException: # if the following fails, there's no interpretation this routine # can cope with sim[qty].units.ratio( units / (sim['x'].units), **sim[qty].conversion_context()) # if we get to this point, we want a projected image kernel = sph.Kernel2D() if av_z: if isinstance(kernel, sph.Kernel2D): raise _units.UnitsException( "Units already imply projected image; can't also average over line-of-sight!") else: kernel = sph.Kernel2D() if units is not None: aunits = units * sim['z'].units else: aunits = None if isinstance(av_z, str): if units is not None: aunits = units * sim[av_z].units * sim['z'].units sim["__prod"] = sim[av_z] * sim[qty] qty = "__prod" else: av_z = "__one" sim["__one"] = np.ones_like(sim[qty]) sim["__one"].units = "1" im = sph.render_image(sim, qty, width / 2, resolution, out_units=aunits, kernel=kernel, z_camera=z_camera, **kwargs) im2 = sph.render_image(sim, av_z, width / 2, resolution, kernel=kernel, z_camera=z_camera, **kwargs) top = sim.ancestor try: del top["__one"] except KeyError: pass try: del top["__prod"] except KeyError: pass im = im / im2 else: im = sph.render_image(sim, qty, width / 2, resolution, out_units=units, kernel=kernel, z_camera=z_camera, **kwargs) if fill_nan: im[np.isnan(im)] = fill_val if not noplot: # set the log or linear normalizations if log: try: im[np.where(im == 0)] = abs(im[np.where(abs(im != 0))]).min() except ValueError: raise ValueError, "Failed to make a sensible logarithmic image. This probably means there are no particles in the view." # check if there are negative values -- if so, use the symmetric # log normalization if (im < 0).any(): # need to set the linear regime around zero -- set to by # default start at 1/1000 of the log range if linthresh is None: linthresh = np.nanmax(abs(im)) / 1000. norm = matplotlib.colors.SymLogNorm( linthresh, vmin=vmin, vmax=vmax) else: norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax) else: norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) # # do the actual plotting # if clear and not subplot: p.clf() if ret_im: return p.imshow(im[::-1, :].view(np.ndarray), extent=(-width / 2, width / 2, -width / 2, width / 2), vmin=vmin, vmax=vmax, cmap=cmap, norm = norm) ims = p.imshow(im[::-1, :].view(np.ndarray), extent=(-width / 2, width / 2, -width / 2, width / 2), vmin=vmin, vmax=vmax, cmap=cmap, norm = norm) u_st = sim['pos'].units.latex() if not subplot: plt.xlabel("$x/%s$" % u_st) plt.ylabel("$y/%s$" % u_st) else: p.set_xlabel("$x/%s$" % u_st) p.set_ylabel("$y/%s$" % u_st) if units is None: units = im.units if log : units = r"$\log_{10}\,"+units.latex()+"$" else : if units.latex() is "": units="" else: units = "$"+units.latex()+"$" if show_cbar: if log: custom_formatter = FuncFormatter(fmt) ## l_f = LogFormatterExponent() # sometimes tacks 'e' on value...??? l_f = custom_formatter else: l_f = ScalarFormatter() if qtytitle is not None: plt.colorbar(ims,format=l_f).set_label(qtytitle) else: plt.colorbar(ims,format=l_f).set_label(units) # colorbar doesn't work wtih subplot: mappable is NoneType # elif show_cbar: # import matplotlib.pyplot as mpl # if qtytitle: mpl.colorbar().set_label(qtytitle) # else: mpl.colorbar().set_label(units) if title is not None: if not subplot: p.title(title) else: p.set_title(title) if filename is not None: p.savefig(filename) plt.draw() # plt.show() - removed by AP on 30/01/2013 - this should not be here as # for some systems you don't get back to the command prompt return im
def image(sim, qty='rho', width="10 kpc", resolution=500, units=None, log=True, vmin=None, vmax=None, av_z=False, filename=None, z_camera=None, clear=True, cmap=None, title=None, qtytitle=None, show_cbar=True, subplot=False, noplot=False, ret_im=False, fill_nan=True, fill_val=0.0, linthresh=None, **kwargs): """ Make an SPH image of the given simulation. **Keyword arguments:** *qty* (rho): The name of the array to interpolate *width* (10 kpc): The overall width and height of the plot. If ``width`` is a float or an int, then it is assumed to be in units of ``sim['pos']``. It can also be passed in as a string indicating the units, i.e. '10 kpc', in which case it is converted to units of ``sim['pos']``. *resolution* (500): The number of pixels wide and tall *units* (None): The units of the output *av_z* (False): If True, the requested quantity is averaged down the line of sight (default False: image is generated in the thin plane z=0, unless output units imply an integral down the line of sight). If a string, the requested quantity is averaged down the line of sight weighted by the av_z array (e.g. use 'rho' for density-weighted quantity; the default results when av_z=True are volume-weighted). *z_camera* (None): If set, a perspective image is rendered. See :func:`pynbody.sph.image` for more details. *filename* (None): if set, the image will be saved in a file *clear* (True): whether to call clf() on the axes first *cmap* (None): user-supplied colormap instance *title* (None): plot title *qtytitle* (None): colorbar quantity title *show_cbar* (True): whether to plot the colorbar *subplot* (False): the user can supply a AxesSubPlot instance on which the image will be shown *noplot* (False): do not display the image, just return the image array *ret_im* (False): return the image instance returned by imshow *num_threads* (None) : if set, specify the number of threads for the multi-threaded routines; otherwise the pynbody.config default is used *fill_nan* (True): if any of the image values are NaN, replace with fill_val *fill_val* (0.0): the fill value to use when replacing NaNs *linthresh* (None): if the image has negative and positive values and a log scaling is requested, the part between `-linthresh` and `linthresh` is shown on a linear scale to avoid divergence at 0 """ if not noplot: import matplotlib.pylab as plt global config if not noplot: if subplot: p = subplot else: p = plt if isinstance(units, str): units = _units.Unit(units) if isinstance(width, str) or issubclass(width.__class__, _units.UnitBase): if isinstance(width, str): width = _units.Unit(width) width = width.in_units(sim['pos'].units, **sim.conversion_context()) width = float(width) kernel = sph.Kernel() perspective = z_camera is not None if perspective and not av_z: kernel = sph.Kernel2D() if units is not None: try: sim[qty].units.ratio(units, **sim[qty].conversion_context()) # if this fails, perhaps we're requesting a projected image? except _units.UnitsException: # if the following fails, there's no interpretation this routine # can cope with sim[qty].units.ratio(units / (sim['x'].units), **sim[qty].conversion_context()) # if we get to this point, we want a projected image kernel = sph.Kernel2D() if av_z: if isinstance(kernel, sph.Kernel2D): raise _units.UnitsException( "Units already imply projected image; can't also average over line-of-sight!" ) else: kernel = sph.Kernel2D() if units is not None: aunits = units * sim['z'].units else: aunits = None if isinstance(av_z, str): if units is not None: aunits = units * sim[av_z].units * sim['z'].units sim["__prod"] = sim[av_z] * sim[qty] qty = "__prod" else: av_z = "__one" sim["__one"] = np.ones_like(sim[qty]) sim["__one"].units = "1" im = sph.render_image(sim, qty, width / 2, resolution, out_units=aunits, kernel=kernel, z_camera=z_camera, **kwargs) im2 = sph.render_image(sim, av_z, width / 2, resolution, kernel=kernel, z_camera=z_camera, **kwargs) top = sim.ancestor try: del top["__one"] except KeyError: pass try: del top["__prod"] except KeyError: pass im = im / im2 else: im = sph.render_image(sim, qty, width / 2, resolution, out_units=units, kernel=kernel, z_camera=z_camera, **kwargs) if fill_nan: im[np.isnan(im)] = fill_val if not noplot: # set the log or linear normalizations if log: try: im[np.where(im == 0)] = abs(im[np.where(abs(im != 0))]).min() except ValueError: raise ValueError, "Failed to make a sensible logarithmic image. This probably means there are no particles in the view." # check if there are negative values -- if so, use the symmetric # log normalization if (im < 0).any(): # need to set the linear regime around zero -- set to by # default start at 1/1000 of the log range if linthresh is None: linthresh = np.nanmax(abs(im)) / 1000. norm = matplotlib.colors.SymLogNorm(linthresh, vmin=vmin, vmax=vmax) else: norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax) else: norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) # # do the actual plotting # if clear and not subplot: p.clf() if ret_im: return p.imshow(im[::-1, :].view(np.ndarray), extent=(-width / 2, width / 2, -width / 2, width / 2), vmin=vmin, vmax=vmax, cmap=cmap, norm=norm) ims = p.imshow(im[::-1, :].view(np.ndarray), extent=(-width / 2, width / 2, -width / 2, width / 2), vmin=vmin, vmax=vmax, cmap=cmap, norm=norm) u_st = sim['pos'].units.latex() if not subplot: plt.xlabel("$x/%s$" % u_st) plt.ylabel("$y/%s$" % u_st) else: p.set_xlabel("$x/%s$" % u_st) p.set_ylabel("$y/%s$" % u_st) if units is None: units = im.units if log: units = r"$\log_{10}\," + units.latex() + "$" else: if units.latex() is "": units = "" else: units = "$" + units.latex() + "$" if show_cbar: if qtytitle is not None: plt.colorbar(ims).set_label(qtytitle) else: plt.colorbar(ims).set_label(units) # colorbar doesn't work wtih subplot: mappable is NoneType # elif show_cbar: # import matplotlib.pyplot as mpl # if qtytitle: mpl.colorbar().set_label(qtytitle) # else: mpl.colorbar().set_label(units) if title is not None: if not subplot: p.title(title) else: p.set_title(title) if filename is not None: p.savefig(filename) plt.draw() # plt.show() - removed by AP on 30/01/2013 - this should not be here as # for some systems you don't get back to the command prompt return im
def make_contour_plot(arr, xs, ys, x_range=None, y_range=None, nlevels=20, logscale=True, xlogrange=False, ylogrange=False, subplot=False, colorbar=False, ret_im=False, cmap=None, clear=True, legend=False, scalemin=None,levels=None, scalemax=None, filename=None, **kwargs): """ Plot a contour plot of grid *arr* corresponding to bin centers specified by *xs* and *ys*. Labels the axes and colobar with proper units taken from x Called by :func:`~pynbody.plot.generic.hist2d` and :func:`~pynbody.plot.generic.gauss_density`. **Input**: *arr*: 2D array to plot *xs*: x-coordinates of bins *ys*: y-coordinates of bins **Optional Keywords**: *x_range*: list, array, or tuple (default = None) size(x_range) must be 2. Specifies the X range. *y_range*: tuple (default = None) size(y_range) must be 2. Specifies the Y range. *xlogrange*: boolean (default = False) whether the x-axis should have a log scale *ylogrange*: boolean (default = False) whether the y-axis should have a log scale *nlevels*: int (default = 20) number of levels to use for the contours *logscale*: boolean (default = True) whether to use log or linear spaced contours *colorbar*: boolean (default = False) draw a colorbar *scalemin*: float (default = arr.min()) minimum value to use for the color scale *scalemax*: float (default = arr.max()) maximum value to use for the color scale """ from matplotlib import ticker, colors if not subplot: import matplotlib.pyplot as plt else: plt = subplot if scalemin is None: scalemin = np.min(arr[arr > 0]) if scalemax is None: scalemax = np.max(arr[arr > 0]) arr[arr < scalemin] = scalemin arr[arr > scalemax] = scalemax if 'norm' in kwargs: del(kwargs['norm']) if logscale: try: levels = np.logspace(np.log10(scalemin), np.log10(scalemax), nlevels) cont_color = colors.LogNorm() except ValueError: raise ValueError( 'crazy contour levels -- try specifying the *levels* keyword or use a linear scale') return if arr.units != NoUnit() and arr.units != 1: cb_label = '$log_{10}(' + arr.units.latex() + ')$' else: cb_label = '$log_{10}(N)$' else: levels = np.linspace(scalemin, scalemax, nlevels) cont_color = None if arr.units != NoUnit() and arr.units != 1: cb_label = '$' + arr.units.latex() + '$' else: cb_label = '$N$' if not subplot and clear: plt.clf() if ret_im: if logscale: arr = np.log10(arr) scalemin, scalemax = np.log10((scalemin, scalemax)) return plt.imshow(arr, origin='down', vmin=scalemin, vmax=scalemax, aspect='auto', cmap=cmap, axes=subplot, # aspect = # np.diff(x_range)/np.diff(y_range),cmap=cmap, extent=[x_range[0], x_range[1], y_range[0], y_range[1]]) cs = plt.contourf( xs, ys, arr, levels, norm=cont_color, cmap=cmap, **kwargs) if 'xlabel' in kwargs: xlabel = kwargs['xlabel'] else: try: if xlogrange: xlabel = r'' + '$log_{10}(' + xs.units.latex() + ')$' else: xlabel = r'' + '$x/' + xs.units.latex() + '$' except AttributeError: xlabel = None if xlabel: try: if subplot: plt.set_xlabel(xlabel) else: plt.xlabel(xlabel) except: pass if 'ylabel' in kwargs: ylabel = kwargs['ylabel'] else: try: if ylogrange: ylabel = '$log_{10}(' + ys.units.latex() + ')$' else: ylabel = r'' + '$y/' + ys.units.latex() + '$' except AttributeError: ylabel = None if ylabel: try: if subplot: plt.set_ylabel(ylabel) else: plt.ylabel(ylabel) except: pass # if not subplot: # plt.xlim((x_range[0],x_range[1])) # plt.ylim((y_range[0],y_range[1])) if colorbar: cb = plt.colorbar(cs, format="%.2e").set_label(r'' + cb_label) if legend: plt.legend(loc=2) if (filename): if config['verbose']: print("Saving " + filename) plt.savefig(filename)
def image(sim, qty='rho', width=10, resolution=500, units=None, log=True, vmin=None, vmax=None, av_z = False, filename=None, z_camera=None, clear = True, cmap=None, center=False, title=None, qtytitle=None, show_cbar=True, subplot=False, noplot = False, ret_im=False, fill_nan = True, fill_val=0.0, **kwargs) : """ Make an SPH image of the given simulation. **Keyword arguments:** *qty* (rho): The name of the array to interpolate *width* (10): The overall width and height of the plot in sim['pos'] units *resolution* (500): The number of pixels wide and tall *units* (None): The units of the output *av_z* (False): If True, the requested quantity is averaged down the line of sight (default False: image is generated in the thin plane z=0, unless output units imply an integral down the line of sight). If a string, the requested quantity is averaged down the line of sight weighted by the av_z array (e.g. use 'rho' for density-weighted quantity; the default results when av_z=True are volume-weighted). *z_camera* (None): If set, a perspective image is rendered. See :func:`pynbody.sph.image` for more details. *filename* (None): if set, the image will be saved in a file *clear* (True): whether to call clf() on the axes first *cmap* (None): user-supplied colormap instance *title* (None): plot title *qtytitle* (None): colorbar quantity title *show_cbar* (True): whether to plot the colorbar *subplot* (False): the user can supply a AxesSubPlot instance on which the image will be shown *noplot* (False): do not display the image, just return the image array *ret_im* (False): return the image instance returned by imshow *num_threads* (None) : if set, specify the number of threads for the multi-threaded routines; otherwise the pynbody.config default is used *fill_nan* (True): if any of the image values are NaN, replace with fill_val *fill_val* (0.0): the fill value to use when replacing NaNs """ import matplotlib.pylab as plt global config if subplot: p = subplot else : p = plt if isinstance(units, str) : units = _units.Unit(units) width = float(width) kernel = sph.Kernel() perspective = z_camera is not None if perspective and not av_z: kernel = sph.Kernel2D() if units is not None : try : sim[qty].units.ratio(units, **sim[qty].conversion_context()) # if this fails, perhaps we're requesting a projected image? except _units.UnitsException : # if the following fails, there's no interpretation this routine can cope with sim[qty].units.ratio(units/(sim['x'].units), **sim[qty].conversion_context()) kernel = sph.Kernel2D() # if we get to this point, we want a projected image if av_z : if isinstance(kernel, sph.Kernel2D) : raise _units.UnitsException("Units already imply projected image; can't also average over line-of-sight!") else : kernel = sph.Kernel2D() if units is not None : aunits = units*sim['z'].units else : aunits = None if isinstance(av_z, str) : if units is not None: aunits = units*sim[av_z].units*sim['z'].units sim["__prod"] = sim[av_z]*sim[qty] qty = "__prod" else : av_z = "__one" sim["__one"]=np.ones_like(sim[qty]) sim["__one"].units="1" im = sph.render_image(sim,qty,width/2,resolution,out_units=aunits, kernel = kernel, z_camera=z_camera, **kwargs) im2 = sph.render_image(sim, av_z, width/2, resolution, kernel=kernel, z_camera=z_camera, **kwargs) top = sim.ancestor try: del top["__one"] except KeyError : pass try: del top["__prod"] except KeyError : pass im = im/im2 else : im = sph.render_image(sim,qty,width/2,resolution,out_units=units, kernel = kernel, z_camera = z_camera, **kwargs) if fill_nan : im[np.isnan(im)] = fill_val if log : im[np.where(im==0)] = abs(im[np.where(im!=0)]).min() im = np.log10(im) if clear and not subplot : p.clf() if ret_im: return plt.imshow(im[::-1,:],extent=(-width/2,width/2,-width/2,width/2), vmin=vmin, vmax=vmax, cmap=cmap) ims = p.imshow(im[::-1,:],extent=(-width/2,width/2,-width/2,width/2), vmin=vmin, vmax=vmax, cmap=cmap) u_st = sim['pos'].units.latex() if not subplot: plt.xlabel("$x/%s$"%u_st) plt.ylabel("$y/%s$"%u_st) else : p.set_xlabel("$x/%s$"%u_st) p.set_ylabel("$y/%s$"%u_st) if units is None : units = im.units if log : units = r"$\log_{10}\,"+units.latex()+"$" else : units = "$"+units.latex()+"$" if show_cbar: if qtytitle is not None: plt.colorbar(ims).set_label(qtytitle) else: plt.colorbar(ims).set_label(units) # colorbar doesn't work wtih subplot: mappable is NoneType #elif show_cbar: # import matplotlib.pyplot as mpl # if qtytitle: mpl.colorbar().set_label(qtytitle) # else: mpl.colorbar().set_label(units) if title is not None: p.set_title(title) if filename is not None: p.savefig(filename) plt.draw() plt.show() return im
# TODO: Check if the indices and the reverse_meanList really express what you # think they do. You might be looking at wrong sections ################################################################################ # Plotting # Just getting an idea what the data looks like voxel_activation = mv[1] timesteps = range(len(mv[1])) pl.scatter(timesteps, voxel_activation) pl.savefig("singlevoxelscatter.png",dpi=100) pl.show() pl.plot(mv[2]) pl.set_xlabel('xlabel') pl.set_ylabel('ylabel') pl.savefig("singlevoxel.png",dpi=100) pl.show() for voxel in mv[:2]: #mv[:3] pl.plot(voxel, ) pl.savefig("voxelsovertime.png",dpi=100) pl.show() # Let's try some algorithms from scikitlearn toolbox # K-means clustering #colors = ['#B77151', '#B75851', '#B75163', '#B7517C', '#B75196'] #print k_means.labels_ #print rev[:100]
def make_contour_plot(arr, xs, ys, x_range=None, y_range=None, nlevels=20, logscale=True, xlogrange=False, ylogrange=False, subplot=False, colorbar=False, ret_im=False, cmap=None, clear=True, legend=False, scalemin=None,levels=None, scalemax=None, filename=None, **kwargs): """ Plot a contour plot of grid *arr* corresponding to bin centers specified by *xs* and *ys*. Labels the axes and colobar with proper units taken from x Called by :func:`~pynbody.plot.generic.hist2d` and :func:`~pynbody.plot.generic.gauss_density`. **Input**: *arr*: 2D array to plot *xs*: x-coordinates of bins *ys*: y-coordinates of bins **Optional Keywords**: *x_range*: list, array, or tuple (default = None) size(x_range) must be 2. Specifies the X range. *y_range*: tuple (default = None) size(y_range) must be 2. Specifies the Y range. *xlogrange*: boolean (default = False) whether the x-axis should have a log scale *ylogrange*: boolean (default = False) whether the y-axis should have a log scale *nlevels*: int (default = 20) number of levels to use for the contours *logscale*: boolean (default = True) whether to use log or linear spaced contours *colorbar*: boolean (default = False) draw a colorbar *scalemin*: float (default = arr.min()) minimum value to use for the color scale *scalemax*: float (default = arr.max()) maximum value to use for the color scale """ from matplotlib import ticker, colors if not subplot: import matplotlib.pyplot as plt else: plt = subplot if scalemin is None: scalemin = np.min(arr[arr > 0]) if scalemax is None: scalemax = np.max(arr[arr > 0]) arr[arr < scalemin] = scalemin arr[arr > scalemax] = scalemax if 'norm' in kwargs: del(kwargs['norm']) if logscale: try: levels = np.logspace(np.log10(scalemin), np.log10(scalemax), nlevels) cont_color = colors.LogNorm() except ValueError: raise ValueError( 'crazy contour levels -- try specifying the *levels* keyword or use a linear scale') return if arr.units != NoUnit() and arr.units != 1: cb_label = '$log_{10}(' + arr.units.latex() + ')$' else: cb_label = '$log_{10}(N)$' else: levels = np.linspace(scalemin, scalemax, nlevels) cont_color = None if arr.units != NoUnit() and arr.units != 1: cb_label = '$' + arr.units.latex() + '$' else: cb_label = '$N$' if not subplot and clear: plt.clf() if ret_im: if logscale: arr = np.log10(arr) scalemin, scalemax = np.log10((scalemin, scalemax)) return plt.imshow(arr, origin='down', vmin=scalemin, vmax=scalemax, aspect='auto', cmap=cmap, axes=subplot, # aspect = # np.diff(x_range)/np.diff(y_range),cmap=cmap, extent=[x_range[0], x_range[1], y_range[0], y_range[1]]) cs = plt.contourf( xs, ys, arr, levels, norm=cont_color, cmap=cmap, **kwargs) if kwargs.has_key('xlabel'): xlabel = kwargs['xlabel'] else: try: if xlogrange: xlabel = r'' + '$log_{10}(' + xs.units.latex() + ')$' else: xlabel = r'' + '$x/' + xs.units.latex() + '$' except AttributeError: xlabel = None if xlabel: try: if subplot: plt.set_xlabel(xlabel) else: plt.xlabel(xlabel) except: pass if kwargs.has_key('ylabel'): ylabel = kwargs['ylabel'] else: try: if ylogrange: ylabel = '$log_{10}(' + ys.units.latex() + ')$' else: ylabel = r'' + '$y/' + ys.units.latex() + '$' except AttributeError: ylabel = None if ylabel: try: if subplot: plt.set_ylabel(ylabel) else: plt.ylabel(ylabel) except: pass # if not subplot: # plt.xlim((x_range[0],x_range[1])) # plt.ylim((y_range[0],y_range[1])) if colorbar: cb = plt.colorbar(cs, format="%.2e").set_label(r'' + cb_label) if legend: plt.legend(loc=2) if (filename): if config['verbose']: print "Saving " + filename plt.savefig(filename)