def __init__(self, *args, **kwargs): # pull non-standard keyword arguments refresh = kwargs.pop('auto_refresh', False) # dynamically set the subplot positions based on the figure size # -- only if the user hasn't customised the subplot params figsize = kwargs.get('figsize', rcParams['figure.figsize']) subplotpars = get_subplot_params(figsize) use_subplotpars = 'subplotpars' not in kwargs and all([ rcParams['figure.subplot.%s' % pos] == MPL_RCPARAMS['figure.subplot.%s' % pos] for pos in ('left', 'bottom', 'right', 'top')]) if use_subplotpars: kwargs['subplotpars'] = subplotpars # generated figure, with associated interactivity from pyplot super(Plot, self).__init__(*args, **kwargs) backend_mod, _, draw_if_interactive, _ = backends.pylab_setup() try: manager = backend_mod.new_figure_manager_given_figure(1, self) except AttributeError: canvas = backend_mod.FigureCanvas(self) manager = FigureManagerBase(canvas, 1) cid = manager.canvas.mpl_connect( 'button_press_event', lambda ev: _pylab_helpers.Gcf.set_active(manager)) manager._cidgcf = cid _pylab_helpers.Gcf.set_active(manager) draw_if_interactive() # finalise self.set_auto_refresh(refresh) self.colorbars = [] self._coloraxes = []
def __init__(self, *args, **kwargs): # pull non-standard keyword arguments auto_refresh = kwargs.pop('auto_refresh', False) # dynamically set the subplot positions based on the figure size # -- only if the user hasn't customised the subplot params figsize = kwargs.get('figsize', rcParams['figure.figsize']) subplotpars = get_subplot_params(figsize) use_subplotpars = 'subplotpars' not in kwargs and all([ rcParams['figure.subplot.%s' % pos] == MPL_RCPARAMS['figure.subplot.%s' % pos] for pos in ('left', 'bottom', 'right', 'top') ]) if use_subplotpars: kwargs['subplotpars'] = subplotpars # generated figure, with associated interactivity from pyplot super(Plot, self).__init__(*args, **kwargs) backend_mod, _, draw_if_interactive, _ = backends.pylab_setup() try: manager = backend_mod.new_figure_manager_given_figure(1, self) except AttributeError: canvas = backend_mod.FigureCanvas(self) manager = FigureManagerBase(canvas, 1) cid = manager.canvas.mpl_connect( 'button_press_event', lambda ev: _pylab_helpers.Gcf.set_active(manager)) manager._cidgcf = cid _pylab_helpers.Gcf.set_active(manager) draw_if_interactive() # finalise self.set_auto_refresh(auto_refresh) self.colorbars = [] self._coloraxes = []
def render(self, fig): if self._render_fig_manager is None: # Chooses the backend_mod based on matplotlib configuration mplib.interactive(True) self._render_backend_mod = pylab_setup()[0] self._render_fig_manager = \ self._render_backend_mod.new_figure_manager_given_figure(1, fig) self._render_fig_manager.canvas.figure = fig self._render_fig_manager.canvas.draw() self._render_backend_mod.show(block=False) return self._render_fig_manager
def __init__(self, *args, **kwargs): # pull non-standard keyword arguments auto_refresh = kwargs.pop('auto_refresh', False) # generated figure, with associated interactivity from pyplot super(Plot, self).__init__(*args, **kwargs) backend_mod, _, draw_if_interactive, _ = backends.pylab_setup() manager = backend_mod.new_figure_manager_given_figure(1, self) cid = manager.canvas.mpl_connect( 'button_press_event', lambda ev: _pylab_helpers.Gcf.set_active(manager)) manager._cidgcf = cid _pylab_helpers.Gcf.set_active(manager) draw_if_interactive() # finalise self.set_auto_refresh(auto_refresh) self.colorbars = [] self._coloraxes = []
def mollview(m, rot=None, coord=None, unit='', xsize=1000, nest=False, min=None, max=None, flip='astro', format='%g', cbar=True, cmap=None, norm=None, graticule=False, graticule_labels=False, **kwargs): """Plot an healpix map (given as an array) in Mollweide projection. Parameters ---------- map : float, array-like or None An array containing the map, supports masked maps, see the `ma` function. If None, will display a blank map, useful for overplotting. rot : scalar or sequence, optional Describe the rotation to apply. In the form (lon, lat, psi) (unit: degrees) : the point at longitude *lon* and latitude *lat* will be at the center. An additional rotation of angle *psi* around this direction is applied. coord : sequence of character, optional Either one of 'G', 'E' or 'C' to describe the coordinate system of the map, or a sequence of 2 of these to rotate the map from the first to the second coordinate system. unit : str, optional A text describing the unit of the data. Default: '' xsize : int, optional The size of the image. Default: 800 nest : bool, optional If True, ordering scheme is NESTED. Default: False (RING) min : float, optional The minimum range value max : float, optional The maximum range value flip : {'astro', 'geo'}, optional Defines the convention of projection : 'astro' (default, east towards left, west towards right) or 'geo' (east towards roght, west towards left) format : str, optional The format of the scale label. Default: '%g' cbar : bool, optional Display the colorbar. Default: True norm : {'hist', 'log', None} Color normalization, hist= histogram equalized color mapping, log= logarithmic color mapping, default: None (linear color mapping) kwargs : keywords any additional keyword is passed to pcolormesh graticule : bool add graticule graticule_labels : bool longitude and latitude labels """ # not implemented features if not (norm is None): raise exceptions.NotImplementedError() # Create the figure import matplotlib.pyplot as plt from matplotlib.backends import pylab_setup _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() width = 8.5 fig = plt.figure(figsize=(width,width*.63)) ax = fig.add_subplot(111, projection="mollweide") # FIXME: make a more general axes creation that works also with subplots #ax = plt.gcf().add_axes((.125, .1, .9, .9), projection="mollweide") # remove white space around the image plt.subplots_adjust(left=0.02, right=0.98, top=0.95, bottom=0.05) if graticule and graticule_labels: plt.subplots_adjust(left=0.04, right=0.98, top=0.95, bottom=0.05) # auto min and max if min is None: min = m.min() if max is None: max = m.max() # allow callers to override the hold state by passing hold=True|False washold = ax.ishold() hold = kwargs.pop('hold', None) if hold is not None: ax.hold(hold) try: ysize = xsize/2 theta = np.linspace(np.pi, 0, ysize) phi = np.linspace(-np.pi, np.pi, xsize) longitude = np.radians(np.linspace(-180, 180, xsize)) if flip == "astro": longitude = longitude[::-1] latitude = np.radians(np.linspace(-90, 90, ysize)) # project the map to a rectangular matrix xsize x ysize PHI, THETA = np.meshgrid(phi, theta) # coord or rotation if coord or rot: r = Rotator(coord=coord, rot=rot, inv=True) THETA, PHI = r(THETA.flatten(), PHI.flatten()) THETA = THETA.reshape(ysize, xsize) PHI = PHI.reshape(ysize, xsize) nside = npix2nside(len(m)) grid_pix = ang2pix(nside, THETA, PHI, nest=nest) grid_map = m[grid_pix] # plot ret = plt.pcolormesh(longitude, latitude, grid_map, vmin=min, vmax=max, rasterized=True, **kwargs) # graticule plt.grid(graticule) if graticule: longitude_grid_spacing = 60 # deg ax.set_longitude_grid(longitude_grid_spacing) if width < 10: ax.set_latitude_grid(45) ax.set_longitude_grid_ends(90) if graticule_labels: ax.xaxis.set_major_formatter(ThetaFormatterShiftPi(longitude_grid_spacing)) else: # remove longitude and latitude labels ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) # colorbar if cbar: cb = fig.colorbar(ret, orientation='horizontal', shrink=.4, pad=0.05, ticks=[min, max]) cb.ax.xaxis.set_label_text(unit) cb.ax.xaxis.labelpad = -8 # workaround for issue with viewers, see colorbar docstring cb.solids.set_edgecolor("face") draw_if_interactive() finally: ax.hold(washold) return ret
def main(): parser = ArgumentParser( formatter_class=type( "", (ArgumentDefaultsHelpFormatter, RawTextHelpFormatter), {}), epilog="""\ Example usage: $ python %(prog)s plot \\ '{{"backend": "agg"}}' \\ '{{"backend": "agg", "agg.path.chunksize": 1000}}' \\ '{{"backend": "module://mplcairo.base", \\ "lines.antialiased": __import__("mplcairo").antialias_t.FAST}}' \\ '{{"backend": "module://mplcairo.base", \\ "lines.antialiased": __import__("mplcairo").antialias_t.BEST}}' """.format(sys.argv[0])) parser.add_argument( "-n", "--n-elements", type=lambda s: [int(n) for n in s.split(",")], default=[10, 30, 100, 300, 1000, 3000, 10000], help="comma-separated list of number of elements") parser.add_argument( "method", choices=["plot", "fill", "scatter"], help="Axes method") parser.add_argument( "rcs", type=eval, nargs="+", metavar="rc", help="rc parameters to test (will be eval'd)") args = parser.parse_args() n_elems = args.n_elements method = args.method rcs = args.rcs results = [] for rc in rcs: # Emulate rc_context, but without the validation (to support mplcairo's # antialiasing enum). try: orig_rc = dict.copy(plt.rcParams) dict.update(plt.rcParams, rc) fig, ax = plt.subplots() backend_mod, *_ = backends.pylab_setup(plt.rcParams["backend"]) ax.figure.canvas = backend_mod.FigureCanvas(ax.figure) results.append(get_times(ax, method, n_elems)) plt.close(fig) finally: dict.update(plt.rcParams, orig_rc) _, main_ax = plt.subplots() main_ax.set(xlabel="number of elements", ylabel="time per edge (s)", xscale="log", yscale="log") for i, (rc, all_times) in enumerate(zip(rcs, results)): normalized = [ np.array(times) / n for n, times in zip(n_elems, all_times)] for norm in normalized: norm.sort() # Use the minimum time as aggregate: the cdfs show that the # distributions are very long tailed. main_ax.plot(n_elems, [norm[0] for norm in normalized], "o", label=pprint.pformat(rc)) fig, detail_ax = plt.subplots() fig.suptitle(pprint.pformat(rc)) for n, norm in zip(n_elems, normalized): detail_ax.plot(norm, np.linspace(0, 1, len(norm))[::-1], drawstyle="steps-pre", label="{} elements (N={})".format(n, len(norm))) detail_ax.set(xlabel="time per element (s)", xscale="log", ylabel="CCDF") detail_ax.legend(loc="upper right") main_ax.legend(loc="upper center") plt.show()
""" plot_radar.py Class instance used to make Display. """ # Load the needed packages import numpy as np import scipy import os import pyart from matplotlib.backends import pylab_setup backend = pylab_setup()[0] FigureCanvasQTAgg = backend.FigureCanvasQTAgg NavigationToolbar = backend.NavigationToolbar2QT #from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg #from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as \ # NavigationToolbar from matplotlib.figure import Figure from matplotlib.colors import Normalize as mlabNormalize from matplotlib.colorbar import ColorbarBase as mlabColorbarBase from matplotlib.pyplot import cm from ..core import (Variable, Component, common, VariableChoose, QtCore, QtGui, QtWidgets) from ..core.points import Points # Save image file type and DPI (resolution) IMAGE_EXT = 'png' DPI = 200 # ========================================================================
#!/usr/bin/env python import numpy as np import matplotlib.axes import matplotlib.patches from matplotlib.quiver import Quiver as _Quiver from matplotlib.collections import EllipseCollection from matplotlib.backends import pylab_setup from matplotlib.pyplot import sci from matplotlib.pyplot import gca import warnings _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() def compute_abphi(sigma_x, sigma_y, rho): n = len(sigma_x) a = [] b = [] phi = [] for i in range(n): if np.ma.is_masked(sigma_x[i]) | np.ma.is_masked(sigma_y[i]) | np.ma.is_masked(rho[i]): a += [0.0] b += [0.0] phi += [0.0] continue sigma_xy = rho[i] * sigma_x[i] * sigma_y[i] cov_mat = np.array([[sigma_x[i] ** 2, sigma_xy], [sigma_xy, sigma_y[i] ** 2]]) val, vec = np.linalg.eig(cov_mat) maxidx = np.argmax(val) minidx = np.argmin(val)
#!/usr/bin/env python import numpy as np import matplotlib.axes import matplotlib.patches from matplotlib.quiver import Quiver as _Quiver from matplotlib.collections import EllipseCollection from matplotlib.backends import pylab_setup from matplotlib.pyplot import sci from matplotlib.pyplot import gca _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() def compute_abphi(sigma_x,sigma_y,rho): n = len(sigma_x) a = [] b = [] phi = [] for i in range(n): if (np.ma.is_masked(sigma_x[i]) | np.ma.is_masked(sigma_y[i]) | np.ma.is_masked(rho[i])): a += [0.0] b += [0.0] phi += [0.0] continue sigma_xy = rho[i]*sigma_x[i]*sigma_y[i] cov_mat = np.array([[sigma_x[i]**2,sigma_xy], [sigma_xy,sigma_y[i]**2]]) val,vec = np.linalg.eig(cov_mat) maxidx = np.argmax(val)
import numpy # from numpy import isscalar, iterable from matplotlib.transforms import Bbox from matplotlib.backends import pylab_setup new_figure_manager, draw_if_interactive, show = pylab_setup() from matplotlib.pyplot import figure import re import xml.dom.minidom from xml.sax.handler import ContentHandler from xml.sax import make_parser def get_type(typestr): pass class XMLFigure(ContentHandler): """ The XML parser. Creates an expat parser, and then handles the defined tags specified in 'start_tags' and 'end_tags'. Currently the allowed tags are: figure, subplot, plot """ def create_parser(self): parser = make_parser()
""" cmap_value.py """ # Load the needed packages import numpy as np from ..core import QtWidgets, QtGui, QtCore import matplotlib.pyplot as plt from matplotlib.figure import Figure from matplotlib.backends import pylab_setup FigureCanvasQTAgg = pylab_setup()[0].FigureCanvasQTAgg #from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg from matplotlib import colors import pyart from .. import core, components gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) class ColormapEdit(core.Component): @classmethod def guiStart(self, parent=None): kwargs, independent = core.common._SimplePluginStart( "ColormapEdit").startDisplay() kwargs['parent'] = parent return self(**kwargs), independent
""" cmap_value.py """ # Load the needed packages import numpy as np from ..core import QtWidgets, QtGui, QtCore import matplotlib.pyplot as plt from matplotlib.figure import Figure from matplotlib.backends import pylab_setup FigureCanvasQTAgg = pylab_setup()[0].FigureCanvasQTAgg #from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg from matplotlib import colors import pyart from .. import core gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) class ColormapEdit(core.Component): @classmethod def guiStart(self, parent=None): kwargs, independent = core.common._SimplePluginStart( "ColormapEdit").startDisplay() kwargs['parent'] = parent return self(**kwargs), independent
import numpy #from numpy import isscalar, iterable from matplotlib.transforms import Bbox from matplotlib.backends import pylab_setup new_figure_manager, draw_if_interactive, show = pylab_setup() from matplotlib.pyplot import figure import re import xml.dom.minidom from xml.sax.handler import ContentHandler from xml.sax import make_parser def get_type(typestr): pass class XMLFigure(ContentHandler): """ The XML parser. Creates an expat parser, and then handles the defined tags specified in 'start_tags' and 'end_tags'. Currently the allowed tags are: figure, subplot, plot """ def create_parser(self): parser = make_parser() parser.setContentHandler(self) return parser