|
From: <jd...@us...> - 2010-11-09 15:23:32
|
Revision: 8785
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=8785&view=rev
Author: jdh2358
Date: 2010-11-09 15:23:25 +0000 (Tue, 09 Nov 2010)
Log Message:
-----------
fix a bug in context so plot directive will be forced to run (but not save) figs which are already cached
Modified Paths:
--------------
branches/v1_0_maint/doc/users/annotations_guide.rst
branches/v1_0_maint/doc/users/gridspec.rst
branches/v1_0_maint/doc/users/image_tutorial.rst
branches/v1_0_maint/doc/users/recipes.rst
branches/v1_0_maint/lib/matplotlib/sphinxext/plot_directive.py
Removed Paths:
-------------
branches/v1_0_maint/examples/units/date_converter.py
branches/v1_0_maint/examples/units/date_support.py
Modified: branches/v1_0_maint/doc/users/annotations_guide.rst
===================================================================
--- branches/v1_0_maint/doc/users/annotations_guide.rst 2010-11-09 07:46:54 UTC (rev 8784)
+++ branches/v1_0_maint/doc/users/annotations_guide.rst 2010-11-09 15:23:25 UTC (rev 8785)
@@ -310,6 +310,7 @@
as 2. The callable object should take a single argument of
renderer instance. For example, following two commands give
identical results ::
+
an2 = ax.annotate("Test 2", xy=(1, 0.5), xycoords=an1,
xytext=(30,0), textcoords="offset points")
an2 = ax.annotate("Test 2", xy=(1, 0.5), xycoords=an1.get_window_extent,
@@ -322,7 +323,7 @@
annotate("Test", xy=(0.5, 1), xycoords=("data", "axes fraction"))
0.5 is in data coordinate, and 1 is in normalized axes coordinate.
- You may use an atist or transform as with a tuple. For example,
+ You may use an atist or transform as with a tuple. For example,
.. plot:: users/plotting/examples/annotate_simple_coord02.py
:include-source:
Modified: branches/v1_0_maint/doc/users/gridspec.rst
===================================================================
--- branches/v1_0_maint/doc/users/gridspec.rst 2010-11-09 07:46:54 UTC (rev 8784)
+++ branches/v1_0_maint/doc/users/gridspec.rst 2010-11-09 15:23:25 UTC (rev 8785)
@@ -1,4 +1,4 @@
-.. _gridspec-guide:
+\.. _gridspec-guide:
************************************************
@@ -23,7 +23,7 @@
====================================
To use subplot2grid, you provide geometry of the grid and the location
-of the subplot in the grid. For a simple single-cell subplot, ::
+of the subplot in the grid. For a simple single-cell subplot::
ax = plt.subplot2grid((2,2),(0, 0))
Modified: branches/v1_0_maint/doc/users/image_tutorial.rst
===================================================================
--- branches/v1_0_maint/doc/users/image_tutorial.rst 2010-11-09 07:46:54 UTC (rev 8784)
+++ branches/v1_0_maint/doc/users/image_tutorial.rst 2010-11-09 15:23:25 UTC (rev 8785)
@@ -40,8 +40,7 @@
Importing image data into Numpy arrays
===============================================
-Plotting image data is supported by the Python Image Library (`PIL
-<http://www.pythonware.com/products/pil/>`_), . Natively, matplotlib
+Plotting image data is supported by the Python Image Library (`PIL <http://www.pythonware.com/products/pil/>`_), . Natively, matplotlib
only supports PNG images. The commands shown below fall back on PIL
if the native read fails.
@@ -122,8 +121,7 @@
data. Why 8 bits? Most displays can only render 8 bits per channel
worth of color gradation. Why can they only render 8 bits/channel?
Because that's about all the human eye can see. More here (from a
-photography standpoint): `Luminous Landscape bit depth tutorial
-<http://www.luminous-landscape.com/tutorials/bit-depth.shtml>`_.
+photography standpoint): `Luminous Landscape bit depth tutorial <http://www.luminous-landscape.com/tutorials/bit-depth.shtml>`_.
Each inner list represents a pixel. Here, with an RGB image, there
are 3 values. Since it's a black and white image, R, G, and B are all
@@ -179,8 +177,7 @@
In [6]: lum_img = img[:,:,0]
-This is array slicing. You can read more in the `Numpy tutorial
-<http://www.scipy.org/Tentative_NumPy_Tutorial>`_.
+This is array slicing. You can read more in the `Numpy tutorial <http://www.scipy.org/Tentative_NumPy_Tutorial>`_.
.. sourcecode:: ipython
@@ -229,9 +226,7 @@
imgplot = plt.imshow(lum_img)
imgplot.set_cmap('spectral')
-There are many other colormap schemes available. See the `list and
-images of the colormaps
-<http://matplotlib.sourceforge.net/examples/pylab_examples/show_colormaps.html>`_.
+There are many other colormap schemes available. See the `list and images of the colormaps <http://matplotlib.sourceforge.net/examples/pylab_examples/show_colormaps.html>`_.
.. _Color Bars
Modified: branches/v1_0_maint/doc/users/recipes.rst
===================================================================
--- branches/v1_0_maint/doc/users/recipes.rst 2010-11-09 07:46:54 UTC (rev 8784)
+++ branches/v1_0_maint/doc/users/recipes.rst 2010-11-09 15:23:25 UTC (rev 8785)
@@ -56,21 +56,30 @@
everything at once, and turn off x and y sharing for the whole bunch.
You can either unpack the axes individually::
- # new style method 1
- fig, (ax1, ax2, ax3, ax4) = plt.subplots(2, 2, sharex=True, sharey=True)
+ # new style method 1; unpack the axes
+ fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax1.plot(x)
or get them back as a numrows x numcolumns object array which supports
numpy indexing::
- # new style method 2
+ # new style method 2; use an axes array
fig, axs = plt.subplots(2, 2, sharex=True, sharey=True)
axs[0,0].plot(x)
+
Fixing common date annoyances
=============================
+
+.. plot::
+ :nofigs:
+ :context:
+
+ # clear the state for context use below
+ plt.close('all')
+
matplotlib allows you to natively plots python datetime instances, and
for the most part does a good job picking tick locations and string
formats. There are a couple of things it does not handle so
@@ -97,13 +106,15 @@
objects are datetime.date instances, which we can see when we print
some samples in the ipython terminal window.
-If you plot the data, you will see that the x tick labels are all
-squashed together::
+If you plot the data, ::
In [67]: plot(r.date, r.close)
Out[67]: [<matplotlib.lines.Line2D object at 0x92a6b6c>]
+you will see that the x tick labels are all squashed together.
+
.. plot::
+ :context:
import matplotlib.cbook as cbook
datafile = cbook.get_sample_data('goog.npy')
@@ -113,23 +124,22 @@
plt.title('Default date handling can cause overlapping labels')
Another annoyance is that if you hover the mouse over a the window and
-look in the lower right corner of the matplotlib toolbar at the x and
-y coordinates, you see that the x locations are formatted the same way
-the tick labels are, eg "Dec 2004". What we'd like is for the
-location in the toolbar to have a higher degree of precision, eg
-giving us the exact date out mouse is hovering over. To fix the first
-problem, we can use method:`matplotlib.figure.Figure.autofmt_xdate()`
-and to fix the second problem we can use the ``ax.fmt_xdata``
-attribute which can be set to any function that takes a position and
-returns a string. matplotlib has a number of date formatters built
-im, so we'll use one of those.
+look in the lower right corner of the matplotlib toolbar
+(:ref:`navigation-toolbar`) at the x and y coordinates, you see that
+the x locations are formatted the same way the tick labels are, eg
+"Dec 2004". What we'd like is for the location in the toolbar to have
+a higher degree of precision, eg giving us the exact date out mouse is
+hovering over. To fix the first problem, we can use
+method:`matplotlib.figure.Figure.autofmt_xdate` and to fix the second
+problem we can use the ``ax.fmt_xdata`` attribute which can be set to
+any function that takes a scalar and returns a string. matplotlib has
+a number of date formatters built in, so we'll use one of those.
.. plot::
:include-source:
+ :context:
- import matplotlib.cbook as cbook
- datafile = cbook.get_sample_data('goog.npy')
- r = np.load(datafile).view(np.recarray)
+ plt.close('all')
fig, ax = plt.subplots(1)
ax.plot(r.date, r.close)
@@ -140,10 +150,10 @@
# toolbar
import matplotlib.dates as mdates
ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
- plt.title('autfmt_xdate fixes the labels')
+ plt.title('fig.autofmt_xdate fixes the labels')
Now when you hover your mouse over the plotted data, you'll see date
-format strings like 2004-12-01.
+format strings like 2004-12-01 in the toolbar.
Fill Between and Alpha
======================
@@ -154,7 +164,7 @@
combine filling with logical ranges, eg to just fill in a curve over
some threshold value.
-At it's most basic level, ``fill_between`` can be use to enhance a
+At its most basic level, ``fill_between`` can be use to enhance a
graphs visual appearance. Let's compare two graphs of a financial
times with a simple line plot on the left and a filled line on the
right.
@@ -162,6 +172,9 @@
.. plot::
:include-source:
+ import matplotlib.pyplot as plt
+ import numpy as np
+
import matplotlib.cbook as cbook
# load up some sample financial data
@@ -180,6 +193,9 @@
ax.grid(True)
ax1.set_ylabel('price')
+ for label in ax2.get_yticklabels():
+ label.set_visible(False)
+
fig.suptitle('Google (GOOG) daily closing price')
fig.autofmt_xdate()
@@ -193,21 +209,24 @@
Our next example computes two populations of random walkers with a
different mean and standard deviation of the normal distributions from
-which there steps are drawn. We use shared regions to plot +/- one
+which the steps are drawn. We use shared regions to plot +/- one
standard deviation of the mean position of the population. Here the
alpha channel is useful, not just aesthetic.
.. plot::
:include-source:
+ import matplotlib.pyplot as plt
+ import numpy as np
+
Nsteps, Nwalkers = 100, 250
t = np.arange(Nsteps)
- # an Nsteps x Nwalkers array of random walk steps
+ # an (Nsteps x Nwalkers) array of random walk steps
S1 = 0.002 + 0.01*np.random.randn(Nsteps, Nwalkers)
S2 = 0.004 + 0.02*np.random.randn(Nsteps, Nwalkers)
- # an Nsteps x Nwalkers array of random walker positions
+ # an (Nsteps x Nwalkers) array of random walker positions
X1 = S1.cumsum(axis=0)
X2 = S2.cumsum(axis=0)
@@ -232,16 +251,16 @@
ax.grid()
-The where keyword argument is very handy for highlighting certain
-regions of the graph. Where takes a boolean mask the same length as
-the x, ymin and ymax arguments, and only fills in the region where the
-boolean mask is True. In the example below, we take a a single random
-walker and compute the analytic mean and standard deviation of the
-population positions. The population mean is shown as the black
+The ``where`` keyword argument is very handy for highlighting certain
+regions of the graph. ``where`` takes a boolean mask the same length
+as the x, ymin and ymax arguments, and only fills in the region where
+the boolean mask is True. In the example below, we simulate a single
+random walker and compute the analytic mean and standard deviation of
+the population positions. The population mean is shown as the black
dashed line, and the plus/minus one sigma deviation from the mean is
showsn as the yellow filled region. We use the where mask
-``X>upper_bound`` to find the region where the walker is above the
-one sigma boundary, and shade that region blue.
+``X>upper_bound`` to find the region where the walker is above the one
+sigma boundary, and shade that region blue.
.. plot::
:include-source:
@@ -258,7 +277,7 @@
S = mu + sigma*np.random.randn(Nsteps)
X = S.cumsum()
- # the 1 sigma upper and lower population bounds
+ # the 1 sigma upper and lower analytic population bounds
lower_bound = mu*t - sigma*np.sqrt(t)
upper_bound = mu*t + sigma*np.sqrt(t)
@@ -323,9 +342,9 @@
When decorating axes with text boxes, two useful tricks are to place
the text in axes coordinates (see :ref:`transforms_tutorial`), so the
text doesn't move around with changes in x or y limits. You can also
-use the bbox property of text to surround the text with a
-:class:`~matplotlib.patches.Patch` instance -- the boox keyword argument
-takes a dictionary with keys that are Patch properties.
+use the ``bbox`` property of text to surround the text with a
+:class:`~matplotlib.patches.Patch` instance -- the ``bbox`` keyword
+argument takes a dictionary with keys that are Patch properties.
.. plot::
:include-source:
Deleted: branches/v1_0_maint/examples/units/date_converter.py
===================================================================
--- branches/v1_0_maint/examples/units/date_converter.py 2010-11-09 07:46:54 UTC (rev 8784)
+++ branches/v1_0_maint/examples/units/date_converter.py 2010-11-09 15:23:25 UTC (rev 8785)
@@ -1,20 +0,0 @@
-import date_support # set up the date converters
-import datetime
-from matplotlib.dates import drange
-from pylab import figure, show
-import numpy as np
-
-
-xmin = datetime.date(2007,1,1)
-xmax = datetime.date.today()
-delta = datetime.timedelta(days=1)
-xdates = drange(xmin, xmax, delta)
-
-fig = figure()
-fig.subplots_adjust(bottom=0.2)
-ax = fig.add_subplot(111)
-ax.plot(xdates, np.random.rand(len(xdates)), 'o')
-ax.set_xlim(datetime.date(2007,2,1), datetime.date(2007,3,1))
-
-fig.autofmt_xdate()
-show()
Deleted: branches/v1_0_maint/examples/units/date_support.py
===================================================================
--- branches/v1_0_maint/examples/units/date_support.py 2010-11-09 07:46:54 UTC (rev 8784)
+++ branches/v1_0_maint/examples/units/date_support.py 2010-11-09 15:23:25 UTC (rev 8785)
@@ -1,36 +0,0 @@
-import matplotlib
-matplotlib.rcParams['units'] = True
-from matplotlib.cbook import iterable, is_numlike
-import matplotlib.units as units
-import matplotlib.dates as dates
-import matplotlib.ticker as ticker
-import datetime
-
-class DateConverter(units.ConversionInterface):
-
- @staticmethod
- def axisinfo(unit, axis):
- 'return the unit AxisInfo'
- if unit=='date':
- majloc = dates.AutoDateLocator()
- majfmt = dates.AutoDateFormatter(majloc)
- return units.AxisInfo(
- majloc = majloc,
- majfmt = majfmt,
- label='date',
- )
- else: return None
-
- @staticmethod
- def convert(value, unit, axis):
- if units.ConversionInterface.is_numlike(value): return value
- return dates.date2num(value)
-
- @staticmethod
- def default_units(x, axis):
- 'return the default unit for x or None'
- return 'date'
-
-
-units.registry[datetime.date] = DateConverter()
-units.registry[datetime.datetime] = DateConverter()
Modified: branches/v1_0_maint/lib/matplotlib/sphinxext/plot_directive.py
===================================================================
--- branches/v1_0_maint/lib/matplotlib/sphinxext/plot_directive.py 2010-11-09 07:46:54 UTC (rev 8784)
+++ branches/v1_0_maint/lib/matplotlib/sphinxext/plot_directive.py 2010-11-09 15:23:25 UTC (rev 8785)
@@ -210,6 +210,7 @@
if plot_code is not None:
exec_code = 'import numpy as np; import matplotlib.pyplot as plt\n%s'%plot_code
+ #print 'CONTEXT', context, plot_context, exec_code
if context:
exec(exec_code, None, plot_context)
else:
@@ -279,6 +280,8 @@
basedir, fname = os.path.split(plot_path)
basename, ext = os.path.splitext(fname)
+
+
all_exists = True
# Look for single-figure output files first
@@ -288,7 +291,7 @@
all_exists = False
break
- if all_exists:
+ if not context and all_exists:
return 1
# Then look for multi-figure output files, assuming
@@ -307,7 +310,7 @@
else:
break
- if i != 0:
+ if not context and i != 0:
return i
# We didn't find the files, so build them
@@ -321,13 +324,17 @@
warnings.warn(s, PlotWarning)
return 0
- num_figs = run_savefig(plot_path, basename, tmpdir, destdir, formats)
+ if not all_exists:
+ num_figs = run_savefig(plot_path, basename, tmpdir, destdir, formats)
- if '__plot__' in sys.modules:
- del sys.modules['__plot__']
+ if '__plot__' in sys.modules:
+ del sys.modules['__plot__']
- return num_figs
+ return num_figs
+ else:
+ return 1
+
def _plot_directive(plot_path, basedir, function_name, plot_code, caption,
options, state_machine):
context = options.has_key('context')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|