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
python类__version__()的实例源码
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
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
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
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
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
def get_h2o_status():
try:
import h2o
return _check_version(h2o.__version__, h2o_min_version)
except ImportError:
traceback.print_exc()
return default_status
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
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
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
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))
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
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
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
test_graphics_others.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
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.")
testing.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
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")
testing.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
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")
testing.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
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))
testing.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
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
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
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
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
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
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def _mpl_ge_1_4_0():
try:
import matplotlib
return (matplotlib.__version__ >= LooseVersion('1.4') or
matplotlib.__version__[0] == '0')
except ImportError:
return False
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def _mpl_ge_1_5_0():
try:
import matplotlib
return (matplotlib.__version__ >= LooseVersion('1.5') or
matplotlib.__version__[0] == '0')
except ImportError:
return False
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)
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()
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()
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__))
###############################################################################
def sanity_check():
import matplotlib
print('matplotlib: {}'.format(matplotlib.__version__))
print('numpy: {}'.format(np.__version__))
print('pandas: {}'.format(pd.__version__))
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__))
###############################################################################
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
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__}