Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Closed
Prev Previous commit
Next Next commit
Review actions
  • Loading branch information
Phil Elson committed Feb 20, 2012
commit f8021a206a703703a3a98c350b8a59e909f34617
36 changes: 15 additions & 21 deletions lib/matplotlib/axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -938,15 +938,11 @@ def hold(self, b=None):
Set the hold state. If *hold* is *None* (default), toggle the
*hold* state. Else set the *hold* state to boolean value *b*.

Examples:

* toggle hold:
>>> hold()
* turn hold on:
>>> hold(True)
* turn hold off
>>> hold(False)

Examples::

hold() # toggle hold
hold(True) # turn hold on
hold(False) # turn hold off

When hold is True, subsequent plot commands will be added to
the current axes. When hold is False, the current axes and
Expand Down Expand Up @@ -3461,12 +3457,11 @@ def axhspan(self, ymin, ymax, xmin=0, xmax=1, **kwargs):
Return value is a :class:`matplotlib.patches.Polygon`
instance.

Examples:

* draw a gray rectangle from *y* = 0.25-0.75 that spans the
horizontal extent of the axes
Examples::

>>> axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5)
# draw a gray rectangle from *y* = 0.25-0.75 that spans the
# horizontal extent of the axes
axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5)

Valid kwargs are :class:`~matplotlib.patches.Polygon` properties:

Expand Down Expand Up @@ -3519,10 +3514,9 @@ def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs):

Examples:

* draw a vertical green translucent rectangle from x=1.25 to 1.55 that
spans the yrange of the axes

>>> axvspan(1.25, 1.55, facecolor='g', alpha=0.5)
# draw a vertical green translucent rectangle from x=1.25 to 1.55
# that spans the yrange of the axes
axvspan(1.25, 1.55, facecolor='g', alpha=0.5)

Valid kwargs are :class:`~matplotlib.patches.Polygon`
properties:
Expand Down Expand Up @@ -6872,7 +6866,7 @@ def pcolor(self, *args, **kwargs):
y = np.arange(3)
X, Y = meshgrid(x,y)

is equivalent to:
is equivalent to::

