Python matplotlib 模块,__version__() 实例源码

我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用matplotlib.__version__()

项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _plot(cls, ax, y, style=None, bw_method=None, ind=None,
              column_num=None, stacking_id=None, **kwds):
        from scipy.stats import gaussian_kde
        from scipy import __version__ as spv

        y = remove_na(y)

        if LooseVersion(spv) >= '0.11.0':
            gkde = gaussian_kde(y, bw_method=bw_method)
        else:
            gkde = gaussian_kde(y)
            if bw_method is not None:
                msg = ('bw_method was added in Scipy 0.11.0.' +
                       ' Scipy version in use is %s.' % spv)
                warnings.warn(msg)

        y = gkde.evaluate(ind)
        lines = MPLPlot._plot(ax, ind, y, style=style, **kwds)
        return lines
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
def get_pandas_status():
    try:
        import pandas as pd
        return _check_version(pd.__version__, pandas_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
def get_sklearn_status():
    try:
        import sklearn as sk
        return _check_version(sk.__version__, sklearn_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
def get_numpy_status():
    try:
        import numpy as np
        return _check_version(np.__version__, numpy_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
def get_scipy_status():
    try:
        import scipy as sc
        return _check_version(sc.__version__, scipy_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status
项目:skutil    作者:tgsmith61591    | 项目源码 | 文件源码
def get_h2o_status():
    try:
        import h2o
        return _check_version(h2o.__version__, h2o_min_version)
    except ImportError:
        traceback.print_exc()
        return default_status
项目:psyplot    作者:Chilipp    | 项目源码 | 文件源码
def inspect_axes(ax):
        """Inspect an axes or subplot to get the initialization parameters"""
        ret = {'fig': ax.get_figure().number}
        if mpl.__version__ < '2.0':
            ret['axisbg'] = ax.get_axis_bgcolor()
        else:  # axisbg is depreceated
            ret['facecolor'] = ax.get_facecolor()
        proj = getattr(ax, 'projection', None)
        if proj is not None and not isinstance(proj, six.string_types):
            proj = (proj.__class__.__module__, proj.__class__.__name__)
        ret['projection'] = proj
        ret['visible'] = ax.get_visible()
        ret['spines'] = {}
        ret['zorder'] = ax.get_zorder()
        ret['yaxis_inverted'] = ax.yaxis_inverted()
        ret['xaxis_inverted'] = ax.xaxis_inverted()
        for key, val in ax.spines.items():
            ret['spines'][key] = {}
            for prop in ['linestyle', 'edgecolor', 'linewidth',
                         'facecolor', 'visible']:
                ret['spines'][key][prop] = getattr(val, 'get_' + prop)()
        if isinstance(ax, mfig.SubplotBase):
            sp = ax.get_subplotspec().get_topmost_subplotspec()
            ret['grid_spec'] = sp.get_geometry()[:2]
            ret['subplotspec'] = [sp.num1, sp.num2]
            ret['is_subplot'] = True
        else:
            ret['args'] = [ax.get_position(True).bounds]
            ret['is_subplot'] = False
        return ret
项目:psyplot    作者:Chilipp    | 项目源码 | 文件源码
def load_axes(d):
        """Create an axes or subplot from what is returned by
        :meth:`inspect_axes`"""
        import matplotlib.pyplot as plt
        fig = plt.figure(d.pop('fig', None))
        proj = d.pop('projection', None)
        spines = d.pop('spines', None)
        invert_yaxis = d.pop('yaxis_inverted', None)
        invert_xaxis = d.pop('xaxis_inverted', None)
        if mpl.__version__ >= '2.0' and 'axisbg' in d:  # axisbg is depreceated
            d['facecolor'] = d.pop('axisbg')
        elif mpl.__version__ < '2.0' and 'facecolor' in d:
            d['axisbg'] = d.pop('facecolor')
        if proj is not None and not isinstance(proj, six.string_types):
            proj = getattr(import_module(proj[0]), proj[1])()
        if d.pop('is_subplot', None):
            grid_spec = mpl.gridspec.GridSpec(*d.pop('grid_spec', (1, 1)))
            subplotspec = mpl.gridspec.SubplotSpec(
                grid_spec, *d.pop('subplotspec', (1, None)))
            return fig.add_subplot(subplotspec, projection=proj, **d)
        ret = fig.add_axes(*d.pop('args', []), projection=proj, **d)
        if spines is not None:
            for key, val in spines.items():
                ret.spines[key].update(val)
        if invert_xaxis:
            if ret.get_xlim()[0] < ret.get_xlim()[1]:
                ret.invert_xaxis()
        if invert_yaxis:
            if ret.get_ylim()[0] < ret.get_ylim()[1]:
                ret.invert_yaxis()
        return ret
项目:pandas-profiling    作者:JosPolfliet    | 项目源码 | 文件源码
def mini_histogram(series, **kwargs):
    """Plot a small (mini) histogram of the data.

    Parameters
    ----------
    series: Series, default None
        The data to plot.

    Returns
    -------
    str, The resulting image encoded as a string.
    """
    imgdata = BytesIO()
    plot = _plot_histogram(series, figsize=(2, 0.75), **kwargs)
    plot.axes.get_yaxis().set_visible(False)

    if LooseVersion(matplotlib.__version__) <= '1.5.9':
        plot.set_axis_bgcolor("w")
    else:
        plot.set_facecolor("w")

    xticks = plot.xaxis.get_major_ticks()
    for tick in xticks[1:-1]:
        tick.set_visible(False)
        tick.label.set_visible(False)
    for tick in (xticks[0], xticks[-1]):
        tick.label.set_fontsize(8)
    plot.figure.subplots_adjust(left=0.15, right=0.85, top=1, bottom=0.35, wspace=0, hspace=0)
    plot.figure.savefig(imgdata)
    imgdata.seek(0)
    result_string = 'data:image/png;base64,' + quote(base64.b64encode(imgdata.getvalue()))
    plt.close(plot.figure)
    return result_string
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def test_set_background_color():
    ds = fake_random_ds(32)
    plot = SlicePlot(ds, 2, 'density')
    for field in ['density', ('gas', 'density')]:
        plot.set_background_color(field, 'red')
        ax = plot.plots[field].axes
        if LooseVersion(matplotlib.__version__) < LooseVersion('2.0.0'):
            assert_equal(ax.get_axis_bgcolor(), 'red')
        else:
            assert_equal(ax.get_facecolor(), (1.0, 0.0, 0.0, 1.0))
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def set_background_color(self, field, color=None):
        """set the background color to match provided color

        Parameters
        ----------
        field : string
            the field to set the colormap
            if field == 'all', applies to all plots.
        color : string or RGBA tuple (optional)
            if set, set the background color to this color
            if unset, background color is set to the bottom value of
            the color map

        """
        actual_field = self.data_source._determine_fields(field)[0]
        if color is None:
            cmap = self._colormaps[actual_field]
            if isinstance(cmap, string_types):
                try:
                    cmap = yt_colormaps[cmap]
                except KeyError:
                    cmap = getattr(matplotlib.cm, cmap)
            color = cmap(0)
        if LooseVersion(matplotlib.__version__) < LooseVersion("2.0.0"):
            self.plots[actual_field].axes.set_axis_bgcolor(color)
        else:
            self.plots[actual_field].axes.set_facecolor(color)
        return self
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def setup_default(self):
        """Setup a default colormap

        Creates a ColorTransferFunction including 10 gaussian layers whose
        colors sample the 'spectral' colormap. Also attempts to scale the
        transfer function to produce a natural contrast ratio.

        """
        if LooseVersion(matplotlib.__version__) < LooseVersion('2.0.0'):
            colormap_name = 'spectral'
        else:
            colormap_name = 'nipy_spectral'
        self.tf.add_layers(10, colormap=colormap_name)
        factor = self.tf.funcs[-1].y.size / self.tf.funcs[-1].y.sum()
        self.tf.funcs[-1].y *= 2*factor
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def get_version_stack():
    version_info = {}
    version_info['yt'] = get_yt_version()
    version_info['numpy'] = numpy.version.version
    version_info['matplotlib'] = matplotlib.__version__
    return version_info
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _skip_if_mpl_14_or_dev_boxplot():
    # GH 8382
    # Boxplot failures on 1.4 and 1.4.1
    # Don't need try / except since that's done at class level
    import matplotlib
    if str(matplotlib.__version__) >= LooseVersion('1.4'):
        raise nose.SkipTest("Matplotlib Regression in 1.4 and current dev.")
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _skip_if_mpl_1_5():
    import matplotlib
    v = matplotlib.__version__
    if v > LooseVersion('1.4.3') or v[0] == '0':
        import nose
        raise nose.SkipTest("matplotlib 1.5")
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _skip_if_scipy_0_17():
    import scipy
    v = scipy.__version__
    if v >= LooseVersion("0.17.0"):
        import nose
        raise nose.SkipTest("scipy 0.17")
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _skip_if_no_xarray():
    try:
        import xarray
    except ImportError:
        import nose
        raise nose.SkipTest("xarray not installed")

    v = xarray.__version__
    if v < LooseVersion('0.7.0'):
        import nose
        raise nose.SkipTest("xarray not version is too low: {0}".format(v))
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _incompat_bottleneck_version(method):
    """ skip if we have bottleneck installed
    and its >= 1.0
    as we don't match the nansum/nanprod behavior for all-nan
    ops, see GH9422
    """
    if method not in ['sum','prod']:
        return False
    try:
        import bottleneck as bn
        return bn.__version__ >= LooseVersion('1.0')
    except ImportError:
        return False
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _mpl_le_1_2_1():
    try:
        import matplotlib as mpl
        return (str(mpl.__version__) <= LooseVersion('1.2.1') and
                str(mpl.__version__)[0] != '0')
    except ImportError:
        return False
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _mpl_ge_1_3_1():
    try:
        import matplotlib
        # The or v[0] == '0' is because their versioneer is
        # messed up on dev
        return (matplotlib.__version__ >= LooseVersion('1.3.1') or
                matplotlib.__version__[0] == '0')
    except ImportError:
        return False
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _mpl_ge_1_4_0():
    try:
        import matplotlib
        return (matplotlib.__version__ >= LooseVersion('1.4') or
                matplotlib.__version__[0] == '0')
    except ImportError:
        return False
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _mpl_ge_1_5_0():
    try:
        import matplotlib
        return (matplotlib.__version__ >= LooseVersion('1.5') or
                matplotlib.__version__[0] == '0')
    except ImportError:
        return False
项目:beremiz    作者:nucleron    | 项目源码 | 文件源码
def SetAxesColor(self, color):
        if LooseVersion(matplotlib.__version__) >= LooseVersion("1.5.0"):
            self.Axes.set_prop_cycle(cycler('color', color))
        else:
            self.Axes.set_color_cycle(color)
项目:yellowbrick    作者:DistrictDataLabs    | 项目源码 | 文件源码
def test_reset_defaults(self):
        """
        Test the ability to reset to the mpl defaults
        """
        # Changes to the rc parameters make this test hard to manage
        # on older versions of matplotlib, so we'll skip it
        if LooseVersion(mpl.__version__) < LooseVersion("1.3"):
            raise self.SkipTest

        yb_rcmod.reset_defaults()
        self.assert_rc_params(mpl.rcParamsDefault)
        yb_rcmod.set_aesthetic()
项目:yellowbrick    作者:DistrictDataLabs    | 项目源码 | 文件源码
def test_reset_orig(self):
        """
        Test the ability to reset to the original (respecting custom styles)
        """

        # Changes to the rc parameters make this test hard to manage
        # on older versions of matplotlib, so we'll skip it
        if LooseVersion(mpl.__version__) < LooseVersion("1.3"):
            raise self.SkipTest

        yb_rcmod.reset_orig()
        self.assert_rc_params(mpl.rcParamsOrig)
        yb_rcmod.set_aesthetic()
项目:TrilinosDrivers    作者:jjellio    | 项目源码 | 文件源码
def sanity_check():
  """
  Report the version number of the core packages we use

  :return: Nothing
  """
  import matplotlib
  print('matplotlib: {}'.format(matplotlib.__version__))
  print('numpy: {}'.format(np.__version__))
  print('pandas: {}'.format(pd.__version__))


###############################################################################
项目:TrilinosDrivers    作者:jjellio    | 项目源码 | 文件源码
def sanity_check():
  import matplotlib
  print('matplotlib: {}'.format(matplotlib.__version__))
  print('numpy: {}'.format(np.__version__))
  print('pandas: {}'.format(pd.__version__))
项目:TrilinosDrivers    作者:jjellio    | 项目源码 | 文件源码
def sanity_check():
  """
  Report the version number of the core packages we use

  :return: Nothing
  """
  import matplotlib
  print('matplotlib: {}'.format(matplotlib.__version__))
  print('numpy: {}'.format(np.__version__))
  print('pandas: {}'.format(pd.__version__))


###############################################################################
项目:faampy    作者:ncasuk    | 项目源码 | 文件源码
def freeze_color_cycle(ax):
    """A function that freezes the color cycle. This is useful for example when
    the twinx() command is used and the color cycle would normally be reseted.

    Usage:

    import matplotlib.pyplot as plt
    import numpy as np

    plt.close('all')
    for i in range(3):
        plt.plot(np.random.random(20))

    ax=plt.gca()
    cc=freeze_color_cycle(ax)
    plt.twinx()
    ax=plt.gca()
    ax.set_color_cycle(cc)

    #plot some more on the new twined axes
    for i in range(3):
        plt.plot(np.random.random(20))

    #When we set-up a new figure we start with blue again
    fig=figure()
    for i in range(3):
        plot(np.random.random(20))

    """
    import matplotlib as mpl
    if mpl.__version__  >= '1.5.1':
        next_color=ax._get_lines.prop_cycler.next()['color']
    else:
        next_color=next(ax._get_lines.color_cycle)

    ix=plt.rcParams['axes.color_cycle'].index(next_color)
    color_cycle=plt.rcParams['axes.color_cycle'][ix:]+plt.rcParams['axes.color_cycle'][:ix]

    return color_cycle
项目:psyplot    作者:Chilipp    | 项目源码 | 文件源码
def _get_versions(requirements=True):
    if requirements:
        import matplotlib as mpl
        import xarray as xr
        import pandas as pd
        import numpy as np
        return {'version': __version__,
                'requirements': {'matplotlib': mpl.__version__,
                                 'xarray': xr.__version__,
                                 'pandas': pd.__version__,
                                 'numpy': np.__version__,
                                 'python': ' '.join(sys.version.splitlines())}}
    else:
        return {'version': __version__}
项目:SLAPP3    作者:terna    | 项目源码 | 文件源码
def loadParameters(self):

    print("NetworkX version %s running" % nx.__version__)
    print("Matplotlib version %s running\n" % mplt.__version__)

    nxv = nx.__version__
    vOK = checkVersion(nxv, 'NetworkX', 1, 9, 1)

    if not vOK:
        print("NetworkX 1.9.1 or greater required")
        os.sys.exit(1)

    mpltv = mplt.__version__
    vOK = checkVersion(mpltv, 'Matplotlib', 1, 5, 1)

    if not vOK:
        print("Matplotlib 1.5.1 or greater required")
        os.sys.exit(1)

    mySeed = eval(input("random number seed (1 to get it from the clock) "))
    if mySeed == 1:
        random.seed()
    else:
        random.seed(mySeed)

    self.nAgents = 0
    print("No 'bland' agents")

    #self.worldXSize= input("X size of the world? ")
    self.worldXSize = 1
    print("X size of the world not relevant")

    #self.worldYSize= input("Y size of the world? ")
    self.worldYSize = 50
    print("y size of the world not relevant")

    # recipes
    common.maxLenght = 10
    common.maxSector = 6
    print(
        "recipes: max lenght",
        common.maxLenght,
        "and max sector number",
        common.maxSector)

    self.nCycles = eval(input("How many cycles? (0 = exit) "))

    v = input("verbose? (y/[n]) ")
    if v == "y" or v == "Y":
        common.verbose = True  # predefined False
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def _init_image(self, data, cbnorm, cblinthresh, cmap, extent, aspect):
        """Store output of imshow in image variable"""
        if (cbnorm == 'log10'):
            norm = matplotlib.colors.LogNorm()
        elif (cbnorm == 'linear'):
            norm = matplotlib.colors.Normalize()
        elif (cbnorm == 'symlog'):
            if cblinthresh is None:
                cblinthresh = (data.max()-data.min())/10.
            norm = matplotlib.colors.SymLogNorm(cblinthresh, vmin=data.min(), vmax=data.max())
        extent = [float(e) for e in extent]
        # tuple colormaps are from palettable (or brewer2mpl)
        if isinstance(cmap, tuple):
            cmap = get_brewer_cmap(cmap)
        self.image = self.axes.imshow(data.to_ndarray(), origin='lower',
                                      extent=extent, norm=norm, vmin=self.zmin,
                                      aspect=aspect, vmax=self.zmax, cmap=cmap,
                                      interpolation='nearest')
        if (cbnorm == 'symlog'):
            if LooseVersion(matplotlib.__version__) < LooseVersion("2.0.0"):
                formatter_kwargs = {}
            else:
                formatter_kwargs = dict(linthresh=cblinthresh)
            formatter = matplotlib.ticker.LogFormatterMathtext(
                **formatter_kwargs)
            self.cb = self.figure.colorbar(
                self.image, self.cax, format=formatter)
            if data.min() >= 0.0:
                yticks = [data.min().v] + list(
                    10**np.arange(np.rint(np.log10(cblinthresh)),
                                  np.ceil(np.log10(data.max())) + 1))
            elif data.max() <= 0.0:
                yticks = list(
                    -10**np.arange(
                        np.floor(np.log10(-data.min())),
                        np.rint(np.log10(cblinthresh)) - 1, -1)) + \
                    [data.max().v]
            else:
                yticks = list(
                    -10**np.arange(np.floor(np.log10(-data.min())),
                                   np.rint(np.log10(cblinthresh))-1, -1)) + \
                    [0] + \
                    list(10**np.arange(np.rint(np.log10(cblinthresh)),
                                       np.ceil(np.log10(data.max()))+1))
            self.cb.set_ticks(yticks)
        else:
            self.cb = self.figure.colorbar(self.image, self.cax)
        for which in ['major', 'minor']:
            self.cax.tick_params(which=which, axis='y', direction='in')
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def streamplot(self, x, y, u, v, *args, **kwargs):
        """
        Draws streamlines of a vector flow.
        (see matplotlib.pyplot.streamplot documentation).

        If ``latlon`` keyword is set to True, x,y are intrepreted as
        longitude and latitude in degrees.  Data and longitudes are
        automatically shifted to match map projection region for cylindrical
        and pseudocylindrical projections, and x,y are transformed to map
        projection coordinates. If ``latlon`` is False (default), x and y
        are assumed to be map projection coordinates.

        Extra keyword ``ax`` can be used to override the default axis instance.

        Other \*args and \**kwargs passed on to matplotlib.pyplot.streamplot.
        """
        if _matplotlib_version < '1.2':
            msg = dedent("""
            streamplot method requires matplotlib 1.2 or higher,
            you have %s""" % _matplotlib_version)
            raise NotImplementedError(msg)
        ax, plt = self._ax_plt_from_kw(kwargs)
        # allow callers to override the hold state by passing hold=True|False
        b = ax.ishold()
        h = kwargs.pop('hold',None)
        if h is not None:
            ax.hold(h)
        try:
            ret =  ax.streamplot(x,y,u,v,*args,**kwargs)
        except:
            ax.hold(b)
            raise
        ax.hold(b)
        if plt is not None and ret.lines.get_array() is not None:
            plt.sci(ret.lines)
        # clip for round polar plots.
        # streamplot arrows not returned in matplotlib 1.1.1, so clip all
        # FancyArrow patches attached to axes instance.
        if self. round:
            ret,c = self._clipcircle(ax,ret)
            for p in ax.patches:
                if isinstance(p,FancyArrowPatch): p.set_clip_path(c)
        # set axes limits to fit map region.
        self.set_axes_limits(ax=ax)
        return ret
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def barbs(self, x, y, u, v, *args, **kwargs):
        """
        Make a wind barb plot (u, v) with on the map.
        (see matplotlib.pyplot.barbs documentation).

        If ``latlon`` keyword is set to True, x,y are intrepreted as
        longitude and latitude in degrees.  Data and longitudes are
        automatically shifted to match map projection region for cylindrical
        and pseudocylindrical projections, and x,y are transformed to map
        projection coordinates. If ``latlon`` is False (default), x and y
        are assumed to be map projection coordinates.

        Extra keyword ``ax`` can be used to override the default axis instance.

        Other \*args and \**kwargs passed on to matplotlib.pyplot.barbs

        Returns two matplotlib.axes.Barbs instances, one for the Northern
        Hemisphere and one for the Southern Hemisphere.
        """
        if _matplotlib_version < '0.98.3':
            msg = dedent("""
            barb method requires matplotlib 0.98.3 or higher,
            you have %s""" % _matplotlib_version)
            raise NotImplementedError(msg)
        ax, plt = self._ax_plt_from_kw(kwargs)
        # allow callers to override the hold state by passing hold=True|False
        b = ax.ishold()
        h = kwargs.pop('hold',None)
        if h is not None:
            ax.hold(h)
        lons, lats = self(x, y, inverse=True)
        unh = ma.masked_where(lats <= 0, u)
        vnh = ma.masked_where(lats <= 0, v)
        ush = ma.masked_where(lats > 0, u)
        vsh = ma.masked_where(lats > 0, v)
        try:
            retnh =  ax.barbs(x,y,unh,vnh,*args,**kwargs)
            kwargs['flip_barb']=True
            retsh =  ax.barbs(x,y,ush,vsh,*args,**kwargs)
        except:
            ax.hold(b)
            raise
        ax.hold(b)
        # Because there are two collections returned in general,
        # we can't set the current image...
        #if plt is not None and ret.get_array() is not None:
        #    plt.sci(retnh)
        # clip for round polar plots.
        if self.round:
            retnh,c = self._clipcircle(ax,retnh)
            retsh,c = self._clipcircle(ax,retsh)
        # set axes limits to fit map region.
        self.set_axes_limits(ax=ax)
        return retnh,retsh
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def streamplot(self, x, y, u, v, *args, **kwargs):
        """
        Draws streamlines of a vector flow.
        (see matplotlib.pyplot.streamplot documentation).

        If ``latlon`` keyword is set to True, x,y are intrepreted as
        longitude and latitude in degrees.  Data and longitudes are
        automatically shifted to match map projection region for cylindrical
        and pseudocylindrical projections, and x,y are transformed to map
        projection coordinates. If ``latlon`` is False (default), x and y
        are assumed to be map projection coordinates.

        Extra keyword ``ax`` can be used to override the default axis instance.

        Other \*args and \**kwargs passed on to matplotlib.pyplot.streamplot.
        """
        if _matplotlib_version < '1.2':
            msg = dedent("""
            streamplot method requires matplotlib 1.2 or higher,
            you have %s""" % _matplotlib_version)
            raise NotImplementedError(msg)
        ax, plt = self._ax_plt_from_kw(kwargs)
        # allow callers to override the hold state by passing hold=True|False
        b = ax.ishold()
        h = kwargs.pop('hold',None)
        if h is not None:
            ax.hold(h)
        try:
            ret =  ax.streamplot(x,y,u,v,*args,**kwargs)
        except:
            ax.hold(b)
            raise
        ax.hold(b)
        if plt is not None and ret.lines.get_array() is not None:
            plt.sci(ret.lines)
        # clip for round polar plots.
        # streamplot arrows not returned in matplotlib 1.1.1, so clip all
        # FancyArrow patches attached to axes instance.
        if self. round:
            ret,c = self._clipcircle(ax,ret)
            for p in ax.patches:
                if isinstance(p,FancyArrowPatch): p.set_clip_path(c)
        # set axes limits to fit map region.
        self.set_axes_limits(ax=ax)
        return ret
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def barbs(self, x, y, u, v, *args, **kwargs):
        """
        Make a wind barb plot (u, v) with on the map.
        (see matplotlib.pyplot.barbs documentation).

        If ``latlon`` keyword is set to True, x,y are intrepreted as
        longitude and latitude in degrees.  Data and longitudes are
        automatically shifted to match map projection region for cylindrical
        and pseudocylindrical projections, and x,y are transformed to map
        projection coordinates. If ``latlon`` is False (default), x and y
        are assumed to be map projection coordinates.

        Extra keyword ``ax`` can be used to override the default axis instance.

        Other \*args and \**kwargs passed on to matplotlib.pyplot.barbs

        Returns two matplotlib.axes.Barbs instances, one for the Northern
        Hemisphere and one for the Southern Hemisphere.
        """
        if _matplotlib_version < '0.98.3':
            msg = dedent("""
            barb method requires matplotlib 0.98.3 or higher,
            you have %s""" % _matplotlib_version)
            raise NotImplementedError(msg)
        ax, plt = self._ax_plt_from_kw(kwargs)
        # allow callers to override the hold state by passing hold=True|False
        b = ax.ishold()
        h = kwargs.pop('hold',None)
        if h is not None:
            ax.hold(h)
        lons, lats = self(x, y, inverse=True)
        unh = ma.masked_where(lats <= 0, u)
        vnh = ma.masked_where(lats <= 0, v)
        ush = ma.masked_where(lats > 0, u)
        vsh = ma.masked_where(lats > 0, v)
        try:
            retnh =  ax.barbs(x,y,unh,vnh,*args,**kwargs)
            kwargs['flip_barb']=True
            retsh =  ax.barbs(x,y,ush,vsh,*args,**kwargs)
        except:
            ax.hold(b)
            raise
        ax.hold(b)
        # Because there are two collections returned in general,
        # we can't set the current image...
        #if plt is not None and ret.get_array() is not None:
        #    plt.sci(retnh)
        # clip for round polar plots.
        if self.round:
            retnh,c = self._clipcircle(ax,retnh)
            retsh,c = self._clipcircle(ax,retsh)
        # set axes limits to fit map region.
        self.set_axes_limits(ax=ax)
        return retnh,retsh
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def package_check(pkg_name, version=None, app='pandas', checker=LooseVersion,
                  exc_failed_import=ImportError,
                  exc_failed_check=RuntimeError):
    """Check that the minimal version of the required package is installed.

    Parameters
    ----------
    pkg_name : string
        Name of the required package.
    version : string, optional
        Minimal version number for required package.
    app : string, optional
        Application that is performing the check.  For instance, the
        name of the tutorial being executed that depends on specific
        packages.
    checker : object, optional
        The class that will perform the version checking.  Default is
        distutils.version.LooseVersion.
    exc_failed_import : Exception, optional
        Class of the exception to be thrown if import failed.
    exc_failed_check : Exception, optional
        Class of the exception to be thrown if version check failed.

    Examples
    --------
    package_check('numpy', '1.3')
    package_check('networkx', '1.0', 'tutorial1')

    """

    if app:
        msg = '%s requires %s' % (app, pkg_name)
    else:
        msg = 'module requires %s' % pkg_name
    if version:
        msg += ' with version >= %s' % (version,)
    try:
        mod = __import__(pkg_name)
    except ImportError:
        raise exc_failed_import(msg)
    if not version:
        return
    try:
        have_version = mod.__version__
    except AttributeError:
        raise exc_failed_check('Cannot find version for %s' % pkg_name)
    if checker(have_version) < checker(version):
        raise exc_failed_check(msg)
项目:TTClust    作者:tubiana    | 项目源码 | 文件源码
def init_log(args, mdtrajectory):
    """
    DESCRIPTION
    initialyse the logfile with some information
    ----
    Args:
        args (dict): dictionnary of all arguments (argparse)
    """
    topo = args["top"]
    traj = args["traj"]
    selection_string = args["select_traj"]
    select_align = args["select_alignement"]
    select_rmsd = args["select_rmsd"]
    logname = os.path.splitext(args["logfile"])[0]


    LOGFILE.write("========================================================\n")
    LOGFILE.write("====================  TTCLUST {}  ===================\n"\
        .format(__version__))
    LOGFILE.write("========================================================\n")
    LOGFILE.write("\n")


    LOGFILE.write("************ General information ************\n")
    LOGFILE.write("software version   : {}\n".format(__version__))
    LOGFILE.write("Created on         : {}\n".format(datetime.datetime.now()))
    write_command_line()
    LOGFILE.write("DESTINATION FOLDER : {}\n".format(os.getcwd()+"/"+logname))
    LOGFILE.write("ARGUMENTS : \n")
    LOGFILE.write("  Selection string :\n")
    LOGFILE.write("      Atoms selected in trajectory = {} \n".format(
                                                        selection_string))
    LOGFILE.write("      Atoms selected for alignement = {} \n".format(
                                                        select_align))
    LOGFILE.write("      Atoms selected for RMSD = {} \n".format(select_rmsd))
    LOGFILE.write("  trajectory file  : {} \n".format(traj))
    LOGFILE.write("   Number of frames  : {} \n".format(mdtrajectory.n_frames))
    LOGFILE.write("   Number of atoms  : {} \n".format(mdtrajectory.n_atoms))
    LOGFILE.write("  topology file    : {} \n".format(topo))
    LOGFILE.write("  method used of clusterring : {}".format(args["method"]))
    LOGFILE.write("\n\n")
    if args["ngroup"]:
        LOGFILE.write("  Number of cluster asked: {}\n".format(args["ngroup"]))
    if args["cutoff"]:
        LOGFILE.write("  cutoff for dendrogram clustering: {}\n".format("cutoff"))
项目:TTClust    作者:tubiana    | 项目源码 | 文件源码
def plot_hist(clusters_list, logname,colors_list):
    """
    DESCRIPTION
    This function is used to plot a histogram with the cluster size.
    Args:
        cluster_number_list (list) : list of cluster label in order or appearance
        output (str) : output logname
    Returns:
        None
    """
    if mpl.__version__[0] == "2":
        STYLE = "classic"
        if STYLE in plt.style.available:
            plt.style.use(STYLE)
    values = []
    labels = []
    for cl in clusters_list:
        #occurence.append((cl.id, cl.size))
        values.append(cl.size)
        labels.append(cl.id)
    #Sorting occurence dict by cluster size

    #### Configuration plot
    width = 0.7 # bars size
    index = np.arange(len(values)) # the x locations for the groups
    fig, ax = plt.subplots()

    bp = ax.bar(index, values, width, color=colors_list, label="Cluster size")
    #add value on top of bars, adapted from matplotlib doc
    for rect in bp:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.0*height,
                '%d' % int(height),
                ha='center', va='bottom')

    plt.xlabel("Clusters")
    plt.ylabel("Number of members")
    plt.title("Distribution within clusters")
    plt.xticks(index+(width/2), labels)
    plt.tight_layout()

    plt.savefig("{0}/{0}-hist.png".format(logname), dpi=DPI,transparent=True)
    plt.close()
项目:TTClust    作者:tubiana    | 项目源码 | 文件源码
def plot_dendro(linkage, logname, cutoff, color_list,clusters_list):
    """
    DESCRIPTION
    This function will create the dendrogram graph with the corresponding
    cluster color.
    Args:
        linkage (numpy array) : linkage matrix
        output (str) : output logfile name
        cutoff (float) : cutoff used for clustering
        color_list (list) : HEX code color for each cluster
        cluster_list (list) : list of all cluster (Cluster object)
    Returns:
        None
    """
    if mpl.__version__[0] == "2":
        STYLE = "classic"
        if STYLE in plt.style.available:
            plt.style.use(STYLE)
    fig = plt.figure()
    #Convert RGB color to HEX color
    color_hex = [mpl.colors.rgb2hex(x) for x in color_list]
    sch.set_link_color_palette(color_hex)
    #clusters_list
    color_member = {}
    for cl in clusters_list:
        for frm in cl.frames:
            color_member[frm] = mpl.colors.rgb2hex(color_list[cl.id-1])

    #Attribute the correct color for each branch.
    #adapte from Ulrich Stern code in StackOverflow http://stackoverflow.com/a/38208611
    link_cols = {}
    for i, i12 in enumerate(linkage[:,:2].astype(int)):
        c1, c2 = (link_cols[x] if x > len(linkage) else color_member[x] for x in i12)
        link_cols[i+1+len(linkage)] = c1 if c1 == c2 else "#808080"

    #Dendrogram creation
    # Override the default linewidth.
    den = sch.dendrogram(linkage, color_threshold=float(cutoff), above_threshold_color="#808080", link_color_func=lambda x: link_cols[x])

    #Graph parameters
    plt.title("Clustering Dendrogram")
    ax = plt.axes()
    ax.set_xticklabels([])
    plt.axhline(y=float(cutoff), color = "grey") # cutoff value vertical line
    ax.set_ylabel("Distance (AU)")
    ax.set_xlabel("Frames")

    plt.savefig("{0}/{0}-den.png".format(logname), format="png", dpi=DPI, transparent=True)
    plt.close()
项目:persian-word-cloud    作者:Mehotkhan    | 项目源码 | 文件源码
def __init__(self, font_path=None, only_persian=False, width=400, height=200, margin=2,
                 ranks_only=None, prefer_horizontal=.9, mask=None, scale=1,
                 color_func=None, max_words=200, min_font_size=4,
                 stopwords=None, random_state=None, background_color='black',
                 max_font_size=None, font_step=1, mode="RGB",
                 relative_scaling=.5, regexp=None, collocations=True,
                 colormap=None, normalize_plurals=True):
        super(PersianWordCloud, self).__init__(font_path, width, height, margin,
                                               ranks_only, prefer_horizontal, mask, scale,
                                               color_func, max_words, min_font_size,
                                               stopwords, random_state, background_color,
                                               max_font_size, font_step, mode,
                                               relative_scaling, regexp, collocations,
                                               colormap, normalize_plurals)
        if font_path is None:
            font_path = FONT_PATH
        if color_func is None and colormap is None:
            # we need a color map
            import matplotlib
            version = matplotlib.__version__
            if version[0] < "2" and version[2] < "5":
                colormap = "hsv"
            else:
                colormap = "viridis"
        self.only_persian = only_persian
        self.colormap = colormap
        self.collocations = collocations
        self.font_path = font_path
        self.width = width
        self.height = height
        self.margin = margin
        self.prefer_horizontal = prefer_horizontal
        self.mask = mask
        self.scale = scale
        self.color_func = color_func or colormap_color_func(colormap)
        self.max_words = max_words
        self.stopwords = stopwords if stopwords is not None else STOPWORDS
        self.min_font_size = min_font_size
        self.font_step = font_step
        self.regexp = regexp
        if isinstance(random_state, int):
            random_state = Random(random_state)
        self.random_state = random_state
        self.background_color = background_color
        self.max_font_size = max_font_size
        self.mode = mode
        if relative_scaling < 0 or relative_scaling > 1:
            raise ValueError("relative_scaling needs to be "
                             "between 0 and 1, got %f." % relative_scaling)
        self.relative_scaling = relative_scaling
        if ranks_only is not None:
            warnings.warn("ranks_only is deprecated and will be removed as"
                          " it had no effect. Look into relative_scaling.",
                          DeprecationWarning)
        self.normalize_plurals = normalize_plurals