X = array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
Expand Down Expand Up @@ -7412,11 +7406,11 @@ def hist(self, x, bins=10, range=None, normed=False, weights=None,
"""
call signature::

def hist(x, bins=10, range=None, normed=False, weights=None,
hist(x, bins=10, range=None, normed=False, weights=None,
cumulative=False, bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False,
color=None, label=None,
**kwargs):
**kwargs)

Compute and draw the histogram of *x*. The return value is a
tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
Expand Down
147 changes: 78 additions & 69 deletions lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@

from legend import Legend
from transforms import Affine2D, Bbox, BboxTransformTo, TransformedBbox
from projections import projection_factory, get_projection_names, \
get_projection_class
from projections import get_projection_names, get_projection_class, \
process_projection_requirements
from matplotlib.blocking_input import BlockingMouseInput, BlockingKeyMouseInput

import matplotlib.cbook as cbook
Expand Down Expand Up @@ -107,12 +107,17 @@ def add(self, key, a):
self._ind += 1
return Stack.push(self, (key, (self._ind, a)))

def __call__(self):
def current_key_axes(self):
"""Return a tuple of (key, axes) for the last axes added."""
if not len(self._elements):
return self._default
return self._default, self._default
else:
return self._elements[self._pos][1][1]
key, (index, axes) = self._elements[self._pos]
return key, axes

def __call__(self):
return self.current_key_axes()[1]

def __contains__(self, a):
return a in self.as_list()

Expand Down Expand Up @@ -681,6 +686,8 @@ def add_axes(self, *args, **kwargs):
"""
if not len(args): return

# shortcut the projection "key" modifications later on, if an axes
# with the exact args/kwargs exists, return it immediately.
key = self._make_key(*args, **kwargs)
ax = self._axstack.get(key)
if ax is not None:
Expand All @@ -692,25 +699,18 @@ def add_axes(self, *args, **kwargs):
assert(a.get_figure() is self)
else:
rect = args[0]
ispolar = kwargs.pop('polar', False)
projection = kwargs.pop('projection', None)
if ispolar:
if projection is not None and projection != 'polar':
raise ValueError(
"polar=True, yet projection=%r. "
"Only one of these arguments should be supplied." %
projection)
projection = 'polar'

if isinstance(projection, basestring) or projection is None:
a = projection_factory(projection, self, rect, **kwargs)
elif hasattr(projection, '_as_mpl_axes'):
projection_class, extra_kwargs = projection._as_mpl_axes()
kwargs.update(**extra_kwargs)
a = projection_class(self, rect, **kwargs)
else:
TypeError('projection must be a string, None or implement a '
'_as_mpl_axes method. Got %r' % projection)
projection_class, kwargs, key = \
process_projection_requirements(self, **kwargs)

# check that an axes of this type doesn't already exist, if it
# does, set it as active and return it
ax = self._axstack.get(key)
if ax is not None and isinstance(ax, projection_class):
self.sca(ax)
return ax

# create the new axes using the axes class given
a = projection_class(self, rect, **kwargs)

self._axstack.add(key, a)
self.sca(a)
Expand All @@ -719,14 +719,21 @@ def add_axes(self, *args, **kwargs):
@docstring.dedent_interpd
def add_subplot(self, *args, **kwargs):
"""
Add a subplot. Examples:
Add a subplot. Examples::

fig.add_subplot(111)
fig.add_subplot(1,1,1) # equivalent but more general
fig.add_subplot(212, axisbg='r') # add subplot with red background
fig.add_subplot(111, projection='polar') # add a polar subplot
fig.add_subplot(111, polar=True) # add a polar subplot
fig.add_subplot(sub) # add Subplot instance sub

# equivalent but more general
fig.add_subplot(1,1,1)

# add subplot with red background
fig.add_subplot(212, axisbg='r')

# add a polar subplot
fig.add_subplot(111, projection='polar')

# add Subplot instance sub
fig.add_subplot(sub)

*kwargs* are legal :class:`!matplotlib.axes.Axes` kwargs plus
*projection*, which chooses a projection type for the axes.
Expand Down Expand Up @@ -756,42 +763,27 @@ def add_subplot(self, *args, **kwargs):
assert(a.get_figure() is self)
key = self._make_key(*args, **kwargs)
else:
kwargs = kwargs.copy()
ispolar = kwargs.pop('polar', False)
projection = kwargs.pop('projection', None)
if ispolar:
if projection is not None and projection != 'polar':
raise ValueError(
"polar=True, yet projection=%r. "
"Only one of these arguments should be supplied." %
projection)
projection = 'polar'

if isinstance(projection, basestring) or projection is None:
projection_class = get_projection_class(projection)
elif hasattr(projection, '_as_mpl_axes'):
projection_class, extra_kwargs = projection._as_mpl_axes()
kwargs.update(**extra_kwargs)
else:
TypeError('projection must be a string, None or implement a '
'_as_mpl_axes method. Got %r' % projection)

# Remake the key without projection kwargs:
key = self._make_key(*args, **kwargs)
projection_class, kwargs, key = \
process_projection_requirements(self, **kwargs)

# try to find the axes with this key in the stack
ax = self._axstack.get(key)

if ax is not None:
if isinstance(ax, projection_class):
# the axes already existed, so set it as active & return
self.sca(ax)
return ax
else:
self._axstack.remove(ax)
# Undocumented convenience behavior:
# subplot(111); subplot(111, projection='polar')
# will replace the first with the second.
# Without this, add_subplot would be simpler and
# more similar to add_axes.
self._axstack.remove(ax)

a = subplot_class_factory(projection_class)(self, *args, **kwargs)

self._axstack.add(key, a)
self.sca(a)
return a
Expand Down Expand Up @@ -1049,23 +1041,40 @@ def gca(self, **kwargs):
"""
Return the current axes, creating one if necessary

The following kwargs are supported
The following kwargs are supported for ensuring the returned axes
adheres to the given projection etc., and for axes creation if
the active axes does not exist:
%(Axes)s

.. note::
When specifying kwargs to ``gca`` to find the pre-created active
axes, they should be equivalent in every way to the kwargs which
were used in its creation.

"""
ax = self._axstack()
if ax is not None:
ispolar = kwargs.get('polar', False)
projection = kwargs.get('projection', None)
if ispolar:
if projection is not None and projection != 'polar':
raise ValueError(
"polar=True, yet projection='%s'. " % projection +
"Only one of these arguments should be supplied.")
projection = 'polar'

projection_class = get_projection_class(projection)
if isinstance(ax, projection_class):
return ax
ckey, kax = self._axstack.current_key_axes()
# if there exists an axes on the stack see if it maches
# the desired axes configuration
if kax is not None:

# if no kwargs are given just return the current axes
# this is a convenience for gca() on axes such as polar etc.
if not kwargs:
return kax

# if the user has specified particular projection detail
# then build up a key which can represent this
else:
# we don't want to modify the original kwargs
# so take a copy so that we can do what we like to it
kwargs_copy = kwargs.copy()
projection_class, _, key = \
process_projection_requirements(self, **kwargs_copy)
# if the kax matches this key then return the axes, otherwise
# continue and a new axes will be created
if key == ckey and isinstance(kax, projection_class):
return kax

return self.add_subplot(111, **kwargs)

def sca(self, a):
Expand Down Expand Up @@ -1096,7 +1105,7 @@ def savefig(self, *args, **kwargs):

savefig(fname, dpi=None, facecolor='w', edgecolor='w',
orientation='portrait', papertype=None, format=None,
transparent=False, bbox_inches=None, pad_inches=0.1):
transparent=False, bbox_inches=None, pad_inches=0.1)

Save the current figure.

Expand Down
49 changes: 35 additions & 14 deletions lib/matplotlib/projections/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ def get_projection_names(self):
def register_projection(cls):
projection_registry.register(cls)


def get_projection_class(projection=None):
"""
Get a projection class from its name.
Expand All @@ -61,22 +62,42 @@ def get_projection_class(projection=None):
except KeyError:
raise ValueError("Unknown projection '%s'" % projection)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can't be getting rid of a public function (even if it probably doesn't get used elsewhere) without a deprecation notice and an addendum in the api_changes.

def projection_factory(projection, figure, rect, **kwargs):
"""
Get a new projection instance.

*projection* is a projection name.

*figure* is a figure to add the axes to.

*rect* is a :class:`~matplotlib.transforms.Bbox` object specifying
the location of the axes within the figure.

Any other kwargs are passed along to the specific projection
constructor being used.
"""
def process_projection_requirements(figure, *args, **kwargs):
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you double-tabbed the body of this method.

"""
Handle the args/kwargs to for add_axes/add_subplot/gca,
returning::

(axes_proj_class, proj_class_kwargs, proj_stack_key)

Which can be used for new axes initialization/identification.

"""
ispolar = kwargs.pop('polar', False)
projection = kwargs.pop('projection', None)
if ispolar:
if projection is not None and projection != 'polar':
raise ValueError(
"polar=True, yet projection=%r. "
"Only one of these arguments should be supplied." %
projection)
projection = 'polar'

if isinstance(projection, basestring) or projection is None:
projection_class = get_projection_class(projection)
elif hasattr(projection, '_as_mpl_axes'):
projection_class, extra_kwargs = projection._as_mpl_axes()
kwargs.update(**extra_kwargs)
else:
raise TypeError('projection must be a string, None or implement a '
'_as_mpl_axes method. Got %r' % projection)

# Make the key without projection kwargs, this is used as a unique
# lookup for axes instances
key = figure._make_key(*args, **kwargs)

return projection_class, kwargs, key

return get_projection_class(projection)(figure, rect, **kwargs)

def get_projection_names():
"""
Expand Down