You can subscribe to this list here.
| 2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(115) |
Aug
(120) |
Sep
(137) |
Oct
(170) |
Nov
(461) |
Dec
(263) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2008 |
Jan
(120) |
Feb
(74) |
Mar
(35) |
Apr
(74) |
May
(245) |
Jun
(356) |
Jul
(240) |
Aug
(115) |
Sep
(78) |
Oct
(225) |
Nov
(98) |
Dec
(271) |
| 2009 |
Jan
(132) |
Feb
(84) |
Mar
(74) |
Apr
(56) |
May
(90) |
Jun
(79) |
Jul
(83) |
Aug
(296) |
Sep
(214) |
Oct
(76) |
Nov
(82) |
Dec
(66) |
| 2010 |
Jan
(46) |
Feb
(58) |
Mar
(51) |
Apr
(77) |
May
(58) |
Jun
(126) |
Jul
(128) |
Aug
(64) |
Sep
(50) |
Oct
(44) |
Nov
(48) |
Dec
(54) |
| 2011 |
Jan
(68) |
Feb
(52) |
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
| 2018 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
|
From: <jd...@us...> - 2008-06-12 16:39:05
|
Revision: 5486
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5486&view=rev
Author: jdh2358
Date: 2008-06-12 09:38:47 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
some minor doc fixes and reorg, closed usetex review (thanks darren!)
Modified Paths:
--------------
trunk/matplotlib/doc/devel/outline.rst
trunk/matplotlib/doc/faq/environment_variables_faq.rst
trunk/matplotlib/doc/faq/howto_faq.rst
trunk/matplotlib/doc/faq/installing_faq.rst
trunk/matplotlib/doc/faq/troubleshooting_faq.rst
trunk/matplotlib/doc/users/customizing.rst
trunk/matplotlib/doc/users/event_handling.rst
Modified: trunk/matplotlib/doc/devel/outline.rst
===================================================================
--- trunk/matplotlib/doc/devel/outline.rst 2008-06-12 16:19:14 UTC (rev 5485)
+++ trunk/matplotlib/doc/devel/outline.rst 2008-06-12 16:38:47 UTC (rev 5486)
@@ -27,8 +27,8 @@
legends ? no author ?
animation John has author ?
collections ? no author ?
-text - mathtext Michael in review John
-text - usetex Darren in review John
+text - mathtext Michael accepted John
+text - usetex Darren accepted John
text - annotations John submitted ?
fonts et al Michael ? no author Darren
pyplot tut John submitted Eric
@@ -173,7 +173,7 @@
Validation is actually built into RcParams. This was done
just prior to development of the traited config, validation is done using
the mechanisms developed in rcsetup. For example::
-
+
>>> rcParams['a.b']=1
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
@@ -214,7 +214,7 @@
ValueError: Could not convert "" to boolean
-
+
#. DONE - You give the example::
import matplotlib.cbook as cbook
@@ -286,6 +286,8 @@
similarly to the :file: directive in html. Let me know if you don't want to
use the file directive.
+ - JDH: let's go with the file directive.
+
#. DONE - try and use internal reference links for every section and be
generous with the sections. Eg, I added a section headers and
internal linka for the postscript and unicode sections (we will
Modified: trunk/matplotlib/doc/faq/environment_variables_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/environment_variables_faq.rst 2008-06-12 16:19:14 UTC (rev 5485)
+++ trunk/matplotlib/doc/faq/environment_variables_faq.rst 2008-06-12 16:38:47 UTC (rev 5486)
@@ -22,10 +22,10 @@
This is the directory used to store user customizations to matplotlib, as
well as some caches to improve performance. If :envvar:`MPLCONFIGDIR` is not
defined, :file:`{HOME}/.matplotlib` is used by default.
-
+
.. _setting-linux-osx-environment-variables:
-Setting Environment Variables in Linux and OS-X
+Setting environment variables in Linux and OS-X
===============================================
To list the current value of :envvar:`PYTHONPATH`, which may be empty, try::
@@ -37,8 +37,8 @@
should be able to determine which by running at the command prompt::
echo $SHELL
-
+
BASH/KSH
--------
@@ -50,13 +50,14 @@
export PATH=~/bin:${PATH}
-The search order may be important to you, do you want `~/bin` to be searched
-first or last? To append to an existing environment variable::
+The search order may be important to you, do you want :file:`~/bin` to
+be searched first or last? To append to an existing environment
+variable::
export PATH=${PATH}:~/bin
To make your changes available in the future, add the commands to your
-`~/.bashrc` file.
+:file:`~/.bashrc` file.
CSH/TCSH
@@ -70,19 +71,19 @@
setenv PATH ~/bin:${PATH}
-The search order may be important to you, do you want `~/bin` to be searched
+The search order may be important to you, do you want :file:`~/bin` to be searched
first or last? To append to an existing environment variable::
setenv PATH ${PATH}:~/bin
To make your changes available in the future, add the commands to your
-`~/.cshrc` file.
+:file:`~/.cshrc` file.
.. _setting-windows-environment-variables:
-Setting Environment Variables in Windows
+Setting environment variables in windows
========================================
Go to the Windows start menu, select `Control Panel`, then select the `System`
icon, click the `Advanced` tab, and select the `Environment Variables`
-button. You can edit or add to the `user variables`.
\ No newline at end of file
+button. You can edit or add to the `user variables`.
Modified: trunk/matplotlib/doc/faq/howto_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/howto_faq.rst 2008-06-12 16:19:14 UTC (rev 5485)
+++ trunk/matplotlib/doc/faq/howto_faq.rst 2008-06-12 16:38:47 UTC (rev 5486)
@@ -1,28 +1,10 @@
-.._ howto-faq:
+.. _howto-faq:
*****
HOWTO
*****
-.. _locating-matplotlib-config-dir:
-Where is my .matplotlib directory?
-==================================
-
-Each user has a :file:`.matplotlib/` directory which may contain a
-:ref:`matplotlibrc <customizing-with-matplotlibrc-files>` file and various
-caches to improve matplotlib's performance. To locate your :file:`.matplotlib/`
-directory, use :func:`matplotlib.get_configdir`:
-
- >>> import matplotlib as mpl
- >>> mpl.get_configdir()
- '/home/darren/.matplotlib'
-
-This directory is generally located in your :envvar:`HOME` directory, but if
-you would like to use a configuration directory other than
-:file:`{HOME}/.matplotlib/`, you can do so by specifying the location in your
-:envvar:`MPLCONFIGDIR` environment variable.
-
.. _howto-ticks:
How do I configure the tick linewidths?
Modified: trunk/matplotlib/doc/faq/installing_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-12 16:19:14 UTC (rev 5485)
+++ trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-12 16:38:47 UTC (rev 5486)
@@ -4,6 +4,8 @@
Installation FAQ
******************
+
+
How do I report a compilation problem?
======================================
@@ -131,7 +133,7 @@
============ ===================================================================================================
-OS X Questions
+OS-X questions
==============
.. _easy-install-osx-egg:
Modified: trunk/matplotlib/doc/faq/troubleshooting_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/troubleshooting_faq.rst 2008-06-12 16:19:14 UTC (rev 5485)
+++ trunk/matplotlib/doc/faq/troubleshooting_faq.rst 2008-06-12 16:38:47 UTC (rev 5486)
@@ -4,7 +4,59 @@
Troubleshooting FAQ
===================
+.. _matplotlib-version:
+What is my matplotlib version?
+==============================
+
+To find out your matplotlib version number, import it and print the
+``__version__`` attribute::
+
+ >>> import matplotlib
+ >>> matplotlib.__version__
+ '0.98.0'
+
+
+.. _locating-matplotlib-install:
+
+Where is matplotlib installed?
+==============================
+
+You can find what directory matplotlib is installed in by importing it
+and printing the ``__file__`` attribute::
+
+ >>> import matplotlib
+ >>> matplotlib.__file__
+ '/home/jdhunter/dev/lib64/python2.5/site-packages/matplotlib/__init__.pyc'
+
+.. _locating-matplotlib-config-dir:
+
+Where is my .matplotlib directory?
+==================================
+
+Each user has a :file:`.matplotlib/` directory which may contain a
+:ref:`matplotlibrc <customizing-with-matplotlibrc-files>` file and various
+caches to improve matplotlib's performance. To locate your :file:`.matplotlib/`
+directory, use :func:`matplotlib.get_configdir`:
+
+ >>> import matplotlib as mpl
+ >>> mpl.get_configdir()
+ '/home/darren/.matplotlib'
+
+On unix like systems, this directory is generally located in your
+:envvar:`HOME` directory. On windows, it is in your documents and
+settings directory by default::
+
+ >>> import matplotlib
+ >>> mpl.get_configdir()
+ 'C:\\Documents and Settings\\jdhunter\\.matplotlib'
+
+If you would like to use a different configuration directory, you can
+do so by specifying the location in your :envvar:`MPLCONFIGDIR`
+environment variable -- see
+:ref:`setting-linux-osx-environment-variables`.
+
+
.. _reporting-problems:
How do I report a problem?
@@ -40,7 +92,7 @@
> python simple_plot.py --verbose-helpful > output.txt
-If you compiled matplotlib yourself, please also provide
+If you compiled matplotlib yourself, please also provide
* any changes you have made to ``setup.py`` or ``setupext.py``
* the output of::
@@ -50,7 +102,7 @@
The beginning of the build output contains lots of details about your
platform that are useful for the matplotlib developers to diagnose
- your problem.
+ your problem.
* your compiler version -- eg, ``gcc --version``
Modified: trunk/matplotlib/doc/users/customizing.rst
===================================================================
--- trunk/matplotlib/doc/users/customizing.rst 2008-06-12 16:19:14 UTC (rev 5485)
+++ trunk/matplotlib/doc/users/customizing.rst 2008-06-12 16:38:47 UTC (rev 5486)
@@ -20,18 +20,20 @@
specific customizations that you do not want to apply elsewhere.
2. :file:`.matplotlib/matplotlibrc`, for the user's default customizations. See
:ref:`locating-matplotlib-config-dir`.
-3. :file:`{INSTALL}/matplotlib/mpl-data/matplotlibrc`, where :file:`{INSTALL}`
- is something like :file:`/usr/lib/python2.5/site-packages` on Linux, and
- maybe :file:`C:\Python25\Lib\site-packages` on Windows. Every time you
- install matplotlib, this file will be overwritten, so if you want your
- customizations to be saved, please move this file to
- :file:`{HOME}/.matplotlib/matplotlibrc`.
+3. :file:`{INSTALL}/matplotlib/mpl-data/matplotlibrc`, where
+ :file:`{INSTALL}` is something like
+ :file:`/usr/lib/python2.5/site-packages` on Linux, and maybe
+ :file:`C:\Python25\Lib\site-packages` on Windows. Every time you
+ install matplotlib, this file will be overwritten, so if you want
+ your customizations to be saved, please move this file to you
+ :file:`.matplotlib` directory.
+
See below for a sample :ref:`matplotlibrc file<matplotlibrc-sample>`.
.. _customizing-with-dynamic-rc-settings:
-Dynamic rc Settings
+Dynamic rc settings
===================
You can also dynamically change the default rc settings in a python script or
Modified: trunk/matplotlib/doc/users/event_handling.rst
===================================================================
--- trunk/matplotlib/doc/users/event_handling.rst 2008-06-12 16:19:14 UTC (rev 5485)
+++ trunk/matplotlib/doc/users/event_handling.rst 2008-06-12 16:38:47 UTC (rev 5486)
@@ -141,7 +141,7 @@
``key``
the key pressed: None, chr(range(255), 'shift', 'win', or 'control'
-Draggable Rectangle Exercise
+Draggable rectangle exercise
----------------------------
Write draggable rectangle class that is initialized with a
@@ -332,7 +332,7 @@
.. _object-picking:
-Object Picking
+Object picking
==============
You can enable picking by setting the ``picker`` property of an
@@ -436,7 +436,7 @@
plt.show()
-Picking Exercise
+Picking exercise
----------------
Create a data set of 100 arrays of 1000 Gaussian random numbers and
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-06-12 16:19:45
|
Revision: 5485
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5485&view=rev
Author: jswhit
Date: 2008-06-12 09:19:14 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
rest-ifying docstrings
Modified Paths:
--------------
trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
Modified: trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
===================================================================
--- trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-06-12 15:27:12 UTC (rev 5484)
+++ trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-06-12 16:19:14 UTC (rev 5485)
@@ -112,11 +112,11 @@
and creates the coastline data structures in native map projection
coordinates.
- The desired projection is set with the projection keyword. Default is 'cyl'.
- Supported projections are:
+ The desired projection is set with the projection keyword. Default is ``cyl``.
+ Supported values for the projection keyword are:
============== ====================================================
- Key Value Description
+ Value Description
============== ====================================================
%(supported_projections)s
============== ====================================================
@@ -150,18 +150,18 @@
lat_0 center of desired map domain (in degrees).
============== ====================================================
- For 'sinu', 'moll', 'npstere', 'spstere', 'nplaea', 'splaea', 'nplaea',
- 'splaea', 'npaeqd', 'spaeqd' or 'robin', the values of
- llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat,width and height are ignored
+ For ``sinu``, ``moll``, ``npstere``, ``spstere``, ``nplaea``, ``splaea``,
+ ``npaeqd``, ``spaeqd`` or ``robin``, the values of
+ llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, width and height are ignored
(because either they are computed internally, or entire globe is
always plotted).
- For the cylindrical projections('cyl','merc' and 'mill'), the default is to use
+ For the cylindrical projections(``cyl``, ``merc`` and ``mill``), the default is to use
llcrnrlon=-180,llcrnrlat=-90, urcrnrlon=180 and urcrnrlat=90). For all other
- projections except 'ortho' and 'geos', either the lat/lon values of the
+ projections except ``ortho`` and ``geos``, either the lat/lon values of the
corners or width and height must be specified by the user.
- For 'ortho' and 'geos', the lat/lon values of the corners may be specified,
+ For ``ortho`` and ``geos``, the lat/lon values of the corners may be specified,
or the x/y values of the corners (llcrnrx,llcrnry,urcrnrx,urcrnry) in the
coordinate system of the global projection (with x=0,y=0 at the center
of the global projection). If the corners are not specified,
@@ -172,31 +172,31 @@
============== ====================================================
Keyword Description
============== ====================================================
- resolution resolution of boundary database to use. Can be 'c'
- (crude), 'l' (low), 'i' (intermediate), 'h' (high),
- 'f' (full) or None.
+ resolution resolution of boundary database to use. Can be ``c``
+ (crude), ``l`` (low), ``i`` (intermediate), ``h``
+ (high), ``f`` (full) or None.
If None, no boundary data will be read in (and
class methods such as drawcoastlines will raise an
if invoked).
Resolution drops off by roughly 80%% between datasets.
Higher res datasets are much slower to draw.
- Default 'c'. Coastline data is from the GSHHS
+ Default ``c``. Coastline data is from the GSHHS
(http://www.soest.hawaii.edu/wessel/gshhs/gshhs.html).
State, country and river datasets from the Generic
Mapping Tools (http://gmt.soest.hawaii.edu).
area_thresh coastline or lake with an area smaller than
area_thresh in km^2 will not be plotted.
Default 10000,1000,100,10,1 for resolution
- 'c','l','i','h','f'.
+ ``c``,``l``,``i``,``h``,``f``.
rsphere radius of the sphere used to define map projection
(default 6370997 meters, close to the arithmetic mean
radius of the earth). If given as a sequence, the
first two elements are interpreted as the radii
of the major and minor axes of an ellipsoid.
Note: sometimes an ellipsoid is specified by the
- major axis and an 'inverse flattening parameter (if).
- The minor axis (b) can be computed from the major axis
- (a) and the inverse flattening parameter using the
+ major axis and an inverse flattening parameter (if).
+ The minor axis (b) can be computed from the major
+ axis (a) and the inverse flattening parameter using
the formula if = a/(a-b).
suppress_ticks suppress automatic drawing of axis ticks and labels
in map projection coordinates. Default False,
@@ -210,94 +210,108 @@
the axes in meters using native map projection
coordinates.
anchor determines how map is placed in axes rectangle
- (passed to axes.set_aspect). Default is 'C',
+ (passed to axes.set_aspect). Default is ``C``,
which means map is centered.
Allowed values are
- ['C', 'SW', 'S', 'SE', 'E', 'NE', 'N', 'NW', 'W'].
+ ``C``, ``SW``, ``S``, ``SE``, ``E``, ``NE``,
+ ``N``, ``NW``, and ``W``.
ax set default axes instance
- (default None - pylab.gca() may be used
+ (default None - matplotlib.pyplot.gca() may be used
to get the current axes instance).
- If you don't want pylab to be imported,
+ If you don``t want matplotlib.pyplot to be imported,
you can either set this to a pre-defined axes
- instance, or use the 'ax' keyword in each Basemap
+ instance, or use the ``ax`` keyword in each Basemap
method call that does drawing. In the first case,
all Basemap method calls will draw to the same axes
instance. In the second case, you can draw to
different axes with the same Basemap instance.
- You can also use the 'ax' keyword in individual
+ You can also use the ``ax`` keyword in individual
method calls to selectively override the default
axes instance.
============== ====================================================
- The following parameters are map projection parameters which all default to
+ The following keywords are map projection parameters which all default to
None. Not all parameters are used by all projections, some are ignored.
- The module variable 'projection_params' is a dictionary which
+ The module variable ``projection_params`` is a dictionary which
lists which parameters apply to which projections.
- lat_ts - latitude of true scale for mercator projection, optional
- for stereographic projection.
+ ================ ====================================================
+ Keyword Description
+ ================ ====================================================
+ lat_ts latitude of true scale for mercator projection,
+ optional for stereographic projection.
+ lat_1 first standard parallel for lambert conformal,
+ albers equal area and equidistant conic.
+ Latitude of one of the two points on the projection
+ for oblique mercator. If lat_1 is not given, but
+ lat_0 is, lat_1 is set to lat_0 for lambert
+ conformal, albers equal area and equidistant conic.
+ lat_2 second standard parallel for lambert conformal,
+ albers equal area and equidistant conic.
+ Latitude of one of the two points on the projection
+ centerline for oblique mercator. If lat_2 is not
+ given it is set to lat_1 for lambert conformal,
+ albers equal area and equidistant conic.
+ lon_1 longitude of one of the two points on the projection
+ centerline for oblique mercator.
+ lon_2 longitude of one of the two points on the projection
+ centerline for oblique mercator.
+ no_rot only used by oblique mercator.
+ If set to True, the map projection coordinates will
+ not be rotated to true North. Default is False
+ (projection coordinates are automatically rotated).
+ lat_0 central latitude (y-axis origin) - used by all
+ projections, Must be equator for mercator projection.
+ lon_0 central meridian (x-axis origin) - used by all
+ projections.
+ boundinglat bounding latitude for pole-centered projections
+ (npstere,spstere,nplaea,splaea,npaeqd,spaeqd).
+ These projections are square regions centered
+ on the north or south pole.
+ The longitude lon_0 is at 6-o'clock, and the
+ latitude circle boundinglat is tangent to the edge
+ of the map at lon_0.
+ satellite_height height of satellite (in m) above equator -
+ only relevant for geostationary projections
+ (``geos``). Default 35,786 km.
+ ================ ====================================================
- lat_1 - first standard parallel for lambert conformal, albers
- equal area projection and equidistant conic projections. Latitude of one
- of the two points on the projection centerline for oblique mercator.
- If lat_1 is not given, but lat_0 is, lat_1 is set to lat_0 for
- lambert conformal, albers equal area and equidistant conic.
-
- lat_2 - second standard parallel for lambert conformal, albers
- equal area projection and equidistant conic projections. Latitude of one
- of the two points on the projection centerline for oblique mercator.
- If lat_2 is not given, it is set to lat_1 for
- lambert conformal, albers equal area and equidistant conic.
-
- lon_1 - longitude of one of the two points on the projection centerline
- for oblique mercator.
-
- lon_2 - longitude of one of the two points on the projection centerline
- for oblique mercator.
-
- no_rot - only used by oblique mercator. If set to True, the map projection
- coordinates will not be rotated to true North. Default is False (projection
- coordinates are automatically rotated).
-
- lat_0 - central latitude (y-axis origin) - used by all projections,
- Must be equator for mercator projection.
-
- lon_0 - central meridian (x-axis origin) - used by all projections,
-
- boundinglat - bounding latitude for pole-centered projections (npstere,spstere,
- nplaea,splaea,npaeqd,spaeqd). These projections are square regions centered
- on the north or south pole. The longitude lon_0 is at 6-o'clock, and the
- latitude circle boundinglat is tangent to the edge of the map at lon_0.
-
- satellite_height - height of satellite (in m) above equator -
- only relevant for geostationary projections ('geos'). Default 35,786 km.
-
Useful instance variables:
- projection - map projection. Print the module variable
- "supported_projections" to see a list.
+ ================ ====================================================
+ Variable Name Description
+ ================ ====================================================
+ projection map projection. Print the module variable
+ "supported_projections" to see a list of allowed
+ values.
+ aspect map aspect ratio
+ (size of y dimension / size of x dimension).
+ llcrnrlon longitude of lower left hand corner of the
+ selected map domain.
+ llcrnrlon latitude of lower left hand corner of the
+ selected map domain.
+ urcrnrlon longitude of upper right hand corner of the
+ selected map domain.
+ urcrnrlon latitude of upper right hand corner of the
+ selected map domain.
+ llcrnrx x value of lower left hand corner of the
+ selected map domain in map projection coordinates.
+ llcrnry y value of lower left hand corner of the
+ selected map domain in map projection coordinates.
+ urcrnrx x value of upper right hand corner of the
+ selected map domain in map projection coordinates.
+ urcrnry y value of upper right hand corner of the
+ selected map domain in map projection coordinates.
+ rmajor equatorial radius of ellipsoid used (in meters).
+ rminor polar radius of ellipsoid used (in meters).
+ resolution resolution of boundary dataset being used (``c``
+ for crude, ``l`` for low, etc.).
+ If None, no boundary dataset is associated with the
+ Basemap instance.
+ srs a string representing the 'spatial reference system'
+ for the map projection as defined by PROJ.4.
+ ================ ====================================================
- aspect - map aspect ratio (size of y dimension / size of x dimension).
-
- llcrnrlon - longitude of lower left hand corner of the desired map domain.
-
- llcrnrlon - latitude of lower left hand corner of the desired map domain.
-
- urcrnrlon - longitude of upper right hand corner of the desired map domain.
-
- urcrnrlon - latitude of upper right hand corner of the desired map domain.
-
- llcrnrx,llcrnry,urcrnrx,urcrnry - corners of map domain in projection coordinates.
-
- rmajor,rminor - equatorial and polar radii of ellipsoid used (in meters).
-
- resolution - resolution of boundary dataset being used ('c' for crude,
- 'l' for low, etc.). If None, no boundary dataset is associated with the
- Basemap instance.
-
- srs - a string representing the 'spatial reference system' for the map
- projection as defined by PROJ.4.
-
Example Usage:
>>> from mpl_toolkits.basemap import Basemap
@@ -322,8 +336,8 @@
>>> plt.show()
[this example (simpletest.py) plus many others can be found in the
- examples directory of source distribution. The "OO" version of this
- example (which does not use pylab) is called "simpletest_oo.py".]
+ examples directory of source distribution. The "OO" version of this
+ example (which does not use matplotlib.pyplot) is called "simpletest_oo.py".]
""" % locals()
# unsupported projection error message.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-06-12 15:27:28
|
Revision: 5484
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5484&view=rev
Author: jswhit
Date: 2008-06-12 08:27:12 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
add api docs
Modified Paths:
--------------
trunk/toolkits/basemap/doc/api/index.rst
Added Paths:
-----------
trunk/toolkits/basemap/doc/api/basemap_api.rst
Added: trunk/toolkits/basemap/doc/api/basemap_api.rst
===================================================================
--- trunk/toolkits/basemap/doc/api/basemap_api.rst (rev 0)
+++ trunk/toolkits/basemap/doc/api/basemap_api.rst 2008-06-12 15:27:12 UTC (rev 5484)
@@ -0,0 +1,11 @@
+**************************
+matplotlib basemap toolkit
+**************************
+
+
+:mod:`mpl_toolkits.basemap`
+=============================
+
+.. automodule:: mpl_toolkits.basemap
+ :members:
+ :undoc-members:
Modified: trunk/toolkits/basemap/doc/api/index.rst
===================================================================
--- trunk/toolkits/basemap/doc/api/index.rst 2008-06-12 14:48:18 UTC (rev 5483)
+++ trunk/toolkits/basemap/doc/api/index.rst 2008-06-12 15:27:12 UTC (rev 5484)
@@ -8,3 +8,5 @@
:Date: |today|
.. toctree::
+
+ basemap_api.rst
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ds...@us...> - 2008-06-12 14:48:56
|
Revision: 5483
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5483&view=rev
Author: dsdale
Date: 2008-06-12 07:48:18 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
responded to JDH review comments on usetex.rst
Modified Paths:
--------------
trunk/matplotlib/doc/devel/outline.rst
trunk/matplotlib/doc/faq/environment_variables_faq.rst
trunk/matplotlib/doc/faq/howto_faq.rst
trunk/matplotlib/doc/users/customizing.rst
trunk/matplotlib/doc/users/usetex.rst
Modified: trunk/matplotlib/doc/devel/outline.rst
===================================================================
--- trunk/matplotlib/doc/devel/outline.rst 2008-06-12 14:39:09 UTC (rev 5482)
+++ trunk/matplotlib/doc/devel/outline.rst 2008-06-12 14:48:18 UTC (rev 5483)
@@ -32,7 +32,7 @@
text - annotations John submitted ?
fonts et al Michael ? no author Darren
pyplot tut John submitted Eric
-configuration Darren preliminary ?
+configuration Darren submitted ?
win32 install Charlie ? no author Darren
os x install Charlie ? no author ?
linux install Darren has author ?
@@ -245,27 +245,48 @@
Review of :ref:`usetex-tutorial`:
-#. In the section on the ps distiller, you might mention that it is
- the rasterization which some users find objectionable, and the
- distiller pram (eg 6000) is a dpi setting for the rasterizer. Not
- everyone will immediately grasp the controversy surrounding dumping
- high res bitmaps into a ps file.
+#. DONE - In the section on the ps distiller, you might mention that it is the
+ rasterization which some users find objectionable, and the distiller pram
+ (eg 6000) is a dpi setting for the rasterizer. Not everyone will
+ immediately grasp the controversy surrounding dumping high res bitmaps into
+ a ps file.
-#. ``= Possible Hangups =`` - this is moin, not rest. I have fixed
- this already, just wanted to point it out. Also, for everything
- but top level chapters, I refer ``Upper lower`` for section
- titles, eg ``Possible hangups``.
+#. DONE - ``= Possible Hangups =`` - this is moin, not rest. I have
+ fixed this already, just wanted to point it out. Also, for everything but
+ top level chapters, I refer ``Upper lower`` for section titles, eg
+ ``Possible hangups``.
-#. in the troubleshooting section, could you add a FAQ showing how to
+#. DONE - in the troubleshooting section, could you add a FAQ showing how to
find their .matplotlib dir (matplotlib.get_data_path) and link to
- it. Also link to the PATH var and properly format
- ``text.latex.preample``. For the dirs, do we want `tex.cache` or
+ it.
+
+ I think you mean mpl.get_configdir. I added this to the faq/HOWTO, and
+ linked to it from usetex.rst and customizing.rst. I also added the
+ MPLCONFIGDIR environment variable to environment_variables_faq.rst.
+
+ DONE - Also link to the PATH var and properly format
+ ``text.latex.preample``.
+
+ DONE - For the dirs, do we want `tex.cache` or
``tex.cache``? I've been using the latter. We could use rest
specific markup for files and dirs, but I've been resisting goin
whle hog onthe markup... But we may eventually decide that is the
better choice.
-#. try and use internal reference links for every section and be
+ I think we should use the directive provided by sphinx::
+
+ :file:`tex.cache`
+
+ I don't think that looks too ugly in ascii, its clear what it means. If you
+ don't like it, I think we should use::
+
+ ``tex.cache``
+
+ which is formatted most
+ similarly to the :file: directive in html. Let me know if you don't want to
+ use the file directive.
+
+#. DONE - try and use internal reference links for every section and be
generous with the sections. Eg, I added a section headers and
internal linka for the postscript and unicode sections (we will
want to be able to refer people to these easily from FAQs and mail
@@ -277,3 +298,5 @@
==================
Looks good!
+
+Thanks!
Modified: trunk/matplotlib/doc/faq/environment_variables_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/environment_variables_faq.rst 2008-06-12 14:39:09 UTC (rev 5482)
+++ trunk/matplotlib/doc/faq/environment_variables_faq.rst 2008-06-12 14:48:18 UTC (rev 5483)
@@ -17,10 +17,17 @@
The list of directories that is added to Python's standard search list when
importing packages and modules
+.. envvar:: MPLCONFIGDIR
-Setting Environment Variables in Linux
-======================================
+ This is the directory used to store user customizations to matplotlib, as
+ well as some caches to improve performance. If :envvar:`MPLCONFIGDIR` is not
+ defined, :file:`{HOME}/.matplotlib` is used by default.
+
+.. _setting-linux-osx-environment-variables:
+Setting Environment Variables in Linux and OS-X
+===============================================
+
To list the current value of :envvar:`PYTHONPATH`, which may be empty, try::
echo $PYTHONPATH
@@ -71,6 +78,7 @@
To make your changes available in the future, add the commands to your
`~/.cshrc` file.
+.. _setting-windows-environment-variables:
Setting Environment Variables in Windows
========================================
Modified: trunk/matplotlib/doc/faq/howto_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/howto_faq.rst 2008-06-12 14:39:09 UTC (rev 5482)
+++ trunk/matplotlib/doc/faq/howto_faq.rst 2008-06-12 14:48:18 UTC (rev 5483)
@@ -4,6 +4,25 @@
HOWTO
*****
+.. _locating-matplotlib-config-dir:
+
+Where is my .matplotlib directory?
+==================================
+
+Each user has a :file:`.matplotlib/` directory which may contain a
+:ref:`matplotlibrc <customizing-with-matplotlibrc-files>` file and various
+caches to improve matplotlib's performance. To locate your :file:`.matplotlib/`
+directory, use :func:`matplotlib.get_configdir`:
+
+ >>> import matplotlib as mpl
+ >>> mpl.get_configdir()
+ '/home/darren/.matplotlib'
+
+This directory is generally located in your :envvar:`HOME` directory, but if
+you would like to use a configuration directory other than
+:file:`{HOME}/.matplotlib/`, you can do so by specifying the location in your
+:envvar:`MPLCONFIGDIR` environment variable.
+
.. _howto-ticks:
How do I configure the tick linewidths?
Modified: trunk/matplotlib/doc/users/customizing.rst
===================================================================
--- trunk/matplotlib/doc/users/customizing.rst 2008-06-12 14:39:09 UTC (rev 5482)
+++ trunk/matplotlib/doc/users/customizing.rst 2008-06-12 14:48:18 UTC (rev 5483)
@@ -4,6 +4,8 @@
Customizing matplotlib
**********************
+.. _customizing-with-matplotlibrc-files:
+
The matplotlibrc File
=====================
@@ -16,8 +18,8 @@
1. :file:`matplotlibrc` in the current working directory, usually used for
specific customizations that you do not want to apply elsewhere.
-2. :file:`{HOME}/.matplotlib/matplotlibrc`, for the user's default
- customizations
+2. :file:`.matplotlib/matplotlibrc`, for the user's default customizations. See
+ :ref:`locating-matplotlib-config-dir`.
3. :file:`{INSTALL}/matplotlib/mpl-data/matplotlibrc`, where :file:`{INSTALL}`
is something like :file:`/usr/lib/python2.5/site-packages` on Linux, and
maybe :file:`C:\Python25\Lib\site-packages` on Windows. Every time you
@@ -27,6 +29,8 @@
See below for a sample :ref:`matplotlibrc file<matplotlibrc-sample>`.
+.. _customizing-with-dynamic-rc-settings:
+
Dynamic rc Settings
===================
Modified: trunk/matplotlib/doc/users/usetex.rst
===================================================================
--- trunk/matplotlib/doc/users/usetex.rst 2008-06-12 14:39:09 UTC (rev 5482)
+++ trunk/matplotlib/doc/users/usetex.rst 2008-06-12 14:48:18 UTC (rev 5483)
@@ -79,38 +79,40 @@
In order to produce encapsulated postscript files that can be embedded in a new
LaTeX document, the default behavior of matplotlib is to distill the output,
which removes some postscript operators used by LaTeX that are illegal in an
-eps file. This step produces fonts which may be unacceptable to some users. One
-workaround is to to set ``ps.distiller.res`` to a higher value (perhaps 6000) in
-your rc settings. A better workaround, which requires Poppler_ or Xpdf_, can be
+eps file. This step produces results which may be unacceptable to some users,
+because the text is coarsely rasterized and converted to bitmaps, which are not
+scalable like standard postscript, and the text is not searchable. One
+workaround is to to set ``ps.distiller.res`` to a higher value (perhaps 6000)
+in your rc settings, which will produce larger files but may look better and
+scale reasonably. A better workaround, which requires Poppler_ or Xpdf_, can be
activated by changing the ``ps.usedistiller`` rc setting to ``xpdf``. This
-alternative produces postscript with text that can be edited in Adobe
-Illustrator, and searched text in pdf documents.
+alternative produces postscript without rasterizing text, so it scales
+properly, can be edited in Adobe Illustrator, and searched text in pdf
+documents.
.. _usetex-hangups:
Possible hangups
================
-* On Windows, the PATH environment variable may need to be modified to
- find the latex, dvipng and ghostscript executables. This is done by
- going to the control panel, selecting the "system" icon, selecting
- the "advanced" tab, and clicking the "environment variables" button
- (and people think Linux is complicated. Sheesh.) Select the PATH
- variable, and add the appropriate directories.
+* On Windows, the :envvar:`PATH` environment variable may need to be modified
+ to include the directories containing the latex, dvipng and ghostscript
+ executables. See :ref:`environment-variables` and
+ :ref:`setting-windows-environment-variables` for details.
-* Using MiKTeX with Computer Modern fonts, if you get odd -Agg and PNG
+* Using MiKTeX with Computer Modern fonts, if you get odd \*Agg and PNG
results, go to MiKTeX/Options and update your format files
-* The fonts look terrible on screen. You are probably running Mac OS,
- and there is some funny business with dvipng on the mac. Set
- text.dvipnghack : True in your matplotlibrc file.
+* The fonts look terrible on screen. You are probably running Mac OS, and there
+ is some funny business with older versions of dvipng on the mac. Set
+ ``text.dvipnghack : True`` in your matplotlibrc file.
* On Ubuntu and Gentoo, the base texlive install does not ship with
the type1cm package. You may need to install some of the extra
packages to get all the goodies that come bundled with other latex
distributions.
-* Some progress has been made so Matplotlib uses the dvi files
+* Some progress has been made so matplotlib uses the dvi files
directly for text layout. This allows latex to be used for text
layout with the pdf and svg backends, as well as the \*Agg and PS
backends. In the future, a latex installation may be the only
@@ -118,12 +120,15 @@
.. _usetex-troubleshooting:
-Trouble shooting
-================
+Troubleshooting
+===============
-* Try deleting `tex.cache` from your `~/.matplotlib` directory
+* Try deleting your :file:`.matplotlib/tex.cache` directory. If you don't know
+ where to find :file:`.matplotlib`, see
+ :ref:`locating-matplotlib-config-dir`.
-* Make sure LaTeX, dvipng and ghostscript are each working and on your PATH.
+* Make sure LaTeX, dvipng and ghostscript are each working and on your
+ :envvar:`PATH`.
* Make sure what you are trying to do is possible in a LaTeX document,
that your LaTeX syntax is valid and that you are using raw strings
@@ -133,7 +138,7 @@
upgrading Ghostscript_. If possible, please try upgrading to the
latest release before reporting problems to the list.
-* The text.latex.preample rc setting is not officially supported. This
+* The ``text.latex.preamble`` rc setting is not officially supported. This
option provides lots of flexibility, and lots of ways to cause
problems. Please disable this option before reporting problems to
the mailing list.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-06-12 14:39:12
|
Revision: 5482
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5482&view=rev
Author: jswhit
Date: 2008-06-12 07:39:09 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
move all of basemap.py in here so sphinx will find docstrings.
Spruce up docstrings, adding rest formatting.
Modified Paths:
--------------
trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
Modified: trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
===================================================================
--- trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-06-12 14:29:42 UTC (rev 5481)
+++ trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-06-12 14:39:09 UTC (rev 5482)
@@ -1,2 +1,3443 @@
-from basemap import __doc__, __version__
-from basemap import *
+"""
+Module for plotting data on maps with matplotlib.
+
+Contains the Basemap class (which does most of the
+heavy lifting), and the following functions:
+
+NetCDFFile: Read local and remote NetCDF datasets.
+
+interp: bilinear interpolation between rectilinear grids.
+
+shiftgrid: shifts global lat/lon grids east or west.
+
+addcyclic: Add cyclic (wraparound) point in longitude.
+
+num2date: convert from a numeric time value to a datetime object.
+
+date2num: convert from a datetime object to a numeric time value.
+"""
+from matplotlib import __version__ as _matplotlib_version
+from matplotlib.cbook import is_scalar, dedent
+# check to make sure matplotlib is not too old.
+_mpl_required_version = '0.98'
+if _matplotlib_version < _mpl_required_version:
+ msg = dedent("""
+ your matplotlib is too old - basemap requires version %s or
+ higher, you have version %s""" %
+ (_mpl_required_version,_matplotlib_version))
+ raise ImportError(msg)
+from matplotlib import rcParams, is_interactive, _pylab_helpers
+from matplotlib.collections import LineCollection
+from matplotlib.patches import Ellipse, Circle, Polygon
+from matplotlib.lines import Line2D
+from matplotlib.transforms import Bbox
+import pyproj, sys, os, math, dbflib
+from proj import Proj
+import numpy as np
+import numpy.ma as ma
+from shapelib import ShapeFile
+import _geoslib, pupynere, netcdftime
+
+# basemap data files now installed in lib/matplotlib/toolkits/basemap/data
+basemap_datadir = os.sep.join([os.path.dirname(__file__), 'data'])
+
+__version__ = '0.99'
+
+# supported map projections.
+_projnames = {'cyl' : 'Cylindrical Equidistant',
+ 'merc' : 'Mercator',
+ 'tmerc' : 'Transverse Mercator',
+ 'omerc' : 'Oblique Mercator',
+ 'mill' : 'Miller Cylindrical',
+ 'lcc' : 'Lambert Conformal',
+ 'laea' : 'Lambert Azimuthal Equal Area',
+ 'nplaea' : 'North-Polar Lambert Azimuthal',
+ 'splaea' : 'South-Polar Lambert Azimuthal',
+ 'eqdc' : 'Equidistant Conic',
+ 'aeqd' : 'Azimuthal Equidistant',
+ 'npaeqd' : 'North-Polar Azimuthal Equidistant',
+ 'spaeqd' : 'South-Polar Azimuthal Equidistant',
+ 'aea' : 'Albers Equal Area',
+ 'stere' : 'Stereographic',
+ 'npstere' : 'North-Polar Stereographic',
+ 'spstere' : 'South-Polar Stereographic',
+ 'cass' : 'Cassini-Soldner',
+ 'poly' : 'Polyconic',
+ 'ortho' : 'Orthographic',
+ 'geos' : 'Geostationary',
+ 'sinu' : 'Sinusoidal',
+ 'moll' : 'Mollweide',
+ 'robin' : 'Robinson',
+ 'gnom' : 'Gnomonic',
+ }
+supported_projections = []
+for _items in _projnames.iteritems():
+ supported_projections.append(" %-17s%-40s\n" % (_items))
+supported_projections = ''.join(supported_projections)
+
+# projection specific parameters.
+projection_params = {'cyl' : 'corners only (no width/height)',
+ 'merc' : 'corners plus lat_ts (no width/height)',
+ 'tmerc' : 'lon_0,lat_0',
+ 'omerc' : 'lon_0,lat_0,lat_1,lat_2,lon_1,lon_2,no_rot',
+ 'mill' : 'corners only (no width/height)',
+ 'lcc' : 'lon_0,lat_0,lat_1,lat_2',
+ 'laea' : 'lon_0,lat_0',
+ 'nplaea' : 'bounding_lat,lon_0,lat_0,no corners or width/height',
+ 'splaea' : 'bounding_lat,lon_0,lat_0,no corners or width/height',
+ 'eqdc' : 'lon_0,lat_0,lat_1,lat_2',
+ 'aeqd' : 'lon_0,lat_0',
+ 'npaeqd' : 'bounding_lat,lon_0,lat_0,no corners or width/height',
+ 'spaeqd' : 'bounding_lat,lon_0,lat_0,no corners or width/height',
+ 'aea' : 'lon_0,lat_0,lat_1',
+ 'stere' : 'lon_0,lat_0,lat_ts',
+ 'npstere' : 'bounding_lat,lon_0,lat_0,no corners or width/height',
+ 'spstere' : 'bounding_lat,lon_0,lat_0,no corners or width/height',
+ 'cass' : 'lon_0,lat_0',
+ 'poly' : 'lon_0,lat_0',
+ 'ortho' : 'lon_0,lat_0,llcrnrx,llcrnry,urcrnrx,urcrnry,no width/height',
+ 'geos' : 'lon_0,satellite_height,llcrnrx,llcrnry,urcrnrx,urcrnry,no width/height',
+ 'sinu' : 'lon_0,lat_0,no corners or width/height',
+ 'moll' : 'lon_0,lat_0,no corners or width/height',
+ 'robin' : 'lon_0,lat_0,no corners or width/height',
+ 'gnom' : 'lon_0,lat_0',
+ }
+
+# The __init__ docstring is pulled out here because it is so long;
+# Having it in the usual place makes it hard to get from the
+# __init__ argument list to the code that uses the arguments.
+_Basemap_init_doc = """
+
+ Sets up a basemap with specified map projection.
+ and creates the coastline data structures in native map projection
+ coordinates.
+
+ The desired projection is set with the projection keyword. Default is 'cyl'.
+ Supported projections are:
+
+ ============== ====================================================
+ Key Value Description
+ ============== ====================================================
+%(supported_projections)s
+ ============== ====================================================
+
+ For most map projections, the map projection region can either be
+ specified by setting these keywords:
+
+ ============== ====================================================
+ Keyword Description
+ ============== ====================================================
+ llcrnrlon longitude of lower left hand corner of the desired map
+ domain (degrees).
+ llcrnrlat latitude of lower left hand corner of the desired map
+ domain (degrees).
+ urcrnrlon longitude of upper right hand corner of the desired map
+ domain (degrees).
+ urcrnrlat latitude of upper right hand corner of the desired map
+ domain (degrees).
+ ============== ====================================================
+
+ or these
+
+ ============== ====================================================
+ Keyword Description
+ ============== ====================================================
+ width width of desired map domain in projection coordinates
+ (meters).
+ height height of desired map domain in projection coordinates
+ (meters).
+ lon_0 center of desired map domain (in degrees).
+ lat_0 center of desired map domain (in degrees).
+ ============== ====================================================
+
+ For 'sinu', 'moll', 'npstere', 'spstere', 'nplaea', 'splaea', 'nplaea',
+ 'splaea', 'npaeqd', 'spaeqd' or 'robin', the values of
+ llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat,width and height are ignored
+ (because either they are computed internally, or entire globe is
+ always plotted).
+
+ For the cylindrical projections('cyl','merc' and 'mill'), the default is to use
+ llcrnrlon=-180,llcrnrlat=-90, urcrnrlon=180 and urcrnrlat=90). For all other
+ projections except 'ortho' and 'geos', either the lat/lon values of the
+ corners or width and height must be specified by the user.
+
+ For 'ortho' and 'geos', the lat/lon values of the corners may be specified,
+ or the x/y values of the corners (llcrnrx,llcrnry,urcrnrx,urcrnry) in the
+ coordinate system of the global projection (with x=0,y=0 at the center
+ of the global projection). If the corners are not specified,
+ the entire globe is plotted.
+
+ Other keyword arguments:
+
+ ============== ====================================================
+ Keyword Description
+ ============== ====================================================
+ resolution resolution of boundary database to use. Can be 'c'
+ (crude), 'l' (low), 'i' (intermediate), 'h' (high),
+ 'f' (full) or None.
+ If None, no boundary data will be read in (and
+ class methods such as drawcoastlines will raise an
+ if invoked).
+ Resolution drops off by roughly 80%% between datasets.
+ Higher res datasets are much slower to draw.
+ Default 'c'. Coastline data is from the GSHHS
+ (http://www.soest.hawaii.edu/wessel/gshhs/gshhs.html).
+ State, country and river datasets from the Generic
+ Mapping Tools (http://gmt.soest.hawaii.edu).
+ area_thresh coastline or lake with an area smaller than
+ area_thresh in km^2 will not be plotted.
+ Default 10000,1000,100,10,1 for resolution
+ 'c','l','i','h','f'.
+ rsphere radius of the sphere used to define map projection
+ (default 6370997 meters, close to the arithmetic mean
+ radius of the earth). If given as a sequence, the
+ first two elements are interpreted as the radii
+ of the major and minor axes of an ellipsoid.
+ Note: sometimes an ellipsoid is specified by the
+ major axis and an 'inverse flattening parameter (if).
+ The minor axis (b) can be computed from the major axis
+ (a) and the inverse flattening parameter using the
+ the formula if = a/(a-b).
+ suppress_ticks suppress automatic drawing of axis ticks and labels
+ in map projection coordinates. Default False,
+ so parallels and meridians can be labelled instead.
+ If parallel or meridian labelling is requested
+ (using drawparallels and drawmeridians methods),
+ automatic tick labelling will be supressed even if
+ suppress_ticks=False. suppress_ticks=False
+ is useful if you want to use your own custom tick
+ formatter, or if you want to let matplotlib label
+ the axes in meters using native map projection
+ coordinates.
+ anchor determines how map is placed in axes rectangle
+ (passed to axes.set_aspect). Default is 'C',
+ which means map is centered.
+ Allowed values are
+ ['C', 'SW', 'S', 'SE', 'E', 'NE', 'N', 'NW', 'W'].
+ ax set default axes instance
+ (default None - pylab.gca() may be used
+ to get the current axes instance).
+ If you don't want pylab to be imported,
+ you can either set this to a pre-defined axes
+ instance, or use the 'ax' keyword in each Basemap
+ method call that does drawing. In the first case,
+ all Basemap method calls will draw to the same axes
+ instance. In the second case, you can draw to
+ different axes with the same Basemap instance.
+ You can also use the 'ax' keyword in individual
+ method calls to selectively override the default
+ axes instance.
+ ============== ====================================================
+
+ The following parameters are map projection parameters which all default to
+ None. Not all parameters are used by all projections, some are ignored.
+ The module variable 'projection_params' is a dictionary which
+ lists which parameters apply to which projections.
+
+ lat_ts - latitude of true scale for mercator projection, optional
+ for stereographic projection.
+
+ lat_1 - first standard parallel for lambert conformal, albers
+ equal area projection and equidistant conic projections. Latitude of one
+ of the two points on the projection centerline for oblique mercator.
+ If lat_1 is not given, but lat_0 is, lat_1 is set to lat_0 for
+ lambert conformal, albers equal area and equidistant conic.
+
+ lat_2 - second standard parallel for lambert conformal, albers
+ equal area projection and equidistant conic projections. Latitude of one
+ of the two points on the projection centerline for oblique mercator.
+ If lat_2 is not given, it is set to lat_1 for
+ lambert conformal, albers equal area and equidistant conic.
+
+ lon_1 - longitude of one of the two points on the projection centerline
+ for oblique mercator.
+
+ lon_2 - longitude of one of the two points on the projection centerline
+ for oblique mercator.
+
+ no_rot - only used by oblique mercator. If set to True, the map projection
+ coordinates will not be rotated to true North. Default is False (projection
+ coordinates are automatically rotated).
+
+ lat_0 - central latitude (y-axis origin) - used by all projections,
+ Must be equator for mercator projection.
+
+ lon_0 - central meridian (x-axis origin) - used by all projections,
+
+ boundinglat - bounding latitude for pole-centered projections (npstere,spstere,
+ nplaea,splaea,npaeqd,spaeqd). These projections are square regions centered
+ on the north or south pole. The longitude lon_0 is at 6-o'clock, and the
+ latitude circle boundinglat is tangent to the edge of the map at lon_0.
+
+ satellite_height - height of satellite (in m) above equator -
+ only relevant for geostationary projections ('geos'). Default 35,786 km.
+
+ Useful instance variables:
+
+ projection - map projection. Print the module variable
+ "supported_projections" to see a list.
+
+ aspect - map aspect ratio (size of y dimension / size of x dimension).
+
+ llcrnrlon - longitude of lower left hand corner of the desired map domain.
+
+ llcrnrlon - latitude of lower left hand corner of the desired map domain.
+
+ urcrnrlon - longitude of upper right hand corner of the desired map domain.
+
+ urcrnrlon - latitude of upper right hand corner of the desired map domain.
+
+ llcrnrx,llcrnry,urcrnrx,urcrnry - corners of map domain in projection coordinates.
+
+ rmajor,rminor - equatorial and polar radii of ellipsoid used (in meters).
+
+ resolution - resolution of boundary dataset being used ('c' for crude,
+ 'l' for low, etc.). If None, no boundary dataset is associated with the
+ Basemap instance.
+
+ srs - a string representing the 'spatial reference system' for the map
+ projection as defined by PROJ.4.
+
+ Example Usage:
+
+ >>> from mpl_toolkits.basemap import Basemap
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> import matplotlib.mlab as mlab
+ >>> # read in topo data (on a regular lat/lon grid)
+ >>> etopo = mlab.load('etopo20data.gz')
+ >>> lons = mlab.load('etopo20lons.gz')
+ >>> lats = mlab.load('etopo20lats.gz')
+ >>> # create Basemap instance for Robinson projection.
+ >>> m = Basemap(projection='robin',lon_0=0.5*(lons[0]+lons[-1]))
+ >>> # compute native map projection coordinates for lat/lon grid.
+ >>> x, y = m(*np.meshgrid(lons,lats))
+ >>> # make filled contour plot.
+ >>> cs = m.contourf(x,y,etopo,30,cmap=plt.cm.jet)
+ >>> m.drawcoastlines() # draw coastlines
+ >>> m.drawmapboundary() # draw a line around the map region
+ >>> m.drawparallels(np.arange(-90.,120.,30.),labels=[1,0,0,0]) # draw parallels
+ >>> m.drawmeridians(np.arange(0.,420.,60.),labels=[0,0,0,1]) # draw meridians
+ >>> plt.title('Robinson Projection') # add a title
+ >>> plt.show()
+
+ [this example (simpletest.py) plus many others can be found in the
+ examples directory of source distribution. The "OO" version of this
+ example (which does not use pylab) is called "simpletest_oo.py".]
+""" % locals()
+
+# unsupported projection error message.
+_unsupported_projection = ["'%s' is an unsupported projection.\n"]
+_unsupported_projection.append("The supported projections are:\n")
+_unsupported_projection.append(supported_projections)
+_unsupported_projection = ''.join(_unsupported_projection)
+
+def _validated_ll(param, name, minval, maxval):
+ param = float(param)
+ if param > maxval or param < minval:
+ raise ValueError('%s must be between %f and %f degrees' %
+ (name, minval, maxval))
+ return param
+
+def _insert_validated(d, param, name, minval, maxval):
+ if param is not None:
+ d[name] = _validated_ll(param, name, minval, maxval)
+
+class Basemap(object):
+
+ def __init__(self, llcrnrlon=None, llcrnrlat=None,
+ urcrnrlon=None, urcrnrlat=None,
+ llcrnrx=None, llcrnry=None,
+ urcrnrx=None, urcrnry=None,
+ width=None, height=None,
+ projection='cyl', resolution='c',
+ area_thresh=None, rsphere=6370997.0,
+ lat_ts=None,
+ lat_1=None, lat_2=None,
+ lat_0=None, lon_0=None,
+ lon_1=None, lon_2=None,
+ no_rot=False,
+ suppress_ticks=True,
+ satellite_height=35786000,
+ boundinglat=None,
+ anchor='C',
+ ax=None):
+ # docstring is added after __init__ method definition
+
+ # where to put plot in figure (default is 'C' or center)
+ self.anchor = anchor
+ # map projection.
+ self.projection = projection
+
+ # set up projection parameter dict.
+ projparams = {}
+ projparams['proj'] = projection
+ try:
+ if rsphere[0] > rsphere[1]:
+ projparams['a'] = rsphere[0]
+ projparams['b'] = rsphere[1]
+ else:
+ projparams['a'] = rsphere[1]
+ projparams['b'] = rsphere[0]
+ except:
+ if projection == 'tmerc':
+ # use bR_a instead of R because of obscure bug
+ # in proj4 for tmerc projection.
+ projparams['bR_a'] = rsphere
+ else:
+ projparams['R'] = rsphere
+ # set units to meters.
+ projparams['units']='m'
+ # check for sane values of lon_0, lat_0, lat_ts, lat_1, lat_2
+ _insert_validated(projparams, lat_0, 'lat_0', -90, 90)
+ _insert_validated(projparams, lat_1, 'lat_1', -90, 90)
+ _insert_validated(projparams, lat_2, 'lat_2', -90, 90)
+ _insert_validated(projparams, lat_ts, 'lat_ts', -90, 90)
+ _insert_validated(projparams, lon_0, 'lon_0', -360, 720)
+ _insert_validated(projparams, lon_1, 'lon_1', -360, 720)
+ _insert_validated(projparams, lon_2, 'lon_2', -360, 720)
+ if projection == 'geos':
+ projparams['h'] = satellite_height
+ # check for sane values of projection corners.
+ using_corners = (None not in [llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat])
+ if using_corners:
+ self.llcrnrlon = _validated_ll(llcrnrlon, 'llcrnrlon', -360, 720)
+ self.urcrnrlon = _validated_ll(urcrnrlon, 'urcrnrlon', -360, 720)
+ self.llcrnrlat = _validated_ll(llcrnrlat, 'llcrnrlat', -90, 90)
+ self.urcrnrlat = _validated_ll(urcrnrlat, 'urcrnrlat', -90, 90)
+
+ # for each of the supported projections,
+ # compute lat/lon of domain corners
+ # and set values in projparams dict as needed.
+
+ if projection in ['lcc', 'eqdc', 'aea']:
+ # if lat_0 is given, but not lat_1,
+ # set lat_1=lat_0
+ if lat_1 is None and lat_0 is not None:
+ lat_1 = lat_0
+ projparams['lat_1'] = lat_1
+ if lat_1 is None or lon_0 is None:
+ raise ValueError('must specify lat_1 or lat_0 and lon_0 for %s basemap (lat_2 is optional)' % _projnames[projection])
+ if lat_2 is None:
+ projparams['lat_2'] = lat_1
+ if not using_corners:
+ if width is None or height is None:
+ raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters'
+ if lon_0 is None or lat_0 is None:
+ raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region'
+ llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams)
+ self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat
+ self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat
+ elif projection == 'stere':
+ if lat_0 is None or lon_0 is None:
+ raise ValueError, 'must specify lat_0 and lon_0 for Stereographic basemap (lat_ts is optional)'
+ if not using_corners:
+ if width is None or height is None:
+ raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters'
+ if lon_0 is None or lat_0 is None:
+ raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region'
+ llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams)
+ self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat
+ self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat
+ elif projection in ['spstere', 'npstere',
+ 'splaea', 'nplaea',
+ 'spaeqd', 'npaeqd']:
+ if boundinglat is None or lon_0 is None:
+ raise ValueError('must specify boundinglat and lon_0 for %s basemap' % _projnames[projection])
+ if projection[0] == 's':
+ sgn = -1
+ else:
+ sgn = 1
+ rootproj = projection[2:]
+ projparams['proj'] = rootproj
+ if rootproj == 'stere':
+ projparams['lat_ts'] = sgn * 90.
+ projparams['lat_0'] = sgn * 90.
+ self.llcrnrlon = lon_0 - sgn*45.
+ self.urcrnrlon = lon_0 + sgn*135.
+ proj = pyproj.Proj(projparams)
+ x,y = proj(lon_0,boundinglat)
+ lon,self.llcrnrlat = proj(math.sqrt(2.)*y,0.,inverse=True)
+ self.urcrnrlat = self.llcrnrlat
+ if width is not None or height is not None:
+ print 'warning: width and height keywords ignored for %s projection' % _projnames[projection]
+ elif projection == 'laea':
+ if lat_0 is None or lon_0 is None:
+ raise ValueError, 'must specify lat_0 and lon_0 for Lambert Azimuthal basemap'
+ if not using_corners:
+ if width is None or height is None:
+ raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters'
+ if lon_0 is None or lat_0 is None:
+ raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region'
+ llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams)
+ self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat
+ self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat
+ elif projection == 'merc':
+ if lat_ts is None:
+ raise ValueError, 'must specify lat_ts for Mercator basemap'
+ # clip plot region to be within -89.99S to 89.99N
+ # (mercator is singular at poles)
+ if not using_corners:
+ llcrnrlon = -180.
+ llcrnrlat = -90.
+ urcrnrlon = 180
+ urcrnrlat = 90.
+ if llcrnrlat < -89.99: llcrnrlat = -89.99
+ if llcrnrlat > 89.99: llcrnrlat = 89.99
+ if urcrnrlat < -89.99: urcrnrlat = -89.99
+ if urcrnrlat > 89.99: urcrnrlat = 89.99
+ self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat
+ self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat
+ if width is not None or height is not None:
+ print 'warning: width and height keywords ignored for %s projection' % self.projection
+ elif projection in ['tmerc','gnom','cass','poly'] :
+ if lat_0 is None or lon_0 is None:
+ raise ValueError, 'must specify lat_0 and lon_0 for Transverse Mercator, Gnomonic, Cassini-Soldnerr Polyconic basemap'
+ if not using_corners:
+ if width is None or height is None:
+ raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters'
+ if lon_0 is None or lat_0 is None:
+ raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region'
+ llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams)
+ self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat
+ self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat
+ elif projection == 'ortho':
+ if not projparams.has_key('R'):
+ raise ValueError, 'orthographic projection only works for perfect spheres - not ellipsoids'
+ if lat_0 is None or lon_0 is None:
+ raise ValueError, 'must specify lat_0 and lon_0 for Orthographic basemap'
+ if width is not None or height is not None:
+ print 'warning: width and height keywords ignored for %s projection' % self.projection
+ if not using_corners:
+ llcrnrlon = -180.
+ llcrnrlat = -90.
+ urcrnrlon = 180
+ urcrnrlat = 90.
+ self._fulldisk = True
+ else:
+ self._fulldisk = False
+ self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat
+ self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat
+ # FIXME: won't work for points exactly on equator??
+ if np.abs(lat_0) < 1.e-2: lat_0 = 1.e-2
+ projparams['lat_0'] = lat_0
+ elif projection == 'geos':
+ if lon_0 is None:
+ raise ValueError, 'must specify lon_0 for Geostationary basemap'
+ if width is not None or height is not None:
+ print 'warning: width and height keywords ignored for %s projection' % self.projection
+ if not using_corners:
+ llcrnrlon = -180.
+ llcrnrlat = -90.
+ urcrnrlon = 180
+ urcrnrlat = 90.
+ self._fulldisk = True
+ else:
+ self._fulldisk = False
+ self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat
+ self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat
+ elif projection in ['moll','robin','sinu']:
+ if lon_0 is None:
+ raise ValueError, 'must specify lon_0 for Robinson, Mollweide, or Sinusoidal basemap'
+ if width is not None or height is not None:
+ print 'warning: width and height keywords ignored for %s projection' % self.projection
+ llcrnrlon = -180.
+ llcrnrlat = -90.
+ urcrnrlon = 180
+ urcrnrlat = 90.
+ self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat
+ self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat
+ elif projection == 'omerc':
+ if lat_1 is None or lon_1 is None or lat_2 is None or lon_2 is None:
+ raise ValueError, 'must specify lat_1,lon_1 and lat_2,lon_2 for Oblique Mercator basemap'
+ projparams['lat_1'] = lat_1
+ projparams['lon_1'] = lon_1
+ projparams['lat_2'] = lat_2
+ projparams['lon_2'] = lon_2
+ projparams['lat_0'] = lat_0
+ if no_rot:
+ projparams['no_rot']=''
+ #if not using_corners:
+ # raise ValueError, 'cannot specify map region with width and height keywords for this projection, please specify lat/lon values of corners'
+ if not using_corners:
+ if width is None or height is None:
+ raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters'
+ if lon_0 is None or lat_0 is None:
+ raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region'
+ llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams)
+ self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat
+ self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat
+ elif projection == 'aeqd':
+ if lat_0 is None or lon_0 is None:
+ raise ValueError, 'must specify lat_0 and lon_0 for Azimuthal Equidistant basemap'
+ if not using_corners:
+ if width is None or height is None:
+ raise ValueError, 'must either specify lat/lon values of corners (llcrnrlon,llcrnrlat,ucrnrlon,urcrnrlat) in degrees or width and height in meters'
+ if lon_0 is None or lat_0 is None:
+ raise ValueError, 'must specify lon_0 and lat_0 when using width, height to specify projection region'
+ llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat = _choosecorners(width,height,**projparams)
+ self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat
+ self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat
+ elif projection == 'mill':
+ if not using_corners:
+ llcrnrlon = -180.
+ llcrnrlat = -90.
+ urcrnrlon = 180
+ urcrnrlat = 90.
+ self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat
+ self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat
+ if width is not None or height is not None:
+ print 'warning: width and height keywords ignored for %s projection' % self.projection
+ elif projection == 'cyl':
+ if not using_corners:
+ llcrnrlon = -180.
+ llcrnrlat = -90.
+ urcrnrlon = 180
+ urcrnrlat = 90.
+ self.llcrnrlon = llcrnrlon; self.llcrnrlat = llcrnrlat
+ self.urcrnrlon = urcrnrlon; self.urcrnrlat = urcrnrlat
+ if width is not None or height is not None:
+ print 'warning: width and height keywords ignored for %s projection' % self.projection
+ else:
+ raise ValueError(_unsupported_projection % projection)
+
+ # initialize proj4
+ proj = Proj(projparams,self.llcrnrlon,self.llcrnrlat,self.urcrnrlon,self.urcrnrlat)
+
+ # make sure axis ticks are suppressed.
+ self.noticks = suppress_ticks
+
+ # make Proj instance a Basemap instance variable.
+ self.projtran = proj
+ # copy some Proj attributes.
+ atts = ['rmajor','rminor','esq','flattening','ellipsoid','projparams']
+ for att in atts:
+ self.__dict__[att] = proj.__dict__[att]
+ # these only exist for geostationary projection.
+ if hasattr(proj,'_width'):
+ self.__dict__['_width'] = proj.__dict__['_width']
+ if hasattr(proj,'_height'):
+ self.__dict__['_height'] = proj.__dict__['_height']
+ # spatial reference string (useful for georeferencing output
+ # images with gdal_translate).
+ if hasattr(self,'_proj4'):
+ self.srs = proj._proj4.srs
+ else:
+ pjargs = []
+ for key,value in self.projparams.iteritems():
+ # 'cyl' projection translates to 'eqc' in PROJ.4
+ if projection == 'cyl' and key == 'proj':
+ value = 'eqc'
+ # ignore x_0 and y_0 settings for 'cyl' projection
+ # (they are not consistent with what PROJ.4 uses)
+ elif projection == 'cyl' and key in ['x_0','y_0']:
+ continue
+ pjargs.append('+'+key+"="+str(value)+' ')
+ self.srs = ''.join(pjargs)
+ # set instance variables defining map region.
+ self.xmin = proj.xmin
+ self.xmax = proj.xmax
+ self.ymin = proj.ymin
+ self.ymax = proj.ymax
+ if projection == 'cyl':
+ self.aspect = (self.urcrnrlat-self.llcrnrlat)/(self.urcrnrlon-self.llcrnrlon)
+ else:
+ self.aspect = (proj.ymax-proj.ymin)/(proj.xmax-proj.xmin)
+ if projection in ['geos','ortho'] and \
+ None not in [llcrnrx,llcrnry,urcrnrx,urcrnry]:
+ self.llcrnrx = llcrnrx+0.5*proj.xmax
+ self.llcrnry = llcrnry+0.5*proj.ymax
+ self.urcrnrx = urcrnrx+0.5*proj.xmax
+ self.urcrnry = urcrnry+0.5*proj.ymax
+ self._fulldisk = False
+ else:
+ self.llcrnrx = proj.llcrnrx
+ self.llcrnry = proj.llcrnry
+ self.urcrnrx = proj.urcrnrx
+ self.urcrnry = proj.urcrnry
+ # set min/max lats for projection domain.
+ if projection in ['mill','cyl','merc']:
+ self.latmin = self.llcrnrlat
+ self.latmax = self.urcrnrlat
+ elif projection in ['ortho','geos','moll','robin','sinu']:
+ self.latmin = -90.
+ self.latmax = 90.
+ else:
+ lons, lats = self.makegrid(101,101)
+ self.latmin = lats.min()
+ self.latmax = lats.max()
+
+ # if ax == None, pyplot.gca may be used.
+ self.ax = ax
+ self.lsmask = None
+
+ # set defaults for area_thresh.
+ self.resolution = resolution
+ if area_thresh is None and resolution is not None:
+ if resolution == 'c':
+ area_thresh = 10000.
+ elif resolution == 'l':
+ area_thresh = 1000.
+ elif resolution == 'i':
+ area_thresh = 100.
+ elif resolution == 'h':
+ area_thresh = 10.
+ elif resolution == 'f':
+ area_thresh = 1.
+ else:
+ raise ValueError, "boundary resolution must be one of 'c','l','i','h' or 'f'"
+ self.area_thresh = area_thresh
+ # define map boundary polygon (in lat/lon coordinates)
+ self._boundarypolyll, self._boundarypolyxy = self._getmapboundary()
+ # read in coastline polygons, only keeping those that
+ # intersect map boundary polygon.
+ if self.resolution is not None:
+ self.coastsegs, self.coastpolygontypes = self._readboundarydata('gshhs')
+ # reformat for use in matplotlib.patches.Polygon.
+ self.coastpolygons = []
+ # also, split coastline segments that jump across entire plot.
+ coastsegs = []
+ for seg in self.coastsegs:
+ x, y = zip(*seg)
+ self.coastpolygons.append((x,y))
+ x = np.array(x,np.float64); y = np.array(y,np.float64)
+ xd = (x[1:]-x[0:-1])**2
+ yd = (y[1:]-y[0:-1])**2
+ dist = np.sqrt(xd+yd)
+ split = dist > 5000000.
+ if np.sum(split) and self.projection not in ['merc','cyl','mill']:
+ ind = (np.compress(split,np.squeeze(split*np.indices(xd.shape)))+1).tolist()
+ iprev = 0
+ ind.append(len(xd))
+ for i in ind:
+ # don't add empty lists.
+ if len(range(iprev,i)):
+ coastsegs.append(zip(x[iprev:i],y[iprev:i]))
+ iprev = i
+ else:
+ coastsegs.append(seg)
+ self.coastsegs = coastsegs
+ # set __init__'s docstring
+ __init__.__doc__ = _Basemap_init_doc
+
+ def __call__(self,x,y,inverse=False):
+ """
+ Calling a Basemap class instance with the arguments lon, lat will
+ convert lon/lat (in degrees) to x/y native map projection
+ coordinates (in meters). If optional keyword 'inverse' is
+ True (default is False), the inverse transformation from x/y
+ to lon/lat is performed.
+
+ For cylindrical equidistant projection ('cyl'), this
+ does nothing (i.e. x,y == lon,lat).
+
+ For non-cylindrical projections, the inverse transformation
+ always returns longitudes between -180 and 180 degrees. For
+ cylindrical projections (self.projection == 'cyl','mill' or 'merc')
+ the inverse transformation will return longitudes between
+ self.llcrnrlon and self.llcrnrlat.
+
+ input arguments lon, lat can be either scalar floats or N arrays.
+ """
+ return self.projtran(x,y,inverse=inverse)
+
+ def makegrid(self,nx,ny,returnxy=False):
+ """
+ return arrays of shape (ny,nx) containing lon,lat coordinates of
+ an equally spaced native projection grid.
+
+ if returnxy = True, the x,y values of the grid are returned also.
+ """
+ return self.projtran.makegrid(nx,ny,returnxy=returnxy)
+
+ def _readboundarydata(self,name):
+ """
+ read boundary data, clip to map projection region.
+ """
+ msg = dedent("""
+ Unable to open boundary dataset file. Only the 'crude', 'low',
+ 'intermediate' and 'high' resolution datasets are installed by default.
+ If you are requesting a 'full' resolution dataset, you may need to
+ download and install those files separately
+ (see the basemap README for details).""")
+ try:
+ bdatfile = open(os.path.join(basemap_datadir,name+'_'+self.resolution+'.dat'),'rb')
+ bdatmetafile = open(os.path.join(basemap_datadir,name+'meta_'+self.resolution+'.dat'),'r')
+ except:
+ raise IOError, msg
+ polygons = []
+ polygon_types = []
+ # coastlines are polygons, other boundaries are line segments.
+ if name == 'gshhs':
+ Shape = _geoslib.Polygon
+ else:
+ Shape = _geoslib.LineString
+ # see if map projection region polygon contains a pole.
+ NPole = _geoslib.Point(self(0.,90.))
+ SPole = _geoslib.Point(self(0.,-90.))
+ boundarypolyxy = self._boundarypolyxy
+ boundarypolyll = self._boundarypolyll
+ hasNP = NPole.within(boundarypolyxy)
+ hasSP = SPole.within(boundarypolyxy)
+ containsPole = hasNP or hasSP
+ # these projections cannot cross pole.
+ if containsPole and\
+ self.projection in ['merc','mill','cyl','robin','moll','sinu','geos']:
+ #self.projection in ['tmerc','omerc','cass','merc','mill','cyl','robin','moll','sinu','geos']:
+ raise ValueError('%s projection cannot cross pole'%(self.projection))
+ # make sure orthographic projection has containsPole=True
+ # we will compute the intersections in stereographic
+ # coordinates, then transform to orthographic.
+ if self.projection == 'ortho' and name == 'gshhs':
+ containsPole = True
+ lon_0=self.projparams['lon_0']
+ lat_0=self.projparams['lat_0']
+ re = self.projparams['R']
+ # center of stereographic projection restricted to be
+ # nearest one of 6 points on the sphere (every 90 deg lat/lon).
+ lon0 = 90.*(np.around(lon_0/90.))
+ lat0 = 90.*(np.around(lat_0/90.))
+ if np.abs(int(lat0)) == 90: lon0=0.
+ maptran = pyproj.Proj(proj='stere',lon_0=lon0,lat_0=lat0,R=re)
+ # boundary polygon for orthographic projection
+ # in stereographic coorindates.
+ b = self._boundarypolyll.boundary
+ blons = b[:,0]; blats = b[:,1]
+ b[:,0], b[:,1] = maptran(blons, blats)
+ boundarypolyxy = _geoslib.Polygon(b)
+ for line in bdatmetafile:
+ linesplit = line.split()
+ area = float(linesplit[1])
+ south = float(linesplit[3])
+ north = float(linesplit[4])
+ if area < 0.: area = 1.e30
+ useit = self.latmax>=south and self.latmin<=north and area>self.area_thresh
+ if useit:
+ type = int(linesplit[0])
+ npts = int(linesplit[2])
+ offsetbytes = int(linesplit[5])
+ bytecount = int(linesplit[6])
+ bdatfile.seek(offsetbytes,0)
+ # read in binary string convert into an npts by 2
+ # numpy array (first column is lons, second is lats).
+ polystring = bdatfile.read(bytecount)
+ # binary data is little endian.
+ b = np.array(np.fromstring(polystring,dtype='<f4'),'f8')
+ b.shape = (npts,2)
+ b2 = b.copy()
+ # if map boundary polygon is a valid one in lat/lon
+ # coordinates (i.e. it does not contain either pole),
+ # the intersections of the boundary geometries
+ # and the map projection region can be computed before
+ # transforming the boundary geometry to map projection
+ # coordinates (this saves time, especially for small map
+ # regions and high-resolution boundary geometries).
+ if not containsPole:
+ # close Antarctica.
+ if name == 'gshhs' and south < -68 and area > 10000:
+ lons = b[:,0]
+ lats = b[:,1]
+ lons2 = lons[:-2][::-1]
+ lats2 = lats[:-2][::-1]
+ lons1 = lons2 - 360.
+ lons3 = lons2 + 360.
+ lons = lons1.tolist()+lons2.tolist()+lons3.tolist()
+ lats = lats2.tolist()+lats2.tolist()+lats2.tolist()
+ lonstart,latstart = lons[0], lats[0]
+ lonend,latend = lons[-1], lats[-1]
+ lons.insert(0,lonstart)
+ lats.insert(0,-90.)
+ lons.append(lonend)
+ lats.append(-90.)
+ b = np.empty((len(lons),2),np.float64)
+ b[:,0] = lons; b[:,1] = lats
+ poly = _geoslib.Polygon(b)
+ antart = True
+ else:
+ poly = Shape(b)
+ antart = False
+ # create duplicate polygons shifted by -360 and +360
+ # (so as to properly treat polygons that cross
+ # Greenwich meridian).
+ if not antart:
+ b2[:,0] = b[:,0]-360
+ poly1 = Shape(b2)
+ b2[:,0] = b[:,0]+360
+ poly2 = Shape(b2)
+ polys = [poly1,poly,poly2]
+ else: # Antartica already extends from -360 to +720.
+ polys = [poly]
+ for poly in polys:
+ # if polygon instersects map projection
+ # region, process it.
+ if poly.intersects(boundarypolyll):
+ # if geometry intersection calculation fails,
+ # just move on.
+ try:
+ geoms = poly.intersection(boundarypolyll)
+ except:
+ continue
+ # iterate over geometries in intersection.
+ for psub in geoms:
+ # only coastlines are polygons,
+ # which have a 'boundary' attribute.
+ # otherwise, use 'coords' attribute
+ # to extract coordinates.
+ b = psub.boundary
+ blons = b[:,0]; blats = b[:,1]
+ # transformation from lat/lon to
+ # map projection coordinates.
+ bx, by = self(blons, blats)
+ polygons.append(zip(bx,by))
+ polygon_types.append(type)
+ # if map boundary polygon is not valid in lat/lon
+ # coordinates, compute intersection between map
+ # projection region and boundary geometries in map
+ # projection coordinates.
+ else:
+ # transform coordinates from lat/lon
+ # to map projection coordinates.
+ # special case for ortho, compute coastline polygon
+ # vertices in stereographic coords.
+ if name == 'gshhs' and self.projection == 'ortho':
+ b[:,0], b[:,1] = maptran(b[:,0], b[:,1])
+ else:
+ b[:,0], b[:,1] = self(b[:,0], b[:,1])
+ goodmask = np.logical_and(b[:,0]<1.e20,b[:,1]<1.e20)
+ # if less than two points are valid in
+ # map proj coords, skip this geometry.
+ if np.sum(goodmask) <= 1: continue
+ if name != 'gshhs':
+ # if not a polygon,
+ # just remove parts of geometry that are undefined
+ # in this map projection.
+ bx = np.compress(goodmask, b[:,0])
+ by = np.compress(goodmask, b[:,1])
+ # for orthographic projection, all points
+ # outside map projection region are eliminated
+ # with the above step, so we're done.
+ if self.projection == 'ortho':
+ polygons.append(zip(bx,by))
+ polygon_types.append(type)
+ continue
+ # create a GEOS geometry object.
+ poly = Shape(b)
+ # if geometry instersects map projection
+ # region, and doesn't have any invalid points, process it.
+ if goodmask.all() and poly.intersects(boundarypolyxy):
+ # if geometry intersection calculation fails,
+ # just move on.
+ try:
+ geoms = poly.intersection(boundarypolyxy)
+ except:
+ continue
+ # iterate over geometries in intersection.
+ for psub in geoms:
+ b = psub.boundary
+ # if projection == 'ortho',
+ # transform polygon from stereographic
+ # to orthographic coordinates.
+ if self.projection == 'ortho':
+ # if coastline polygon covers more than 99%
+ # of map region for fulldisk projection,
+ # it's probably bogus, so skip it.
+ areafrac = psub.area()/boundarypolyxy.area()
+ if name == 'gshhs' and\
+ self._fulldisk and\
+ areafrac > 0.99: continue
+ # inverse transform from stereographic
+ # to lat/lon.
+ b[:,0], b[:,1] = maptran(b[:,0], b[:,1], inverse=True)
+ # orthographic.
+ b[:,0], b[:,1]= self(b[:,0], b[:,1])
+ polygons.append(zip(b[:,0],b[:,1]))
+ polygon_types.append(type)
+ return polygons, polygon_types
+
+ def _getmapboundary(self):
+ """
+ create map boundary polygon (in lat/lon and x/y coordinates)
+ """
+ nx = 100
+ ny = 100
+ maptran = self
+ if self.projection in ['ortho','geos']:
+ # circular region.
+ thetas = np.linspace(0.,2.*np.pi,2*nx*ny)[:-1]
+ if self.projection == 'ortho':
+ rminor = self.rmajor
+ rmajor = self.rmajor
+ else:
+ rminor = self._height
+ rmajor = self._width
+ x = rmajor*np.cos(thetas) + rmajor
+ y = rminor*np.sin(thetas) + rminor
+ b = np.empty((len(x),2),np.float64)
+ b[:,0]=x; b[:,1]=y
+ boundaryxy = _geoslib.Polygon(b)
+ # compute proj instance for full disk, if necessary.
+ if not self._fulldisk:
+ projparms = self.projparams.copy()
+ del projparms['x_0']
+ del projparms['y_0']
+ if self.projection == 'ortho':
+ llcrnrx = -self.rmajor
+ llcrnry = -self.rmajor
+ urcrnrx = -llcrnrx
+ urcrnry = -llcrnry
+ else:
+ llcrnrx = -self._width
+ llcrnry = -self._height
+ urcrnrx = -llcrnrx
+ urcrnry = -llcrnry
+ projparms['x_0']=-llcrnrx
+ projparms['y_0']=-llcrnry
+ maptran = pyproj.Proj(projparms)
+ elif self.projection in ['moll','robin','sinu']:
+ # quasi-elliptical region.
+ lon_0 = self.projparams['lon_0']
+ # left side
+ lats1 = np.linspace(-89.9,89.9,ny).tolist()
+ lons1 = len(lats1)*[lon_0-179.9]
+ # top.
+ lons2 = np.linspace(lon_0-179.9,lon_0+179.9,nx).tolist()
+ lats2 = len(lons2)*[89.9]
+ # right side
+ lats3 = np.linspace(89.9,-89.9,ny).tolist()
+ lons3 = len(lats3)*[lon_0+179.9]
+ # bottom.
+ lons4 = np.linspace(lon_0+179.9,lon_0-179.9,nx).tolist()
+ lats4 = len(lons4)*[-89.9]
+ lons = np.array(lons1+lons2+lons3+lons4,np.float64)
+ lats = np.array(lats1+lats2+lats3+lats4,np.float64)
+ x, y = maptran(lons,lats)
+ b = np.empty((len(x),2),np.float64)
+ b[:,0]=x; b[:,1]=y
+ boundaryxy = _geoslib.Polygon(b)
+ else: # all other projections are rectangular.
+ # left side (x = xmin, ymin <= y <= ymax)
+ yy = np.linspace(self.ymin, self.ymax, ny)[:-1]
+ x = len(yy)*[self.xmin]; y = yy.tolist()
+ # top (y = ymax, xmin <= x <= xmax)
+ xx = np.linspace(self.xmin, self.xmax, nx)[:-1]
+ x = x + xx.tolist()
+ y = y + len(xx)*[self.ymax]
+ # right side (x = xmax, ymin <= y <= ymax)
+ yy = np.linspace(self.ymax, self.ymin, ny)[:-1]
+ x = x + len(yy)*[self.xmax]; y = y + yy.tolist()
+ # bottom (y = ymin, xmin <= x <= xmax)
+ xx = np.linspace(self.xmax, self.xmin, nx)[:-1]
+ x = x + xx.tolist()
+ y = y + len(xx)*[self.ymin]
+ x = np.array(x,np.float64)
+ y = np.array(y,np.float64)
+ b = np.empty((4,2),np.float64)
+ b[:,0]=[self.xmin,self.xmin,self.xmax,self.xmax]
+ b[:,1]=[self.ymin,self.ymax,self.ymax,self.ymin]
+ boundaryxy = _geoslib.Polygon(b)
+ if self.projection in ['mill','merc','cyl']:
+ # make sure map boundary doesn't quite include pole.
+ if self.urcrnrlat > 89.9999:
+ urcrnrlat = 89.9999
+ else:
+ urcrnrlat = self.urcrnrlat
+ if self.llcrnrlat < -89.9999:
+ llcrnrlat = -89.9999
+ else:
+ llcrnrlat = self.llcrnrlat
+ lons = [self.llcrnrlon, self.llcrnrlon, self.urcrnrlon, self.urcrnrlon]
+ lats = [llcrnrlat, urcrnrlat, urcrnrlat, llcrnrlat]
+ x, y = self(lons, lats)
+ b = np.empty((len(x),2),np.float64)
+ b[:,0]=x; b[:,1]=y
+ boundaryxy = _geoslib.Polygon(b)
+ else:
+ if self.projection not in ['moll','robin','sinu']:
+ lons, lats = maptran(x,y,inverse=True)
+ # fix lons so there are no jumps.
+ n = 1
+ lonprev = lons[0]
+ for lon,lat in zip(lons[1:],lats[1:]):
+ if np.abs(lon-lonprev) > 90.:
+ if lonprev < 0:
+ lon = lon - 360.
+ else:
+ lon = lon + 360
+ lons[n] = lon
+ lonprev = lon
+ n = n + 1
+ b = np.empty((len(lons),2),np.float64)
+ b[:,0]=lons; b[:,1]=lats
+ boundaryll = _geoslib.Polygon(b)
+ return boundaryll, boundaryxy
+
+
+ def drawmapboundary(self,color='k',linewidth=1.0,fill_color=None,\
+ zorder=None,ax=None):
+ """
+ draw boundary around map projection region, optionally
+ filling interior of region.
+
+ linewidth - line width for boundary (default 1.)
+
+ color - color of boundary line (default black)
+
+ fill_color - fill the map region background with this
+ color (default is no fill or fill with axis background color).
+
+ zorder - sets the zorder for filling map background
+ (default 0).
+
+ ax - axes instance to use (default None, use default axes
+ instance).
+
+ returns PatchCollection representing map boundary.
+ """
+ # get current axes instance (if none specified).
+ if ax is None and self.ax is None:
+ try:
+ ax = plt.gca()
+ except:
+ import matplotlib.pyplot as plt
+ ax = plt.gca()
+ elif ax is None and self.ax is not None:
+ ax = self.ax
+ limb = None
+ if self.projection == 'ortho':
+ limb = Circle((self.rmajor,self.rmajor),self.rmajor)
+ elif self.projection == 'geos':
+ limb = Ellipse((self._width,self._height),2.*self._width,2.*self._height)
+ if self.projection in ['ortho','geos'] and self._fulldisk:
+ # elliptical region.
+ ax.add_patch(limb)
+ if fill_color is None:
+ limb.set_fill(False)
+ else:
+ limb.set_facecolor(fill_color)
+ limb.set_zorder(0)
+ limb.set_edgecolor(color)
+ limb.set_linewidth(linewidth)
+ limb.set_clip_on(False)
+ if zorder is not None:
+ limb.set_zorder(zorder)
+ elif self.projection in ['moll','robin','sinu']: # elliptical region.
+ nx = 100; ny = 100
+ # quasi-elliptical region.
+ lon_0 = self.projparams['lon_0']
+ # left side
+ lats1 = np.linspace(-89.9,89.9,ny).tolist()
+ lons1 = len(lats1)*[lon_0-179.9]
+ # top.
+ lons2 = np.linspace(lon_0-179.9,lon_0+179.9,nx).tolist()
+ lats2 = len(lons2)*[89.9]
+ # right side
+ lats3 = np.linspace(89.9,-89.9,ny).tolist()
+ lons3 = len(lats3)*[lon_0+179.9]
+ # bottom.
+ lons4 = np.linspace(lon_0+179.9,lon_0-179.9,nx).tolist()
+ lats4 = len(lons4)*[-89.9]
+ lons = np.array(lons1+lons2+lons3+lons4,np.float64)
+ lats = np.array(lats1+lats2+lats3+lats4,np.float64)
+ x, y = self(lons,lats)
+ xy = zip(x,y)
+ limb = Polygon(xy,edgecolor=color,linewidth=linewidth)
+ ax.add_patch(limb)
+ if fill_color is None:
+ limb.set_fill(False)
+ else:
+ limb.set_facecolor(fill_color)
+ limb.set_zorder(0)
+ limb.set_clip_on(False)
+ if zorder is not None:
+ limb.set_zorder(zorder)
+ else: # all other projections are rectangular.
+ ax.axesPatch.set_linewidth(linewidth)
+ if self.projection not in ['geos','ortho']:
+ if fill_color is None:
+ ax.axesPatch.set_facecolor(ax.get_axis_bgcolor())
+ else:
+ ax.axesPatch.set_facecolor(fill_color)
+ ax.axesPatch.set_zorder(0)
+ ax.axesPatch.set_edgecolor(color)
+ ax.set_frame_on(True)
+ if zorder is not None:
+ ax.axesPatch.set_zorder(zorder)
+ else:
+ ax.axesPatch.set_facecolor(ax.get_axis_bgcolor())
+ ax.axesPatch.set_edgecolor(color)
+ ax.set_frame_on(True)
+ if zorder is not None:
+ ax.axesPatch.set_zorder(zorder)
+ # for geos or ortho projections, also
+ # draw and fill map projection limb, clipped
+ # to rectangular region.
+ ax.add_patch(limb)
+ if fill_color is None:
+ limb.set_fill(False)
+ else:
+ limb.set_facecolor(fill_color)
+ limb.set_zorder(0)
+ limb.set_edgecolor(color)
+ limb.set_linewidth(linewidth)
+ if zorder is not None:
+ limb.set_zorder(zorder)
+ limb.set_clip_on(True)
+ # set axes limits to fit map region.
+ self.set_axes_limits(ax=ax)
+ return limb
+
+ def fillcontinents(self,color='0.8',lake_color=None,ax=None,zorder=None):
+ """
+ Fill continents.
+
+ color - color to fill continents (default gray).
+
+ lake_color - color to fill inland lakes (default axes background).
+
+ ax - axes instance (overrides default axes instance).
+
+ zorder - sets the zorder for the continent polygons (if not specified,
+ uses default zorder for a Polygon patch). Set to zero if you want to paint
+ over the filled continents).
+
+ After filling continents, lakes are re-filled with axis background color.
+
+ returns Polygon object.
+ """
+ if self.resolution is None:
+ raise AttributeError, 'there are no boundary datasets associated with this Basemap instance'
+ # get current axes instance (if none specified).
+ if ax is None and self.ax is None:
+ try:
+ ax = plt.gca()
+ except:
+ import matplotlib.pyplot as plt
+ ax = plt.gca()
+ elif ax is None and self.ax is not None:
+ ax = self.ax
+ # get axis background color.
+ axisbgc = ax.get_axis_bgcolor()
+ npoly = 0
+ for x,y in self.coastpolygons:
+ xa = np.array(x,np.float32)
+ ya = np.array(y,np.float32)
+ # check to see if all four corners of domain in polygon (i...
[truncated message content] |
|
From: <md...@us...> - 2008-06-12 14:29:43
|
Revision: 5481
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5481&view=rev
Author: mdboom
Date: 2008-06-12 07:29:42 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
Fix latex doc build by removing some more obscure symbols that aren't
likely to be installed and adding "txfonts" to preamble.
Modified Paths:
--------------
trunk/matplotlib/doc/conf.py
trunk/matplotlib/doc/sphinxext/math_symbol_table.py
Modified: trunk/matplotlib/doc/conf.py
===================================================================
--- trunk/matplotlib/doc/conf.py 2008-06-12 13:38:00 UTC (rev 5480)
+++ trunk/matplotlib/doc/conf.py 2008-06-12 14:29:42 UTC (rev 5481)
@@ -154,6 +154,7 @@
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
+ \usepackage{txfonts}
"""
# Documents to append as an appendix to all manuals.
Modified: trunk/matplotlib/doc/sphinxext/math_symbol_table.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/math_symbol_table.py 2008-06-12 13:38:00 UTC (rev 5480)
+++ trunk/matplotlib/doc/sphinxext/math_symbol_table.py 2008-06-12 14:29:42 UTC (rev 5481)
@@ -55,11 +55,8 @@
\succnapprox \subsetneqq \nvDash \precnsim \succnsim \supsetneqq
\nvdash \lnapprox \gnapprox \ntriangleleft \ntrianglelefteq
\lneqq \gneqq \ntriangleright \lnsim \gnsim \ntrianglerighteq
- \approxident \origof \imageof \coloneq \triangleeq \stareq \nsime
- \dotminus \eqsim \nequiv \Equiv \measeq \napprox \eqless
- \kernelcontraction \nsupset \doublebarwedge \nVdash \arceq
- \backcong \Doteq \eqdef \wedgeq \questeq \eqgtr \cupdot
- \veeeq \nsubset \eqcolon \ne
+ \coloneq \eqsim \nequiv \napprox \nsupset \doublebarwedge \nVdash
+ \Doteq \nsubset \eqcolon \ne
"""],
["Arrow symbols",
2,
@@ -82,21 +79,17 @@
\upharpoonright \downharpoonright \rightsquigarrow \nleftarrow
\nrightarrow \nLeftarrow \nRightarrow \nleftrightarrow
\nLeftrightarrow \to \Swarrow \Searrow \Nwarrow \Nearrow
- \barleftarrow \mapsup \mapsdown \mapsfrom \rightarrowbar
- \twoheaduparrow \updownarrowbar \leftsquigarrow \rightzigzagarrow
- \twoheaddownarrow \downzigzagarrow
+ \leftsquigarrow
"""],
["Miscellaneous symbols",
3,
- r"""\neg \invnot \turnednot \infty \forall \wp \exists \bigstar
- \angle \partial \nexists \measuredangle \eth \emptyset
- \sphericalangle \clubsuit \varnothing \complement \diamondsuit
- \imath \Finv \triangledown \heartsuit \jmath \Game \spadesuit
- \ell \hbar \vartriangle \cdots \hslash \vdots \blacksquare \ldots
- \blacktriangle \ddots \sharp \prime \blacktriangledown \Im \flat
- \backprime \Re \natural \circledS \P \O \copyright \ss \Ldsh
- \frakZ \l \carriagereturn \circledR \S \sterling \L \yen \danger
- \d \OE \AA \AE \scurel \oe \o \checkmark \Rdsh \ae \ac \prurel \$
+ r"""\neg \infty \forall \wp \exists \bigstar \angle \partial
+ \nexists \measuredangle \eth \emptyset \sphericalangle \clubsuit
+ \varnothing \complement \diamondsuit \imath \Finv \triangledown
+ \heartsuit \jmath \Game \spadesuit \ell \hbar \vartriangle \cdots
+ \hslash \vdots \blacksquare \ldots \blacktriangle \ddots \sharp
+ \prime \blacktriangledown \Im \flat \backprime \Re \natural
+ \circledS \P \copyright \ss \circledR \S \yen \AA \checkmark \$
\iiint \iint \iint \oiiint"""]
]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ds...@us...> - 2008-06-12 13:38:02
|
Revision: 5480
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5480&view=rev
Author: dsdale
Date: 2008-06-12 06:38:00 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
comments in the coding guide review
Modified Paths:
--------------
trunk/matplotlib/doc/devel/outline.rst
Modified: trunk/matplotlib/doc/devel/outline.rst
===================================================================
--- trunk/matplotlib/doc/devel/outline.rst 2008-06-12 12:22:58 UTC (rev 5479)
+++ trunk/matplotlib/doc/devel/outline.rst 2008-06-12 13:38:00 UTC (rev 5480)
@@ -168,6 +168,53 @@
rc() function and using that instead of setting the
dictionary entries directly), if necessary.
+ Darren notes:
+
+ Validation is actually built into RcParams. This was done
+ just prior to development of the traited config, validation is done using
+ the mechanisms developed in rcsetup. For example::
+
+ >>> rcParams['a.b']=1
+ ---------------------------------------------------------------------------
+ KeyError Traceback (most recent call last)
+
+ /home/darren/<ipython console> in <module>()
+
+ /usr/lib64/python2.5/site-packages/matplotlib/__init__.pyc in __setitem__(self, key, val)
+ 555 except KeyError:
+ 556 raise KeyError('%s is not a valid rc parameter.\
+ --> 557 See rcParams.keys() for a list of valid parameters.'%key)
+ 558
+ 559
+
+ KeyError: 'a.b is not a valid rc parameter.See rcParams.keys() for a list of valid parameters.'
+
+ also::
+
+ rcParams['text.usetex']=''
+ ---------------------------------------------------------------------------
+ ValueError Traceback (most recent call last)
+
+ /home/darren/<ipython console> in <module>()
+
+ /usr/lib64/python2.5/site-packages/matplotlib/__init__.pyc in __setitem__(self, key, val)
+ 551 instead.'% (key, alt))
+ 552 key = alt
+ --> 553 cval = self.validate[key](val)
+ 554 dict.__setitem__(self, key, cval)
+ 555 except KeyError:
+
+ /usr/lib64/python2.5/site-packages/matplotlib/rcsetup.pyc in validate_bool(b)
+ 56 elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False): return False
+ 57 else:
+ ---> 58 raise ValueError('Could not convert "%s" to boolean' % b)
+ 59
+ 60 def validate_bool_maybe_none(b):
+
+ ValueError: Could not convert "" to boolean
+
+
+
#. DONE - You give the example::
import matplotlib.cbook as cbook
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ds...@us...> - 2008-06-12 12:23:02
|
Revision: 5479
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5479&view=rev
Author: dsdale
Date: 2008-06-12 05:22:58 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
added an empty matplotlibrc to users/figures
Added Paths:
-----------
trunk/matplotlib/doc/users/figures/matplotlibrc
Added: trunk/matplotlib/doc/users/figures/matplotlibrc
===================================================================
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-12 12:17:12
|
Revision: 5478
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5478&view=rev
Author: mdboom
Date: 2008-06-12 05:17:07 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
Fix compiler warnings.
Modified Paths:
--------------
trunk/matplotlib/src/ft2font.cpp
Modified: trunk/matplotlib/src/ft2font.cpp
===================================================================
--- trunk/matplotlib/src/ft2font.cpp 2008-06-11 18:35:01 UTC (rev 5477)
+++ trunk/matplotlib/src/ft2font.cpp 2008-06-12 12:17:07 UTC (rev 5478)
@@ -74,15 +74,15 @@
if (height < 0) height = 1;
size_t numBytes = width*height;
- if (width != _width || height != _height) {
+ if ((unsigned long)width != _width || (unsigned long)height != _height) {
if (numBytes > _width*_height) {
delete [] _buffer;
_buffer = NULL;
_buffer = new unsigned char [numBytes];
}
- _width = width;
- _height = height;
+ _width = (unsigned long)width;
+ _height = (unsigned long)height;
}
memset(_buffer, 0, numBytes);
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-11 18:35:31
|
Revision: 5477
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5477&view=rev
Author: mdboom
Date: 2008-06-11 11:35:01 -0700 (Wed, 11 Jun 2008)
Log Message:
-----------
Fix capitalization.
Modified Paths:
--------------
trunk/matplotlib/doc/sphinxext/math_symbol_table.py
Modified: trunk/matplotlib/doc/sphinxext/math_symbol_table.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/math_symbol_table.py 2008-06-11 18:33:05 UTC (rev 5476)
+++ trunk/matplotlib/doc/sphinxext/math_symbol_table.py 2008-06-11 18:35:01 UTC (rev 5477)
@@ -21,12 +21,12 @@
5,
r"""\bigcap \bigcup \bigodot \bigoplus \bigotimes \biguplus
\bigvee \bigwedge \coprod \oint \prod \sum \int"""],
- ["Standard Function Names",
+ ["Standard function names",
4,
r"""\arccos \csc \ker \min \arcsin \deg \lg \Pr \arctan \det \lim
\gcd \ln \sup \cot \hom \log \tan \coth \inf \max \tanh
\sec \arg \dim \liminf \sin \cos \exp \limsup \sinh \cosh"""],
- ["Binary Operation and Relation Symbols",
+ ["Binary operation and relation symbols",
3,
r"""\ast \pm \slash \cap \star \mp \cup \cdot \uplus
\triangleleft \circ \odot \sqcap \triangleright \bullet \ominus
@@ -61,7 +61,7 @@
\backcong \Doteq \eqdef \wedgeq \questeq \eqgtr \cupdot
\veeeq \nsubset \eqcolon \ne
"""],
- ["Arrow Symbols",
+ ["Arrow symbols",
2,
r"""\leftarrow \longleftarrow \uparrow \Leftarrow \Longleftarrow
\Uparrow \rightarrow \longrightarrow \downarrow \Rightarrow
@@ -86,7 +86,7 @@
\twoheaduparrow \updownarrowbar \leftsquigarrow \rightzigzagarrow
\twoheaddownarrow \downzigzagarrow
"""],
- ["Miscellaneous Symbols",
+ ["Miscellaneous symbols",
3,
r"""\neg \invnot \turnednot \infty \forall \wp \exists \bigstar
\angle \partial \nexists \measuredangle \eth \emptyset
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-11 18:33:11
|
Revision: 5476
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5476&view=rev
Author: mdboom
Date: 2008-06-11 11:33:05 -0700 (Wed, 11 Jun 2008)
Log Message:
-----------
Removing debugging output
Modified Paths:
--------------
trunk/matplotlib/src/_png.cpp
Modified: trunk/matplotlib/src/_png.cpp
===================================================================
--- trunk/matplotlib/src/_png.cpp 2008-06-11 18:05:21 UTC (rev 5475)
+++ trunk/matplotlib/src/_png.cpp 2008-06-11 18:33:05 UTC (rev 5476)
@@ -32,7 +32,6 @@
};
static void write_png_data(png_structp png_ptr, png_bytep data, png_size_t length) {
- printf("%x %x %d %x\n", png_ptr, data, *data, length);
PyObject* py_file_obj = (PyObject*)png_get_io_ptr(png_ptr);
PyObject* write_method = PyObject_GetAttrString(py_file_obj, "write");
PyObject* result = NULL;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-11 18:05:32
|
Revision: 5475
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5475&view=rev
Author: mdboom
Date: 2008-06-11 11:05:21 -0700 (Wed, 11 Jun 2008)
Log Message:
-----------
Fix silly typo in _png.cpp that broke usetex support.
Modified Paths:
--------------
trunk/matplotlib/src/_png.cpp
Modified: trunk/matplotlib/src/_png.cpp
===================================================================
--- trunk/matplotlib/src/_png.cpp 2008-06-11 17:24:57 UTC (rev 5474)
+++ trunk/matplotlib/src/_png.cpp 2008-06-11 18:05:21 UTC (rev 5475)
@@ -19,7 +19,7 @@
{
add_varargs_method("write_png", &_png_module::write_png,
"write_png(buffer, width, height, fileobj, dpi=None)");
- add_varargs_method("read_png", &_png_module::write_png,
+ add_varargs_method("read_png", &_png_module::read_png,
"read_png(fileobj)");
initialize("Module to write PNG files");
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-11 17:25:00
|
Revision: 5474
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5474&view=rev
Author: mdboom
Date: 2008-06-11 10:24:57 -0700 (Wed, 11 Jun 2008)
Log Message:
-----------
Fix docutils 0.4 incompatibility.
Modified Paths:
--------------
trunk/matplotlib/doc/sphinxext/math_symbol_table.py
Modified: trunk/matplotlib/doc/sphinxext/math_symbol_table.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/math_symbol_table.py 2008-06-11 17:05:42 UTC (rev 5473)
+++ trunk/matplotlib/doc/sphinxext/math_symbol_table.py 2008-06-11 17:24:57 UTC (rev 5474)
@@ -100,48 +100,61 @@
\iiint \iint \iint \oiiint"""]
]
-from docutils import nodes, statemachine
-from docutils.parsers.rst import Directive
-class math_symbol_table_directive(Directive):
- has_content = True
- def run(self):
- def get_n(n, l):
- part = []
- for x in l:
- part.append(x)
- if len(part) == n:
- yield part
- part = []
- yield part
+def run(state_machine):
+ def get_n(n, l):
+ part = []
+ for x in l:
+ part.append(x)
+ if len(part) == n:
+ yield part
+ part = []
+ yield part
- lines = []
- for category, columns, syms in symbols:
- syms = syms.split()
- syms.sort()
- lines.append("**%s**" % category)
+ lines = []
+ for category, columns, syms in symbols:
+ syms = syms.split()
+ syms.sort()
+ lines.append("**%s**" % category)
+ lines.append('')
+ max_width = 0
+ for sym in syms:
+ max_width = max(max_width, len(sym))
+ max_width = max_width * 2 + 16
+ header = " " + (('=' * max_width) + ' ') * columns
+ format = '%%%ds' % max_width
+ for chunk in get_n(20, get_n(columns, syms)):
+ lines.append(header)
+ for part in chunk:
+ line = []
+ for sym in part:
+ line.append(format % (":math:`%s` ``%s``" % (sym, sym)))
+ lines.append(" " + " ".join(line))
+ lines.append(header)
lines.append('')
- max_width = 0
- for sym in syms:
- max_width = max(max_width, len(sym))
- max_width = max_width * 2 + 16
- header = " " + (('=' * max_width) + ' ') * columns
- format = '%%%ds' % max_width
- for chunk in get_n(20, get_n(columns, syms)):
- lines.append(header)
- for part in chunk:
- line = []
- for sym in part:
- line.append(format % (":math:`%s` ``%s``" % (sym, sym)))
- lines.append(" " + " ".join(line))
- lines.append(header)
- lines.append('')
- self.state_machine.insert_input(lines, "Symbol table")
- return []
-from docutils.parsers.rst import directives
-directives.register_directive('math_symbol_table',
- math_symbol_table_directive)
+ state_machine.insert_input(lines, "Symbol table")
+ return []
+try:
+ from docutils.parsers.rst import Directive
+except ImportError:
+ from docutils.parsers.rst.directives import _directives
+ def math_symbol_table_directive(name, arguments, options, content, lineno,
+ content_offset, block_text, state, state_machine):
+ return run(state_machine)
+ math_symbol_table_directive.arguments = None
+ math_symbol_table_directive.options = {}
+ math_symbol_table_directive.content = False
+ _directives['math_symbol_table'] = math_symbol_table_directive
+else:
+ class math_symbol_table_directive(Directive):
+ has_content = False
+ def run(self):
+ return run(self.state_machine)
+ from docutils.parsers.rst import directives
+ directives.register_directive('math_symbol_table',
+ math_symbol_table_directive)
+
if __name__ == "__main__":
# Do some verification of the tables
from matplotlib import _mathtext_data
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-11 17:06:11
|
Revision: 5473
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5473&view=rev
Author: mdboom
Date: 2008-06-11 10:05:42 -0700 (Wed, 11 Jun 2008)
Log Message:
-----------
Fix Python 2.4 incompatibility.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/pyparsing.py
Modified: trunk/matplotlib/lib/matplotlib/pyparsing.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pyparsing.py 2008-06-11 16:24:12 UTC (rev 5472)
+++ trunk/matplotlib/lib/matplotlib/pyparsing.py 2008-06-11 17:05:42 UTC (rev 5473)
@@ -213,8 +213,7 @@
ErrorStop indicates that parsing is to stop immediately because
an unbacktrackable syntax error has been found"""
def __init__(self, pe):
- super(ParseSyntaxException, self).__init__(
- pe.pstr, pe.loc, pe.msg, pe.parserElement)
+ ParseFatalException.__init__(self, pe.pstr, pe.loc, pe.msg, pe.parserElement)
#~ class ReparseException(ParseBaseException):
#~ """Experimental class - parse actions can raise this exception to cause
@@ -3481,16 +3480,16 @@
return ret
def indentedBlock(blockStatementExpr, indentStack, indent=True):
- """Helper method for defining space-delimited indentation blocks, such as
+ """Helper method for defining space-delimited indentation blocks, such as
those used to define block statements in Python source code.
-
+
Parameters:
- - blockStatementExpr - expression defining syntax of statement that
+ - blockStatementExpr - expression defining syntax of statement that
is repeated within the indented block
- indentStack - list created by caller to manage indentation stack
(multiple statementWithIndentedBlock expressions within a single grammar
should share a common indentStack)
- - indent - boolean indicating whether block must be indented beyond the
+ - indent - boolean indicating whether block must be indented beyond the
the current level; set to False for block of left-most statements
(default=True)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-11 16:24:16
|
Revision: 5472
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5472&view=rev
Author: mdboom
Date: 2008-06-11 09:24:12 -0700 (Wed, 11 Jun 2008)
Log Message:
-----------
Forgot this file
Added Paths:
-----------
trunk/matplotlib/src/_png.cpp
Added: trunk/matplotlib/src/_png.cpp
===================================================================
--- trunk/matplotlib/src/_png.cpp (rev 0)
+++ trunk/matplotlib/src/_png.cpp 2008-06-11 16:24:12 UTC (rev 5472)
@@ -0,0 +1,293 @@
+#include <png.h>
+
+// To remove a gcc warning
+#ifdef _POSIX_C_SOURCE
+#undef _POSIX_C_SOURCE
+#endif
+
+// TODO: Un CXX-ify this module
+#include "CXX/Extensions.hxx"
+#include "numpy/arrayobject.h"
+#include "mplutils.h"
+
+// the extension module
+class _png_module : public Py::ExtensionModule<_png_module>
+{
+public:
+ _png_module()
+ : Py::ExtensionModule<_png_module>( "_png" )
+ {
+ add_varargs_method("write_png", &_png_module::write_png,
+ "write_png(buffer, width, height, fileobj, dpi=None)");
+ add_varargs_method("read_png", &_png_module::write_png,
+ "read_png(fileobj)");
+ initialize("Module to write PNG files");
+ }
+
+ virtual ~_png_module() {}
+
+private:
+ Py::Object write_png(const Py::Tuple& args);
+ Py::Object read_png(const Py::Tuple& args);
+};
+
+static void write_png_data(png_structp png_ptr, png_bytep data, png_size_t length) {
+ printf("%x %x %d %x\n", png_ptr, data, *data, length);
+ PyObject* py_file_obj = (PyObject*)png_get_io_ptr(png_ptr);
+ PyObject* write_method = PyObject_GetAttrString(py_file_obj, "write");
+ PyObject* result = NULL;
+ if (write_method)
+ result = PyObject_CallFunction(write_method, (char *)"s#", data, length);
+ Py_XDECREF(write_method);
+ Py_XDECREF(result);
+}
+
+static void flush_png_data(png_structp png_ptr) {
+ PyObject* py_file_obj = (PyObject*)png_get_io_ptr(png_ptr);
+ PyObject* flush_method = PyObject_GetAttrString(py_file_obj, "flush");
+ PyObject* result = NULL;
+ if (flush_method)
+ result = PyObject_CallFunction(flush_method, (char *)"");
+ Py_XDECREF(flush_method);
+ Py_XDECREF(result);
+}
+
+// this code is heavily adapted from the paint license, which is in
+// the file paint.license (BSD compatible) included in this
+// distribution. TODO, add license file to MANIFEST.in and CVS
+Py::Object _png_module::write_png(const Py::Tuple& args)
+{
+ args.verify_length(4, 5);
+
+ FILE *fp = NULL;
+ bool close_file = false;
+ Py::Object buffer_obj = Py::Object(args[0]);
+ PyObject* buffer = buffer_obj.ptr();
+ if (!PyObject_CheckReadBuffer(buffer)) {
+ throw Py::TypeError("First argument must be an rgba buffer.");
+ }
+
+ const void* pixBufferPtr = NULL;
+ Py_ssize_t pixBufferLength = 0;
+ if (PyObject_AsReadBuffer(buffer, &pixBufferPtr, &pixBufferLength)) {
+ throw Py::ValueError("Couldn't get data from read buffer.");
+ }
+
+ png_byte* pixBuffer = (png_byte*)pixBufferPtr;
+ int width = (int)Py::Int(args[1]);
+ int height = (int)Py::Int(args[2]);
+
+ if (pixBufferLength < width * height * 4) {
+ throw Py::ValueError("Buffer and width, height don't seem to match.");
+ }
+
+ Py::Object py_fileobj = Py::Object(args[3]);
+ if (py_fileobj.isString()) {
+ std::string fileName = Py::String(py_fileobj);
+ const char *file_name = fileName.c_str();
+ if ((fp = fopen(file_name, "wb")) == NULL)
+ throw Py::RuntimeError( Printf("Could not open file %s", file_name).str() );
+ close_file = true;
+ } else if (PyFile_CheckExact(py_fileobj.ptr())) {
+ fp = PyFile_AsFile(py_fileobj.ptr());
+ }
+ else {
+ PyObject* write_method = PyObject_GetAttrString(py_fileobj.ptr(), "write");
+ if (!(write_method && PyCallable_Check(write_method))) {
+ Py_XDECREF(write_method);
+ throw Py::TypeError("Object does not appear to be a 8-bit string path or a Python file-like object");
+ }
+ Py_XDECREF(write_method);
+ }
+
+ png_bytep *row_pointers = NULL;
+ png_structp png_ptr = NULL;
+ png_infop info_ptr = NULL;
+
+ try {
+ struct png_color_8_struct sig_bit;
+ png_uint_32 row;
+
+ row_pointers = new png_bytep[height];
+ for (row = 0; row < (png_uint_32)height; ++row) {
+ row_pointers[row] = pixBuffer + row * width * 4;
+ }
+
+ png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+ if (png_ptr == NULL) {
+ throw Py::RuntimeError("Could not create write struct");
+ }
+
+ info_ptr = png_create_info_struct(png_ptr);
+ if (info_ptr == NULL) {
+ throw Py::RuntimeError("Could not create info struct");
+ }
+
+ if (setjmp(png_ptr->jmpbuf)) {
+ throw Py::RuntimeError("Error building image");
+ }
+
+ if (fp) {
+ png_init_io(png_ptr, fp);
+ } else {
+ png_set_write_fn(png_ptr, (void*)py_fileobj.ptr(),
+ &write_png_data, &flush_png_data);
+ }
+ png_set_IHDR(png_ptr, info_ptr,
+ width, height, 8,
+ PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
+ PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
+
+ // Save the dpi of the image in the file
+ if (args.size() == 5) {
+ double dpi = Py::Float(args[4]);
+ size_t dots_per_meter = (size_t)(dpi / (2.54 / 100.0));
+ png_set_pHYs(png_ptr, info_ptr, dots_per_meter, dots_per_meter, PNG_RESOLUTION_METER);
+ }
+
+ // this a a color image!
+ sig_bit.gray = 0;
+ sig_bit.red = 8;
+ sig_bit.green = 8;
+ sig_bit.blue = 8;
+ /* if the image has an alpha channel then */
+ sig_bit.alpha = 8;
+ png_set_sBIT(png_ptr, info_ptr, &sig_bit);
+
+ png_write_info(png_ptr, info_ptr);
+ png_write_image(png_ptr, row_pointers);
+ png_write_end(png_ptr, info_ptr);
+ } catch (...) {
+ if (fp && close_file) fclose(fp);
+ delete [] row_pointers;
+ /* Changed calls to png_destroy_write_struct to follow
+ http://www.libpng.org/pub/png/libpng-manual.txt.
+ This ensures the info_ptr memory is released.
+ */
+ if (png_ptr && info_ptr) png_destroy_write_struct(&png_ptr, &info_ptr);
+ throw;
+ }
+
+ png_destroy_write_struct(&png_ptr, &info_ptr);
+ delete [] row_pointers;
+ if (fp && close_file) fclose(fp);
+
+ return Py::Object();
+}
+
+
+Py::Object
+_png_module::read_png(const Py::Tuple& args) {
+
+ args.verify_length(1);
+ std::string fname = Py::String(args[0]);
+
+ png_byte header[8]; // 8 is the maximum size that can be checked
+
+ FILE *fp = fopen(fname.c_str(), "rb");
+ if (!fp)
+ throw Py::RuntimeError(Printf("_image_module::readpng could not open PNG file %s for reading", fname.c_str()).str());
+
+ if (fread(header, 1, 8, fp) != 8)
+ throw Py::RuntimeError("_image_module::readpng: error reading PNG header");
+ if (png_sig_cmp(header, 0, 8))
+ throw Py::RuntimeError("_image_module::readpng: file not recognized as a PNG file");
+
+
+ /* initialize stuff */
+ png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+
+ if (!png_ptr)
+ throw Py::RuntimeError("_image_module::readpng: png_create_read_struct failed");
+
+ png_infop info_ptr = png_create_info_struct(png_ptr);
+ if (!info_ptr)
+ throw Py::RuntimeError("_image_module::readpng: png_create_info_struct failed");
+
+ if (setjmp(png_jmpbuf(png_ptr)))
+ throw Py::RuntimeError("_image_module::readpng: error during init_io");
+
+ png_init_io(png_ptr, fp);
+ png_set_sig_bytes(png_ptr, 8);
+
+ png_read_info(png_ptr, info_ptr);
+
+ png_uint_32 width = info_ptr->width;
+ png_uint_32 height = info_ptr->height;
+
+ // convert misc color types to rgb for simplicity
+ if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY ||
+ info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
+ png_set_gray_to_rgb(png_ptr);
+ else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
+ png_set_palette_to_rgb(png_ptr);
+
+
+ int bit_depth = info_ptr->bit_depth;
+ if (bit_depth == 16) png_set_strip_16(png_ptr);
+
+
+ png_set_interlace_handling(png_ptr);
+ png_read_update_info(png_ptr, info_ptr);
+
+ bool rgba = info_ptr->color_type == PNG_COLOR_TYPE_RGBA;
+ if ( (info_ptr->color_type != PNG_COLOR_TYPE_RGB) && !rgba) {
+ std::cerr << "Found color type " << (int)info_ptr->color_type << std::endl;
+ throw Py::RuntimeError("_image_module::readpng: cannot handle color_type");
+ }
+
+ /* read file */
+ if (setjmp(png_jmpbuf(png_ptr)))
+ throw Py::RuntimeError("_image_module::readpng: error during read_image");
+
+ png_bytep *row_pointers = new png_bytep[height];
+ png_uint_32 row;
+
+ for (row = 0; row < height; row++)
+ row_pointers[row] = new png_byte[png_get_rowbytes(png_ptr,info_ptr)];
+
+ png_read_image(png_ptr, row_pointers);
+
+
+
+ int dimensions[3];
+ dimensions[0] = height; //numrows
+ dimensions[1] = width; //numcols
+ dimensions[2] = 4;
+
+ PyArrayObject *A = (PyArrayObject *) PyArray_FromDims(3, dimensions, PyArray_FLOAT);
+
+
+ for (png_uint_32 y = 0; y < height; y++) {
+ png_byte* row = row_pointers[y];
+ for (png_uint_32 x = 0; x < width; x++) {
+
+ png_byte* ptr = (rgba) ? &(row[x*4]) : &(row[x*3]);
+ size_t offset = y*A->strides[0] + x*A->strides[1];
+ //if ((y<10)&&(x==10)) std::cout << "r = " << ptr[0] << " " << ptr[0]/255.0 << std::endl;
+ *(float*)(A->data + offset + 0*A->strides[2]) = (float)(ptr[0]/255.0f);
+ *(float*)(A->data + offset + 1*A->strides[2]) = (float)(ptr[1]/255.0f);
+ *(float*)(A->data + offset + 2*A->strides[2]) = (float)(ptr[2]/255.0f);
+ *(float*)(A->data + offset + 3*A->strides[2]) = rgba ? (float)(ptr[3]/255.0f) : 1.0f;
+ }
+ }
+
+ //free the png memory
+ png_read_end(png_ptr, info_ptr);
+ png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);
+ fclose(fp);
+ for (row = 0; row < height; row++)
+ delete [] row_pointers[row];
+ delete [] row_pointers;
+ return Py::asObject((PyObject*)A);
+}
+
+extern "C"
+ DL_EXPORT(void)
+ init_png(void)
+{
+ import_array();
+
+ static _png_module* _png = NULL;
+ _png = new _png_module;
+}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-11 15:49:22
|
Revision: 5471
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5471&view=rev
Author: mdboom
Date: 2008-06-11 08:49:11 -0700 (Wed, 11 Jun 2008)
Log Message:
-----------
Fix some mathtext scaling bugs
Add new mathtext symbols
Use mathtext to render math in the docs (the dog-fooding patch!)
Move PNG reading/writing to its own module and remove it from
_backend_agg and _image
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/doc/conf.py
trunk/matplotlib/doc/devel/outline.rst
trunk/matplotlib/doc/sphinxext/mathpng.py
trunk/matplotlib/doc/users/mathtext.rst
trunk/matplotlib/examples/pylab_examples/mathtext_examples.py
trunk/matplotlib/lib/matplotlib/_mathtext_data.py
trunk/matplotlib/lib/matplotlib/backends/backend_agg.py
trunk/matplotlib/lib/matplotlib/backends/backend_svg.py
trunk/matplotlib/lib/matplotlib/image.py
trunk/matplotlib/lib/matplotlib/mathtext.py
trunk/matplotlib/lib/matplotlib/texmanager.py
trunk/matplotlib/matplotlibrc.template
trunk/matplotlib/setup.py
trunk/matplotlib/setupext.py
trunk/matplotlib/src/_backend_agg.cpp
trunk/matplotlib/src/_backend_agg.h
trunk/matplotlib/src/_image.cpp
trunk/matplotlib/src/_image.h
trunk/matplotlib/src/ft2font.cpp
trunk/matplotlib/src/ft2font.h
Added Paths:
-----------
trunk/matplotlib/doc/sphinxext/math_symbol_table.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/CHANGELOG 2008-06-11 15:49:11 UTC (rev 5471)
@@ -1,3 +1,13 @@
+2008-06-11 Use matplotlib.mathtext to render math expressions in
+ online docs - MGD
+
+2008-06-11 Move PNG loading/saving to its own extension module, and
+ remove duplicate code in _backend_agg.cpp and _image.cpp
+ that does the same thing - MGD
+
+2008-06-11 Numerous mathtext bugfixes, primarily related to
+ dpi-independence - MGD
+
2008-06-10 Bar now applies the label only to the first patch only, and
sets '_nolegend_' for the other patch labels. This lets
autolegend work as expected for hist and bar - see
Modified: trunk/matplotlib/doc/conf.py
===================================================================
--- trunk/matplotlib/doc/conf.py 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/doc/conf.py 2008-06-11 15:49:11 UTC (rev 5471)
@@ -27,7 +27,7 @@
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['mathpng', 'sphinx.ext.autodoc']
+extensions = ['mathpng', 'math_symbol_table', 'sphinx.ext.autodoc']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
@@ -150,7 +150,11 @@
latex_logo = None
# Additional stuff for the LaTeX preamble.
-latex_preamble = ''
+latex_preamble = """
+ \usepackage{amsmath}
+ \usepackage{amsfonts}
+ \usepackage{amssymb}
+"""
# Documents to append as an appendix to all manuals.
latex_appendices = []
Modified: trunk/matplotlib/doc/devel/outline.rst
===================================================================
--- trunk/matplotlib/doc/devel/outline.rst 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/doc/devel/outline.rst 2008-06-11 15:49:11 UTC (rev 5471)
@@ -113,13 +113,29 @@
ported over to rest and included in the API so the links from the
user's guide tutorial work.
+ - There's nothing in the mathtext module that I really consider a
+ "public" API (i.e. that would be useful to people just doing
+ plots). If mathtext.py were to be documented, I would put it in
+ the developer's docs. Maybe I should just take the link in the
+ user's guide out. - MGD
+
#. This section might also benefit from a little more detail on the
customizations that are possible (eg an example fleshing out the rc
options a little bit). Admittedly, this is pretty clear from
readin ghte rc file, but it might be helpful to a newbie.
+ - The only rcParam that is currently useful is mathtext.fontset,
+ which is documented here. The others only apply when
+ mathtext.fontset == 'custom', which I'd like to declare
+ "unsupported". It's really hard to get a good set of math fonts
+ working that way, though it might be useful in a bind when
+ someone has to use a specific wacky font for mathtext and only
+ needs basics, like sub/superscripts. - MGD
+
#. There is still a TODO in the file to include a complete list of symbols
+ - Done. It's pretty extensive, thanks to STIX... - MGD
+
coding guide (reviewed by EF)
-----------------------------
Added: trunk/matplotlib/doc/sphinxext/math_symbol_table.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/math_symbol_table.py (rev 0)
+++ trunk/matplotlib/doc/sphinxext/math_symbol_table.py 2008-06-11 15:49:11 UTC (rev 5471)
@@ -0,0 +1,164 @@
+symbols = [
+ ["Lower-case Greek",
+ 5,
+ r"""\alpha \beta \gamma \chi \delta \epsilon \eta \iota \kappa
+ \lambda \mu \nu \omega \phi \pi \psi \rho \sigma \tau \theta
+ \upsilon \xi \zeta \digamma \varepsilon \varkappa \varphi
+ \varpi \varrho \varsigma \vartheta"""],
+ ["Upper-case Greek",
+ 6,
+ r"""\Delta \Gamma \Lambda \Omega \Phi \Pi \Psi \Sigma \Theta
+ \Upsilon \Xi \mho \nabla"""],
+ ["Hebrew",
+ 4,
+ r"""\aleph \beth \daleth \gimel"""],
+ ["Delimiters",
+ 6,
+ r"""| \{ \lfloor / \Uparrow \llcorner \vert \} \rfloor \backslash
+ \uparrow \lrcorner \| \langle \lceil [ \Downarrow \ulcorner
+ \Vert \rangle \rceil ] \downarrow \urcorner"""],
+ ["Big symbols",
+ 5,
+ r"""\bigcap \bigcup \bigodot \bigoplus \bigotimes \biguplus
+ \bigvee \bigwedge \coprod \oint \prod \sum \int"""],
+ ["Standard Function Names",
+ 4,
+ r"""\arccos \csc \ker \min \arcsin \deg \lg \Pr \arctan \det \lim
+ \gcd \ln \sup \cot \hom \log \tan \coth \inf \max \tanh
+ \sec \arg \dim \liminf \sin \cos \exp \limsup \sinh \cosh"""],
+ ["Binary Operation and Relation Symbols",
+ 3,
+ r"""\ast \pm \slash \cap \star \mp \cup \cdot \uplus
+ \triangleleft \circ \odot \sqcap \triangleright \bullet \ominus
+ \sqcup \bigcirc \oplus \wedge \diamond \oslash \vee
+ \bigtriangledown \times \otimes \dag \bigtriangleup \div \wr
+ \ddag \barwedge \veebar \boxplus \curlywedge \curlyvee \boxminus
+ \Cap \Cup \boxtimes \bot \top \dotplus \boxdot \intercal
+ \rightthreetimes \divideontimes \leftthreetimes \equiv \leq \geq
+ \perp \cong \prec \succ \mid \neq \preceq \succeq \parallel \sim
+ \ll \gg \bowtie \simeq \subset \supset \Join \approx \subseteq
+ \supseteq \ltimes \asymp \sqsubset \sqsupset \rtimes \doteq
+ \sqsubseteq \sqsupseteq \smile \propto \dashv \vdash \frown
+ \models \in \ni \notin \approxeq \leqq \geqq \lessgtr \leqslant
+ \geqslant \lesseqgtr \backsim \lessapprox \gtrapprox \lesseqqgtr
+ \backsimeq \lll \ggg \gtreqqless \triangleq \lessdot \gtrdot
+ \gtreqless \circeq \lesssim \gtrsim \gtrless \bumpeq \eqslantless
+ \eqslantgtr \backepsilon \Bumpeq \precsim \succsim \between
+ \doteqdot \precapprox \succapprox \pitchfork \Subset \Supset
+ \fallingdotseq \subseteqq \supseteqq \risingdotseq \sqsubset
+ \sqsupset \varpropto \preccurlyeq \succcurlyeq \Vdash \therefore
+ \curlyeqprec \curlyeqsucc \vDash \because \blacktriangleleft
+ \blacktriangleright \Vvdash \eqcirc \trianglelefteq
+ \trianglerighteq \neq \vartriangleleft \vartriangleright \ncong
+ \nleq \ngeq \nsubseteq \nmid \nsupseteq \nparallel \nless \ngtr
+ \nprec \nsucc \subsetneq \nsim \supsetneq \nVDash \precnapprox
+ \succnapprox \subsetneqq \nvDash \precnsim \succnsim \supsetneqq
+ \nvdash \lnapprox \gnapprox \ntriangleleft \ntrianglelefteq
+ \lneqq \gneqq \ntriangleright \lnsim \gnsim \ntrianglerighteq
+ \approxident \origof \imageof \coloneq \triangleeq \stareq \nsime
+ \dotminus \eqsim \nequiv \Equiv \measeq \napprox \eqless
+ \kernelcontraction \nsupset \doublebarwedge \nVdash \arceq
+ \backcong \Doteq \eqdef \wedgeq \questeq \eqgtr \cupdot
+ \veeeq \nsubset \eqcolon \ne
+ """],
+ ["Arrow Symbols",
+ 2,
+ r"""\leftarrow \longleftarrow \uparrow \Leftarrow \Longleftarrow
+ \Uparrow \rightarrow \longrightarrow \downarrow \Rightarrow
+ \Longrightarrow \Downarrow \leftrightarrow \updownarrow
+ \longleftrightarrow \updownarrow \Leftrightarrow
+ \Longleftrightarrow \Updownarrow \mapsto \longmapsto \nearrow
+ \hookleftarrow \hookrightarrow \searrow \leftharpoonup
+ \rightharpoonup \swarrow \leftharpoondown \rightharpoondown
+ \nwarrow \rightleftharpoons \leadsto \dashrightarrow
+ \dashleftarrow \leftleftarrows \leftrightarrows \Lleftarrow
+ \Rrightarrow \twoheadleftarrow \leftarrowtail \looparrowleft
+ \leftrightharpoons \curvearrowleft \circlearrowleft \Lsh
+ \upuparrows \upharpoonleft \downharpoonleft \multimap
+ \leftrightsquigarrow \rightrightarrows \rightleftarrows
+ \rightrightarrows \rightleftarrows \twoheadrightarrow
+ \rightarrowtail \looparrowright \rightleftharpoons
+ \curvearrowright \circlearrowright \Rsh \downdownarrows
+ \upharpoonright \downharpoonright \rightsquigarrow \nleftarrow
+ \nrightarrow \nLeftarrow \nRightarrow \nleftrightarrow
+ \nLeftrightarrow \to \Swarrow \Searrow \Nwarrow \Nearrow
+ \barleftarrow \mapsup \mapsdown \mapsfrom \rightarrowbar
+ \twoheaduparrow \updownarrowbar \leftsquigarrow \rightzigzagarrow
+ \twoheaddownarrow \downzigzagarrow
+ """],
+ ["Miscellaneous Symbols",
+ 3,
+ r"""\neg \invnot \turnednot \infty \forall \wp \exists \bigstar
+ \angle \partial \nexists \measuredangle \eth \emptyset
+ \sphericalangle \clubsuit \varnothing \complement \diamondsuit
+ \imath \Finv \triangledown \heartsuit \jmath \Game \spadesuit
+ \ell \hbar \vartriangle \cdots \hslash \vdots \blacksquare \ldots
+ \blacktriangle \ddots \sharp \prime \blacktriangledown \Im \flat
+ \backprime \Re \natural \circledS \P \O \copyright \ss \Ldsh
+ \frakZ \l \carriagereturn \circledR \S \sterling \L \yen \danger
+ \d \OE \AA \AE \scurel \oe \o \checkmark \Rdsh \ae \ac \prurel \$
+ \iiint \iint \iint \oiiint"""]
+]
+
+from docutils import nodes, statemachine
+from docutils.parsers.rst import Directive
+class math_symbol_table_directive(Directive):
+ has_content = True
+ def run(self):
+ def get_n(n, l):
+ part = []
+ for x in l:
+ part.append(x)
+ if len(part) == n:
+ yield part
+ part = []
+ yield part
+
+ lines = []
+ for category, columns, syms in symbols:
+ syms = syms.split()
+ syms.sort()
+ lines.append("**%s**" % category)
+ lines.append('')
+ max_width = 0
+ for sym in syms:
+ max_width = max(max_width, len(sym))
+ max_width = max_width * 2 + 16
+ header = " " + (('=' * max_width) + ' ') * columns
+ format = '%%%ds' % max_width
+ for chunk in get_n(20, get_n(columns, syms)):
+ lines.append(header)
+ for part in chunk:
+ line = []
+ for sym in part:
+ line.append(format % (":math:`%s` ``%s``" % (sym, sym)))
+ lines.append(" " + " ".join(line))
+ lines.append(header)
+ lines.append('')
+ self.state_machine.insert_input(lines, "Symbol table")
+ return []
+
+from docutils.parsers.rst import directives
+directives.register_directive('math_symbol_table',
+ math_symbol_table_directive)
+
+if __name__ == "__main__":
+ # Do some verification of the tables
+ from matplotlib import _mathtext_data
+
+ print "SYMBOLS NOT IN STIX:"
+ all_symbols = {}
+ for category, columns, syms in symbols:
+ if category == "Standard Function Names":
+ continue
+ syms = syms.split()
+ for sym in syms:
+ if len(sym) > 1:
+ all_symbols[sym[1:]] = None
+ if sym[1:] not in _mathtext_data.tex2uni:
+ print sym
+
+ print "SYMBOLS NOT IN TABLE:"
+ for sym in _mathtext_data.tex2uni:
+ if sym not in all_symbols:
+ print sym
Modified: trunk/matplotlib/doc/sphinxext/mathpng.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/mathpng.py 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/doc/sphinxext/mathpng.py 2008-06-11 15:49:11 UTC (rev 5471)
@@ -3,7 +3,7 @@
from hashlib import md5
except ImportError:
from md5 import md5
-
+
from docutils import nodes
from docutils.writers.html4css1 import HTMLTranslator
from sphinx.latexwriter import LaTeXTranslator
@@ -39,7 +39,7 @@
else:
class math_directive(Directive):
has_content = True
- def run(self):
+ def run(self):
latex = ' '.join(self.content)
node = latex_math(self.block_text)
node['latex'] = latex
@@ -75,26 +75,44 @@
LaTeXTranslator.depart_latex_math = depart_latex_math_latex
from os.path import isfile
+
+# This calls out to LaTeX to render the expression
+def latex2png(latex, name):
+ f = open('math.tex', 'w')
+ f.write(r"""\documentclass[12pt]{article}
+ \pagestyle{empty}
+ \begin{document}""")
+ if inline:
+ f.write('$%s$' % latex)
+ else:
+ f.write(r'\[ %s \]' % latex)
+ f.write('\end{document}')
+ f.close()
+ os.system('latex --interaction=nonstopmode math.tex > /dev/null')
+ os.system('dvipng -bgTransparent -Ttight --noghostscript -l10 ' +
+ '-o %s math.dvi > /dev/null' % name)
+
+# This uses mathtext to render the expression
+def latex2png(latex, filename):
+ from matplotlib import rcParams
+ from matplotlib import _png
+ from matplotlib.mathtext import MathTextParser
+ rcParams['mathtext.fontset'] = 'cm'
+ mathtext_parser = MathTextParser("Bitmap")
+ ftimage = mathtext_parser.parse("$%s$" % latex, 120)
+ _png.write_png(ftimage.as_rgba_str(), ftimage.get_width(),
+ ftimage.get_height(), filename)
+
# LaTeX to HTML translation stuff:
def latex2html(node, source):
inline = isinstance(node.parent, nodes.TextElement)
latex = node['latex']
- print latex
- name = 'math-' + md5(latex).hexdigest()[-10:]
- if not isfile('_static/%s.png' % name):
- f = open('math.tex', 'w')
- f.write(r"""\documentclass[12pt]{article}
- \pagestyle{empty}
- \begin{document}""")
- if inline:
- f.write('$%s$' % latex)
- else:
- f.write(r'\[ %s \]' % latex)
- f.write('\end{document}')
- f.close()
- os.system('latex --interaction=nonstopmode math.tex > /dev/null')
- os.system('dvipng -bgTransparent -Ttight --noghostscript -l10 ' +
- '-o _static/%s.png math.dvi > /dev/null' % name)
+ print latex.encode("ascii", "backslashreplace")
+ name = 'math-%s' % md5(latex).hexdigest()[-10:]
+ dest = '_static/%s.png' % name
+ if not isfile(dest):
+ latex2png(latex, dest)
+
path = '_static'
count = source.split('/doc/')[-1].count('/')
for i in range(count):
@@ -110,3 +128,4 @@
else:
cls = 'class="center" '
return '<img src="%s/%s.png" %s%s/>' % (path, name, align, cls)
+
Modified: trunk/matplotlib/doc/users/mathtext.rst
===================================================================
--- trunk/matplotlib/doc/users/mathtext.rst 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/doc/users/mathtext.rst 2008-06-11 15:49:11 UTC (rev 5471)
@@ -3,13 +3,11 @@
Writing mathematical expressions
================================
-
-You can use TeX markup in any matplotlib text string; see the
-:mod:`matplotlib.mathtext` module documentation for details. Note
-that you do not need to have TeX installed, since matplotlib ships its
-own TeX expression parser, layout engine and fonts. The layout engine
-is a fairly direct adaptation of the layout algorithms in Donald
-Knuth's TeX, so the quality is quite good (matplotlib also provides a
+You can use TeX markup in any matplotlib text string. Note that you
+do not need to have TeX installed, since matplotlib ships its own TeX
+expression parser, layout engine and fonts. The layout engine is a
+fairly direct adaptation of the layout algorithms in Donald Knuth's
+TeX, so the quality is quite good (matplotlib also provides a
``usetex`` option for those who do want to call out to TeX to generate
their text (see :ref:`usetex-tutorial`).
@@ -37,9 +35,6 @@
produces ":math:`\alpha > \beta`".
-.. TODO: Include a complete list here
-
-
Subscripts and superscripts
---------------------------
@@ -106,7 +101,7 @@
Radicals
--------
-Radicals can be produced with the ``\sqrt[]{}`` command. For example:
+Radicals can be produced with the ``\sqrt[]{}`` command. For example::
r'$\sqrt{2}$'
@@ -116,7 +111,7 @@
Any base can (optionally) be provided inside square brackets. Note
that the base must be a simple expression, and can not contain layout
-commands such as fractions or sub/superscripts.
+commands such as fractions or sub/superscripts::
r'$\sqrt[3]{x}$'
@@ -181,6 +176,42 @@
.. image:: ../_static/stixsans_fontset.png
+Custom fonts
+~~~~~~~~~~~~
+
+mathtext also provides a way to use custom fonts for math. This
+method is fairly tricky to use, and should be considered an
+experimental feature for patient users only. By setting the rcParam
+``mathtext.fontset`` to ``custom``, you can then set the following
+parameters, which control which font file to use for a particular set
+of math characters.
+
+ ============================== =================================
+ Parameter Corresponds to
+ ============================== =================================
+ ``mathtext.it`` ``\mathit{}`` or default italic
+ ``mathtext.rm`` ``\mathrm{}`` Roman (upright)
+ ``mathtext.tt`` ``\mathtt{}`` Typewriter (monospace)
+ ``mathtext.bf`` ``\mathbf{}`` bold italic
+ ``mathtext.cal`` ``\mathcal{}`` calligraphic
+ ``mathtext.sf`` ``\mathsf{}`` sans-serif
+ ============================== =================================
+
+Each parameter should be set to a fontconfig font descriptor (as
+defined in the yet-to-be-written font chapter).
+
+.. TODO: Link to font chapter
+
+The fonts used should have a Unicode mapping in order to find any
+non-Latin characters, such as Greek. If you want to use a math symbol
+that is not contained in your custom fonts, you can set the rcParam
+``mathtext.fallback_to_cm`` to ``True`` which will cause the mathtext
+system to use characters from the default Computer Modern fonts
+whenever a particular character can not be found in the custom font.
+
+Note that the math glyphs specified in Unicode have evolved over time,
+and many fonts may not have glyphs in the correct place for mathtext.
+
Accents
-------
@@ -211,19 +242,29 @@
``\widetilde{xyz}`` :math:`\widetilde{xyz}`
============================== =================================
+Care should be taken when putting accents on lower-case i's and j's.
+Note that in the following ``\mathi`` is used to avoid the extra dot
+over the i::
+ r"$\hat i\ \ \hat \imath$"
+
+.. math::
+
+ \hat i\ \ \hat \imath
+
Symbols
-------
You can also use a large number of the TeX symbols, as in ``\infty``,
-``\leftarrow``, ``\sum``, ``\int``; see :mod:`matplotlib.mathtext` for a
-complete list.
+``\leftarrow``, ``\sum``, ``\int``.
+.. math_symbol_table::
+
If a particular symbol does not have a name (as is true of many of the
more obscure symbols in the STIX fonts), Unicode characters can
also be used::
- ur'Generic symbol: $\u23ce$'
+ ur'$\u23ce$'
Example
-------
Modified: trunk/matplotlib/examples/pylab_examples/mathtext_examples.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/mathtext_examples.py 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/examples/pylab_examples/mathtext_examples.py 2008-06-11 15:49:11 UTC (rev 5471)
@@ -5,7 +5,7 @@
import gc
stests = [
- r'Kerning: AVA $AVA$ $$',
+ r'$x \doteq y$',
r'\$100.00 $\alpha \_$',
r'$\frac{\$100.00}{y}$',
r'$x y$',
Modified: trunk/matplotlib/lib/matplotlib/_mathtext_data.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/lib/matplotlib/_mathtext_data.py 2008-06-11 15:49:11 UTC (rev 5471)
@@ -37,6 +37,8 @@
r'\}' : ('cmex10', 130),
r'\leftangle' : ('cmex10', 97),
r'\rightangle' : ('cmex10', 64),
+ r'\langle' : ('cmex10', 97),
+ r'\rangle' : ('cmex10', 64),
r'\widehat' : ('cmex10', 15),
r'\widetilde' : ('cmex10', 52),
@@ -1758,6 +1760,54 @@
tex2uni = {
'widehat': 0x0302,
'widetilde': 0x0303,
+'langle': 0x27e8,
+'rangle': 0x27e9,
+'perp': 0x27c2,
+'neq': 0x2260,
+'Join': 0x2a1d,
+'leqslant': 0x2a7d,
+'geqslant': 0x2a7e,
+'lessapprox': 0x2a85,
+'gtrapprox': 0x2a86,
+'lesseqqgtr': 0x2a8b,
+'gtreqqless': 0x2a8c,
+'triangleeq': 0x225c,
+'eqslantless': 0x2a95,
+'eqslantgtr': 0x2a96,
+'backepsilon': 0x03f6,
+'precapprox': 0x2ab7,
+'succapprox': 0x2ab8,
+'fallingdotseq': 0x2252,
+'subseteqq': 0x2ac5,
+'supseteqq': 0x2ac6,
+'varpropto': 0x221d,
+'precnapprox': 0x2ab9,
+'succnapprox': 0x2aba,
+'subsetneqq': 0x2acb,
+'supsetneqq': 0x2acc,
+'lnapprox': 0x2ab9,
+'gnapprox': 0x2aba,
+'longleftarrow': 0x27f5,
+'longrightarrow': 0x27f6,
+'longleftrightarrow': 0x27f7,
+'Longleftarrow': 0x27f8,
+'Longrightarrow': 0x27f9,
+'Longleftrightarrow': 0x27fa,
+'longmapsto': 0x27fc,
+'leadsto': 0x21dd,
+'dashleftarrow': 0x290e,
+'dashrightarrow': 0x290f,
+'circlearrowleft': 0x21ba,
+'circlearrowright': 0x21bb,
+'leftrightsquigarrow': 0x21ad,
+'leftsquigarrow': 0x219c,
+'rightsquigarrow': 0x219d,
+'Game': 0x2141,
+'hbar': 0x0127,
+'hslash': 0x210f,
+'ldots': 0x22ef,
+'vdots': 0x22ee,
+'doteqdot': 0x2251,
'doteq': 8784,
'partial': 8706,
'gg': 8811,
@@ -1922,7 +1972,7 @@
'napprox': 8777,
'ast': 8727,
'twoheaduparrow': 8607,
-'doublebarwedge ?': 8966,
+'doublebarwedge': 8966,
'Sigma': 931,
'leftharpoonaccent': 8400,
'ntrianglelefteq': 8940,
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_agg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_agg.py 2008-06-11 15:49:11 UTC (rev 5471)
@@ -40,6 +40,7 @@
from matplotlib.transforms import Affine2D, Bbox
from _backend_agg import RendererAgg as _RendererAgg
+from matplotlib import _png
backend_version = 'v2.2'
@@ -302,5 +303,9 @@
renderer.dpi = self.figure.dpi
if is_string_like(filename_or_obj):
filename_or_obj = file(filename_or_obj, 'wb')
- self.get_renderer()._renderer.write_png(filename_or_obj, self.figure.dpi)
+ renderer = self.get_renderer()
+ x = renderer._renderer.buffer_rgba(0, 0)
+ _png.write_png(renderer._renderer.buffer_rgba(0, 0),
+ renderer.width, renderer.height,
+ filename_or_obj, self.figure.dpi)
renderer.dpi = original_dpi
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_svg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_svg.py 2008-06-11 15:49:11 UTC (rev 5471)
@@ -1,6 +1,6 @@
from __future__ import division
-import os, codecs, base64, tempfile, urllib, gzip, md5
+import os, codecs, base64, tempfile, urllib, gzip, md5, cStringIO
from matplotlib import verbose, __version__, rcParams
from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\
@@ -14,6 +14,7 @@
from matplotlib.mathtext import MathTextParser
from matplotlib.path import Path
from matplotlib.transforms import Affine2D
+from matplotlib import _png
from xml.sax.saxutils import escape as escape_xml_text
@@ -46,6 +47,7 @@
self._char_defs = {}
self._markers = {}
self._path_collection_id = 0
+ self._imaged = {}
self.mathtext_parser = MathTextParser('SVG')
svgwriter.write(svgProlog%(width,height,width,height))
@@ -267,33 +269,20 @@
)
if rcParams['svg.image_inline']:
- class Base64Writer(object):
- def __init__(self, write_method):
- self._write_method = write_method
- self._buffer = ''
- def write(self, data):
- self._buffer += data
- while len(self._buffer) >= 64:
- self._write_method(base64.encodestring(buffer[:64]))
- self._write_method('\n')
- self._buffer = self._buffer[64:]
- def flush(self):
- self._write_method(base64.encodestring(self._buffer))
- self._write_method('\n')
-
self._svgwriter.write("data:image/png;base64,\n")
- base64writer = Base64Writer(self._svgwriter.write)
-
+ stringio = cStringIO.StringIO()
im.flipud_out()
- im.write_png(base64writer)
+ rows, cols, buffer = im.as_rgba_str()
+ _png.write_png(buffer, cols, rows, stringio)
im.flipud_out()
- base64writer.flush()
+ self._svgwriter.write(base64.encodestring(stringio.getvalue()))
else:
self._imaged[self.basename] = self._imaged.get(self.basename,0) + 1
filename = '%s.image%d.png'%(self.basename, self._imaged[self.basename])
verbose.report( 'Writing image file for inclusion: %s' % filename)
im.flipud_out()
- im.write_png(filename)
+ rows, cols, buffer = im.as_rgba_str()
+ _png.write_png(buffer, cols, rows, filename)
im.flipud_out()
self._svgwriter.write(filename)
Modified: trunk/matplotlib/lib/matplotlib/image.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/image.py 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/lib/matplotlib/image.py 2008-06-11 15:49:11 UTC (rev 5471)
@@ -16,6 +16,7 @@
# For clarity, names from _image are given explicitly in this module:
from matplotlib import _image
+from matplotlib import _png
# For user convenience, the names from _image are also imported into
# the image namespace:
@@ -256,12 +257,13 @@
"""Write the image to png file with fname"""
im = self.make_image()
if noscale:
- numrows,numcols = im.get_size()
+ numrows, numcols = im.get_size()
im.reset_matrix()
im.set_interpolation(0)
im.resize(numcols, numrows)
im.flipud_out()
- im.write_png(fname)
+ rows, cols, buffer = im.as_rgba_str()
+ _png.write_png(buffer, cols, rows, fname)
def set_data(self, A, shape=None):
"""
@@ -661,7 +663,8 @@
def write_png(self, fname):
"""Write the image to png file with fname"""
im = self.make_image()
- im.write_png(fname)
+ rows, cols, buffer = im.as_rgba_str()
+ _png.write_png(buffer, cols, rows, fname)
def imread(fname):
"""
@@ -686,7 +689,7 @@
return pil_to_array(image)
- handlers = {'png' :_image.readpng,
+ handlers = {'png' :_png.read_png,
}
basename, ext = os.path.splitext(fname)
ext = ext.lower()[1:]
Modified: trunk/matplotlib/lib/matplotlib/mathtext.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-11 15:49:11 UTC (rev 5471)
@@ -655,8 +655,9 @@
return xHeight
def get_underline_thickness(self, font, fontsize, dpi):
- cached_font = self._get_font(font)
- return (cached_font.font.underline_thickness / 64.0 / fontsize) * (dpi)
+ # This function used to grab underline thickness from the font,
+ # but that information is just too un-reliable, so it is now hardcoded.
+ return ((0.75 / 12.0) * fontsize * dpi) / 72.0
def get_kern(self, font1, fontclass1, sym1, fontsize1,
font2, fontclass2, sym2, fontsize2, dpi):
@@ -682,6 +683,8 @@
fontmap = {}
def __init__(self, *args, **kwargs):
+ self._stix_fallback = StixFonts(*args, **kwargs)
+
TruetypeFonts.__init__(self, *args, **kwargs)
if not len(self.fontmap):
for key, val in self._fontmap.iteritems():
@@ -689,6 +692,7 @@
self.fontmap[key] = fullpath
self.fontmap[val] = fullpath
+
_slanted_symbols = Set(r"\int \oint".split())
def _get_glyph(self, fontname, font_class, sym, fontsize):
@@ -717,6 +721,7 @@
cached_font.charmap[num])
if symbol_name is None:
+ return self._stix_fallback._get_glyph(fontname, font_class, sym, fontsize)
warn("Unrecognized symbol '%s'. Substituting with a dummy symbol."
% sym.encode('ascii', 'backslashreplace'), MathTextWarning)
fontname = 'it'
@@ -868,6 +873,8 @@
return self.cm_fallback._get_glyph(
fontname, 'it', sym, fontsize)
else:
+ if fontname == 'it' and isinstance(self, StixFonts):
+ return self._get_glyph('rm', font_class, sym, fontsize)
warn("Substituting with a dummy symbol.", MathTextWarning)
fontname = 'rm'
new_fontname = fontname
@@ -2031,7 +2038,8 @@
bslash = Literal('\\')
- accent = oneOf(self._accent_map.keys() + list(self._wide_accents))
+ accent = oneOf(self._accent_map.keys() +
+ list(self._wide_accents))
function = oneOf(list(self._function_names))
@@ -2057,10 +2065,10 @@
unicode_range = u"\U00000080-\U0001ffff"
symbol =(Regex(UR"([a-zA-Z0-9 +\-*/<>=:,.;!'@()\[\]|%s])|(\\[%%${}\[\]_|])" % unicode_range)
- | Combine(
+ | (Combine(
bslash
+ oneOf(tex2uni.keys())
- )
+ ) + FollowedBy(Regex("[^a-zA-Z]")))
).setParseAction(self.symbol).leaveWhitespace()
c_over_c =(Suppress(bslash)
@@ -2486,14 +2494,14 @@
if super is not None:
hlist = HCentered([super])
hlist.hpack(width, 'exactly')
- vlist.extend([hlist, Kern(rule_thickness * 2.0)])
+ vlist.extend([hlist, Kern(rule_thickness * 3.0)])
hlist = HCentered([nucleus])
hlist.hpack(width, 'exactly')
vlist.append(hlist)
if sub is not None:
hlist = HCentered([sub])
hlist.hpack(width, 'exactly')
- vlist.extend([Kern(rule_thickness * 2.0), hlist])
+ vlist.extend([Kern(rule_thickness * 3.0), hlist])
shift = hlist.height + hlist.depth + rule_thickness * 2.0
vlist = Vlist(vlist)
vlist.shift_amount = shift + nucleus.depth * 0.5
Modified: trunk/matplotlib/lib/matplotlib/texmanager.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/texmanager.py 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/lib/matplotlib/texmanager.py 2008-06-11 15:49:11 UTC (rev 5471)
@@ -38,7 +38,7 @@
import numpy as np
import matplotlib as mpl
from matplotlib import rcParams
-from matplotlib._image import readpng
+from matplotlib._png import read_png
DEBUG = False
@@ -364,7 +364,7 @@
if alpha is None:
pngfile = self.make_png(tex, fontsize, dpi)
- X = readpng(os.path.join(self.texcache, pngfile))
+ X = read_png(os.path.join(self.texcache, pngfile))
if rcParams['text.dvipnghack'] is not None:
hack = rcParams['text.dvipnghack']
Modified: trunk/matplotlib/matplotlibrc.template
===================================================================
--- trunk/matplotlib/matplotlibrc.template 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/matplotlibrc.template 2008-06-11 15:49:11 UTC (rev 5471)
@@ -162,6 +162,8 @@
# The following settings allow you to select the fonts in math mode.
# They map from a TeX font name to a fontconfig font pattern.
# These settings are only used if mathtext.fontset is 'custom'.
+# Note that this "custom" mode is unsupported and may go away in the
+# future.
#mathtext.cal : cursive
#mathtext.rm : serif
#mathtext.tt : monospace
Modified: trunk/matplotlib/setup.py
===================================================================
--- trunk/matplotlib/setup.py 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/setup.py 2008-06-11 15:49:11 UTC (rev 5471)
@@ -34,7 +34,7 @@
check_for_cairo, check_provide_traits, check_provide_pytz, \
check_provide_dateutil, check_provide_configobj, check_for_dvipng, \
check_for_ghostscript, check_for_latex, check_for_pdftops, \
- check_for_datetime, options
+ check_for_datetime, options, build_png
#import distutils.sysconfig
# jdh
@@ -100,16 +100,20 @@
print_raw("")
print_raw("OPTIONAL BACKEND DEPENDENCIES")
+has_libpng = check_for_libpng()
-if check_for_libpng() and options['build_agg']:
+if has_libpng and options['build_agg']:
build_agg(ext_modules, packages)
rc['backend'] = 'Agg'
else:
rc['backend'] = 'SVG'
-if options['build_image']:
+if has_libpng and options['build_image']:
build_image(ext_modules, packages)
+if has_libpng and options['build_agg'] or options['build_image']:
+ build_png(ext_modules, packages)
+
if options['build_windowing'] and sys.platform=='win32':
build_windowing(ext_modules, packages)
Modified: trunk/matplotlib/setupext.py
===================================================================
--- trunk/matplotlib/setupext.py 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/setupext.py 2008-06-11 15:49:11 UTC (rev 5471)
@@ -79,6 +79,7 @@
True = True
False = False
+BUILT_PNG = False
BUILT_AGG = False
BUILT_FT2FONT = False
BUILT_TTCONV = False
@@ -248,9 +249,6 @@
status, output = commands.getstatusoutput(
"%s %s %s" % (pkg_config_exec, flags, packages))
- #if packages.startswith('pygtk'):
- # print 'status', status, output
- # raise SystemExit
if status == 0:
for token in output.split():
attr = _flags.get(token[:2], None)
@@ -570,12 +568,18 @@
import numpy
module.include_dirs.append(numpy.get_include())
+def add_png_flags(module):
+ try_pkgconfig(module, 'libpng', 'png')
+ add_base_flags(module)
+ add_numpy_flags(module)
+ module.libraries.append('z')
+ module.include_dirs.extend(['.'])
+ module.libraries.extend(std_libs)
+
def add_agg_flags(module):
'Add the module flags to build extensions which use agg'
# before adding the freetype flags since -z comes later
- try_pkgconfig(module, 'libpng', 'png')
- module.libraries.append('z')
add_base_flags(module)
add_numpy_flags(module)
module.include_dirs.extend(['src', '%s/include'%AGG_VERSION, '.'])
@@ -1201,7 +1205,26 @@
ext_modules.append(module)
BUILT_WXAGG = True
+def build_png(ext_modules, packages):
+ global BUILT_PNG
+ if BUILT_PNG: return # only build it if you you haven't already
+ deps = ['src/_png.cpp', 'src/mplutils.cpp']
+ deps.extend(glob.glob('CXX/*.cxx'))
+ deps.extend(glob.glob('CXX/*.c'))
+
+ module = Extension(
+ 'matplotlib._png',
+ deps,
+ include_dirs=numpy_inc_dirs,
+ )
+
+ add_png_flags(module)
+ ext_modules.append(module)
+
+ BUILT_PNG = True
+
+
def build_agg(ext_modules, packages):
global BUILT_AGG
if BUILT_AGG: return # only build it if you you haven't already
Modified: trunk/matplotlib/src/_backend_agg.cpp
===================================================================
--- trunk/matplotlib/src/_backend_agg.cpp 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/src/_backend_agg.cpp 2008-06-11 15:49:11 UTC (rev 5471)
@@ -1356,136 +1356,7 @@
return Py::Object();
}
-static void write_png_data(png_structp png_ptr, png_bytep data, png_size_t length) {
- PyObject* py_file_obj = (PyObject*)png_get_io_ptr(png_ptr);
- PyObject* write_method = PyObject_GetAttrString(py_file_obj, "write");
- PyObject* result = NULL;
- if (write_method)
- result = PyObject_CallFunction(write_method, (char *)"s#", data, length);
- Py_XDECREF(write_method);
- Py_XDECREF(result);
-}
-
-static void flush_png_data(png_structp png_ptr) {
- PyObject* py_file_obj = (PyObject*)png_get_io_ptr(png_ptr);
- PyObject* flush_method = PyObject_GetAttrString(py_file_obj, "flush");
- PyObject* result = NULL;
- if (flush_method)
- result = PyObject_CallFunction(flush_method, (char *)"");
- Py_XDECREF(flush_method);
- Py_XDECREF(result);
-}
-
-// this code is heavily adapted from the paint license, which is in
-// the file paint.license (BSD compatible) included in this
-// distribution. TODO, add license file to MANIFEST.in and CVS
Py::Object
-RendererAgg::write_png(const Py::Tuple& args)
-{
- _VERBOSE("RendererAgg::write_png");
-
- args.verify_length(1, 2);
-
- FILE *fp = NULL;
- bool close_file = false;
- Py::Object py_fileobj = Py::Object(args[0]);
- if (py_fileobj.isString()) {
- std::string fileName = Py::String(py_fileobj);
- const char *file_name = fileName.c_str();
- if ((fp = fopen(file_name, "wb")) == NULL)
- throw Py::RuntimeError( Printf("Could not open file %s", file_name).str() );
- close_file = true;
- } else if (PyFile_CheckExact(py_fileobj.ptr())) {
- fp = PyFile_AsFile(py_fileobj.ptr());
- }
- else {
- PyObject* write_method = PyObject_GetAttrString(py_fileobj.ptr(), "write");
- if (!(write_method && PyCallable_Check(write_method))) {
- Py_XDECREF(write_method);
- throw Py::TypeError("Object does not appear to be a 8-bit string path or a Python file-like object");
- }
- Py_XDECREF(write_method);
- }
-
- png_bytep *row_pointers = NULL;
- png_structp png_ptr = NULL;
- png_infop info_ptr = NULL;
-
- try {
- struct png_color_8_struct sig_bit;
- png_uint_32 row;
-
- row_pointers = new png_bytep[height];
- for (row = 0; row < height; ++row) {
- row_pointers[row] = pixBuffer + row * width * 4;
- }
-
- png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
- if (png_ptr == NULL) {
- throw Py::RuntimeError("Could not create write struct");
- }
-
- info_ptr = png_create_info_struct(png_ptr);
- if (info_ptr == NULL) {
- throw Py::RuntimeError("Could not create info struct");
- }
-
- if (setjmp(png_ptr->jmpbuf)) {
- throw Py::RuntimeError("Error building image");
- }
-
- if (fp) {
- png_init_io(png_ptr, fp);
- } else {
- png_set_write_fn(png_ptr, (void*)py_fileobj.ptr(),
- &write_png_data, &flush_png_data);
- }
- png_set_IHDR(png_ptr, info_ptr,
- width, height, 8,
- PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
- PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
-
- // Save the dpi of the image in the file
- if (args.size() == 2) {
- double dpi = Py::Float(args[1]);
- size_t dots_per_meter = (size_t)(dpi / (2.54 / 100.0));
- png_set_pHYs(png_ptr, info_ptr, dots_per_meter, dots_per_meter, PNG_RESOLUTION_METER);
- }
-
- // this a a color image!
- sig_bit.gray = 0;
- sig_bit.red = 8;
- sig_bit.green = 8;
- sig_bit.blue = 8;
- /* if the image has an alpha channel then */
- sig_bit.alpha = 8;
- png_set_sBIT(png_ptr, info_ptr, &sig_bit);
-
- png_write_info(png_ptr, info_ptr);
- png_write_image(png_ptr, row_pointers);
- png_write_end(png_ptr, info_ptr);
-
-
- } catch (...) {
- if (fp && close_file) fclose(fp);
- delete [] row_pointers;
- /* Changed calls to png_destroy_write_struct to follow
- http://www.libpng.org/pub/png/libpng-manual.txt.
- This ensures the info_ptr memory is released.
- */
- if (png_ptr && info_ptr) png_destroy_write_struct(&png_ptr, &info_ptr);
- throw;
- }
-
- png_destroy_write_struct(&png_ptr, &info_ptr);
- delete [] row_pointers;
- if (fp && close_file) fclose(fp);
-
- return Py::Object();
-}
-
-
-Py::Object
RendererAgg::tostring_rgb(const Py::Tuple& args) {
//"Return the rendered buffer as an RGB string";
@@ -1763,8 +1634,6 @@
"draw_image(x, y, im)");
add_varargs_method("write_rgba", &RendererAgg::write_rgba,
"write_rgba(fname)");
- add_varargs_method("write_png", &RendererAgg::write_png,
- "write_png(fname, dpi=None)");
add_varargs_method("tostring_rgb", &RendererAgg::tostring_rgb,
"s = tostring_rgb()");
add_varargs_method("tostring_argb", &RendererAgg::tostring_argb,
Modified: trunk/matplotlib/src/_backend_agg.h
===================================================================
--- trunk/matplotlib/src/_backend_agg.h 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/src/_backend_agg.h 2008-06-11 15:49:11 UTC (rev 5471)
@@ -176,7 +176,6 @@
Py::Object write_rgba(const Py::Tuple & args);
- Py::Object write_png(const Py::Tuple & args);
Py::Object tostring_rgb(const Py::Tuple & args);
Py::Object tostring_argb(const Py::Tuple & args);
Py::Object tostring_bgra(const Py::Tuple & args);
Modified: trunk/matplotlib/src/_image.cpp
===================================================================
--- trunk/matplotlib/src/_image.cpp 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/src/_image.cpp 2008-06-11 15:49:11 UTC (rev 5471)
@@ -1,11 +1,9 @@
-#include <png.h>
-
// To remove a gcc warning
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif
-#include "Python.h" //after png.h due to setjmp bug
+#include "Python.h"
#include <string>
#include <iostream>
@@ -644,131 +642,7 @@
return Py::Object();
}
-static void write_png_data(png_structp png_ptr, png_bytep data, png_size_t length) {
- PyObject* py_file_obj = (PyObject*)png_get_io_ptr(png_ptr);
- PyObject* write_method = PyObject_GetAttrString(py_file_obj, "write");
- PyObject* result = NULL;
- if (write_method)
- result = PyObject_CallFunction(write_method, (char *)"s#", data, length);
- Py_XDECREF(write_method);
- Py_XDECREF(result);
-}
-static void flush_png_data(png_structp png_ptr) {
- PyObject* py_file_obj = (PyObject*)png_get_io_ptr(png_ptr);
- PyObject* flush_method = PyObject_GetAttrString(py_file_obj, "flush");
- PyObject* result = NULL;
- if (flush_method)
- result = PyObject_CallFunction(flush_method, (char *)"");
- Py_XDECREF(flush_method);
- Py_XDECREF(result);
-}
-
-// this code is heavily adapted from the paint license, which is in
-// the file paint.license (BSD compatible) included in this
-// distribution. TODO, add license file to MANIFEST.in and CVS
-char Image::write_png__doc__[] =
-"write_png(fname)\n"
-"\n"
-"Write the image to filename fname as png\n"
-;
-Py::Object
-Image::write_png(const Py::Tuple& args)
-{
- //small memory leak in this function - JDH 2004-06-08
- _VERBOSE("Image::write_png");
-
- args.verify_length(1);
-
- FILE *fp = NULL;
- Py::Object py_fileobj = Py::Object(args[0]);
- if (py_fileobj.isString()) {
- std::string fileName = Py::String(py_fileobj);
- const char *file_name = fileName.c_str();
- if ((fp = fopen(file_name, "wb")) == NULL)
- throw Py::RuntimeError( Printf("Could not open file %s", file_name).str() );
- }
- else {
- PyObject* write_method = PyObject_GetAttrString(py_fileobj.ptr(), "write");
- if (!(write_method && PyCallable_Check(write_method))) {
- Py_XDECREF(write_method);
- throw Py::TypeError("Object does not appear to be a path or a Python file-like object");
- }
- Py_XDECREF(write_method);
- }
-
- png_structp png_ptr;
- png_infop info_ptr;
- struct png_color_8_struct sig_bit;
- png_uint_32 row=0;
-
- //todo: allocate on heap
- png_bytep *row_pointers = NULL;
- std::pair<agg::int8u*,bool> bufpair;
- bufpair.first = NULL;
- bufpair.second = false;
-
- try {
- row_pointers = new png_bytep[rowsOut];
- if (!row_pointers)
- throw Py::RuntimeError("Out of memory");
-
- bufpair = _get_output_buffer();
- for (row = 0; row < rowsOut; ++row)
- row_pointers[row] = bufpair.first + row * colsOut * 4;
-
- png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
- if (png_ptr == NULL)
- throw Py::RuntimeError("Could not create write struct");
-
- info_ptr = png_create_info_struct(png_ptr);
- if (info_ptr == NULL)
- throw Py::RuntimeError("Could not create info struct");
-
- if (setjmp(png_ptr->jmpbuf))
- throw Py::RuntimeError("Error building image");
-
- if (fp) {
- png_init_io(png_ptr, fp);
- } else {
- png_set_write_fn(png_ptr, (void*)py_fileobj.ptr(),
- &write_png_data, &flush_png_data);
- }
- png_set_IHDR(png_ptr, info_ptr,
- colsOut, rowsOut, 8,
- PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
- PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
-
- // this a a color image!
- sig_bit.gray = 0;
- sig_bit.red = 8;
- sig_bit.green = 8;
- sig_bit.blue = 8;
- /* if the image has an alpha channel then */
- sig_bit.alpha = 8;
- png_set_sBIT(png_ptr, info_ptr, &sig_bit);
-
- png_write_info(png_ptr, info_ptr);
- png_write_image(png_ptr, row_pointers);
- png_write_end(png_ptr, info_ptr);
- png_destroy_write_struct(&png_ptr, &info_ptr);
- } catch (...) {
- if (bufpair.second) delete [] bufpair.first;
- if (fp) fclose(fp);
- png_destroy_write_struct(&png_ptr, &info_ptr);
- delete [] row_pointers;
- throw;
- }
-
- if (fp) fclose(fp);
- delete [] row_pointers;
- if (bufpair.second) delete [] bufpair.first;
-
- return Py::Object();
-}
-
-
-
char Image::set_aspect__doc__[] =
"set_aspect(scheme)\n"
"\n"
@@ -812,7 +686,6 @@
add_varargs_method( "set_interpolation", &Image::set_interpolation, Image::set_interpolation__doc__);
add_varargs_method( "set_resample", &Image::set_resample, Image::set_resample__doc__);
add_varargs_method( "set_aspect", &Image::set_aspect, Image::set_aspect__doc__);
- add_varargs_method( "write_png", &Image::write_png, Image::write_png__doc__);
add_varargs_method( "set_bg", &Image::set_bg, Image::set_bg__doc__);
add_varargs_method( "flipud_out", &Image::flipud_out, Image::flipud_out__doc__);
add_varargs_method( "flipud_in", &Image::flipud_in, Image::flipud_in__doc__);
@@ -901,118 +774,6 @@
}
-
-char _image_module_readpng__doc__[] =
-"readpng(fname)\n"
-"\n"
-"Load an image from png file into a numerix array of MxNx4 float";
-Py::Object
-_image_module::readpng(const Py::Tuple& args) {
-
- args.verify_length(1);
- std::string fname = Py::String(args[0]);
-
- png_byte header[8]; // 8 is the maximum size that can be checked
-
- FILE *fp = fopen(fname.c_str(), "rb");
- if (!fp)
- throw Py::RuntimeError(Printf("_image_module::readpng could not open PNG file %s for reading", fname.c_str()).str());
-
- if (fread(header, 1, 8, fp) != 8)
- throw Py::RuntimeError("_image_module::readpng: error reading PNG header");
- if (png_sig_cmp(header, 0, 8))
- throw Py::RuntimeError("_image_module::readpng: file not recognized as a PNG file");
-
-
- /* initialize stuff */
- png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
-
- if (!png_ptr)
- throw Py::RuntimeError("_image_module::readpng: png_create_read_struct failed");
-
- png_infop info_ptr = png_create_info_struct(png_ptr);
- if (!info_ptr)
- throw Py::RuntimeError("_image_module::readpng: png_create_info_struct failed");
-
- if (setjmp(png_jmpbuf(png_ptr)))
- throw Py::RuntimeError("_image_module::readpng: error during init_io");
-
- png_init_io(png_ptr, fp);
- png_set_sig_bytes(png_ptr, 8);
-
- png_read_info(png_ptr, info_ptr);
-
- png_uint_32 width = info_ptr->width;
- png_uint_32 height = info_ptr->height;
-
- // convert misc color types to rgb for simplicity
- if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY ||
- info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
- png_set_gray_to_rgb(png_ptr);
- else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
- png_set_palette_to_rgb(png_ptr);
-
-
- int bit_depth = info_ptr->bit_depth;
- if (bit_depth == 16) png_set_strip_16(png_ptr);
-
-
- png_set_interlace_handling(png_ptr);
- png_read_update_info(png_ptr, info_ptr);
-
- bool rgba = info_ptr->color_type == PNG_COLOR_TYPE_RGBA;
- if ( (info_ptr->color_type != PNG_COLOR_TYPE_RGB) && !rgba) {
- std::cerr << "Found color type " << (int)info_ptr->color_type << std::endl;
- throw Py::RuntimeError("_image_module::readpng: cannot handle color_type");
- }
-
- /* read file */
- if (setjmp(png_jmpbuf(png_ptr)))
- throw Py::RuntimeError("_image_module::readpng: error during read_image");
-
- png_bytep *row_pointers = new png_bytep[height];
- png_uint_32 row;
-
- for (row = 0; row < height; row++)
- row_pointers[row] = new png_byte[png_get_rowbytes(png_ptr,info_ptr)];
-
- png_read_image(png_ptr, row_pointers);
-
-
-
- int dimensions[3];
- dimensions[0] = height; //numrows
- dimensions[1] = width; //numcols
- dimensions[2] = 4;
-
- PyArrayObject *A = (PyArrayObject *) PyArray_FromDims(3, dimensions, PyArray_FLOAT);
-
-
- for (png_uint_32 y = 0; y < height; y++) {
- png_byte* row = row_pointers[y];
- for (png_uint_32 x = 0; x < width; x++) {
-
- png_byte* ptr = (rgba) ? &(row[x*4]) : &(row[x*3]);
- size_t offset = y*A->strides[0] + x*A->strides[1];
- //if ((y<10)&&(x==10)) std::cout << "r = " << ptr[0] << " " << ptr[0]/255.0 << std::endl;
- *(float*)(A->data + offset + 0*A->strides[2]) = (float)(ptr[0]/255.0f);
- *(float*)(A->data + offset + 1*A->strides[2]) = (float)(ptr[1]/255.0f);
- *(float*)(A->data + offset + 2*A->strides[2]) = (float)(ptr[2]/255.0f);
- *(float*)(A->data + offset + 3*A->strides[2]) = rgba ? (float)(ptr[3]/255.0f) : 1.0f;
- }
- }
-
- //free the png memory
- png_read_end(png_ptr, info_ptr);
- png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);
- fclose(fp);
- for (row = 0; row < height; row++)
- delete [] row_pointers[row];
- delete [] row_pointers;
- return Py::asObject((PyObject*)A);
-}
-
-
char _image_module_fromarray__doc__[] =
"fromarray(A, isoutput)\n"
"\n"
Modified: trunk/matplotlib/src/_image.h
===================================================================
--- trunk/matplotlib/src/_image.h 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/src/_image.h 2008-06-11 15:49:11 UTC (rev 5471)
@@ -38,7 +38,6 @@
Py::Object get_interpolation(const Py::Tuple& args);
Py::Object set_interpolation(const Py::Tuple& args);
Py::Object set_aspect(const Py::Tuple& args);
- Py::Object write_png(const Py::Tuple& args);
Py::Object set_bg(const Py::Tuple& args);
Py::Object flipud_out(const Py::Tuple& args);
Py::Object flipud_in(const Py::Tuple& args);
@@ -100,7 +99,6 @@
static char get_interpolation__doc__[];
static char set_interpolation__doc__[];
static char set_aspect__doc__[];
- static char write_png__doc__[];
static char set_bg__doc__[];
static char flipud_out__doc__[];
static char flipud_in__doc__[];
@@ -133,8 +131,6 @@
"frombyte");
add_varargs_method("frombuffer", &_image_module::frombuffer,
"frombuffer");
- add_varargs_method("readpng", &_image_module::readpng,
- "readpng");
add_varargs_method("from_images", &_image_module::from_images,
"from_images");
add_varargs_method("pcolor", &_image_module::pcolor,
@@ -153,7 +149,6 @@
Py::Object fromarray2 (const Py::Tuple &args);
Py::Object pcolor (const Py::Tuple &args);
Py::Object pcolor2 (const Py::Tuple &args);
- Py::Object readpng (const Py::Tuple &args);
Py::Object from_images (const Py::Tuple &args);
static char _image_module_fromarray__doc__[];
Modified: trunk/matplotlib/src/ft2font.cpp
===================================================================
--- trunk/matplotlib/src/ft2font.cpp 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/src/ft2font.cpp 2008-06-11 15:49:11 UTC (rev 5471)
@@ -69,7 +69,9 @@
delete _rgbaCopy;
}
-void FT2Image::resize(unsigned long width, unsigned long height) {
+void FT2Image::resize(long width, long height) {
+ if (width < 0) width = 1;
+ if (height < 0) height = 1;
size_t numBytes = width*height;
if (width != _width || height != _height) {
Modified: trunk/matplotlib/src/ft2font.h
===================================================================
--- trunk/matplotlib/src/ft2font.h 2008-06-11 15:31:21 UTC (rev 5470)
+++ trunk/matplotlib/src/ft2font.h 2008-06-11 15:49:11 UTC (rev 5471)
@@ -66,7 +66,7 @@
void makeRgbCopy();
void makeRgbaCopy();
- void resize(unsigned long width, unsigned long height);
+ void resize(long width, long height);
};
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-11 15:31:23
|
Revision: 5470
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5470&view=rev
Author: jdh2358
Date: 2008-06-11 08:31:21 -0700 (Wed, 11 Jun 2008)
Log Message:
-----------
fixed a text layout bug where layout was cached between renderers
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/text.py
Modified: trunk/matplotlib/lib/matplotlib/text.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/text.py 2008-06-11 12:37:21 UTC (rev 5469)
+++ trunk/matplotlib/lib/matplotlib/text.py 2008-06-11 15:31:21 UTC (rev 5470)
@@ -394,7 +394,7 @@
return (x, y, self._text, self._color,
self._verticalalignment, self._horizontalalignment,
hash(self._fontproperties), self._rotation,
- self._renderer.dpi
+ self._renderer.dpi, id(self._renderer)
)
def get_text(self):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-06-11 12:37:33
|
Revision: 5469
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5469&view=rev
Author: jswhit
Date: 2008-06-11 05:37:21 -0700 (Wed, 11 Jun 2008)
Log Message:
-----------
add material to users guide
Modified Paths:
--------------
trunk/toolkits/basemap/doc/users/index.rst
Added Paths:
-----------
trunk/toolkits/basemap/doc/users/figures/ortho_full.png
trunk/toolkits/basemap/doc/users/figures/ortho_full.py
trunk/toolkits/basemap/doc/users/figures/ortho_partial.png
trunk/toolkits/basemap/doc/users/figures/ortho_partial.py
trunk/toolkits/basemap/doc/users/mapsetup.rst
trunk/toolkits/basemap/doc/users/ortho.rst
Added: trunk/toolkits/basemap/doc/users/figures/ortho_full.png
===================================================================
(Binary files differ)
Property changes on: trunk/toolkits/basemap/doc/users/figures/ortho_full.png
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/toolkits/basemap/doc/users/figures/ortho_full.py
===================================================================
--- trunk/toolkits/basemap/doc/users/figures/ortho_full.py (rev 0)
+++ trunk/toolkits/basemap/doc/users/figures/ortho_full.py 2008-06-11 12:37:21 UTC (rev 5469)
@@ -0,0 +1,14 @@
+from mpl_toolkits.basemap import Basemap
+import numpy as np
+import matplotlib.pyplot as plt
+# lon_0, lat_0 are the center point of the projection.
+# resolution = 'l' means use low resolution coastlines.
+m = Basemap(projection='ortho',lon_0=-105,lat_0=40,resolution='l')
+m.drawcoastlines()
+m.fillcontinents(color='coral',lake_color='aqua')
+# draw parallels and meridians.
+m.drawparallels(np.arange(-90.,120.,30.))
+m.drawmeridians(np.arange(0.,420.,60.))
+m.drawmapboundary(fill_color='aqua')
+plt.title("Full Disk Orthographic Projection")
+plt.savefig('ortho_full.png')
Added: trunk/toolkits/basemap/doc/users/figures/ortho_partial.png
===================================================================
(Binary files differ)
Property changes on: trunk/toolkits/basemap/doc/users/figures/ortho_partial.png
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/toolkits/basemap/doc/users/figures/ortho_partial.py
===================================================================
--- trunk/toolkits/basemap/doc/users/figures/ortho_partial.py (rev 0)
+++ trunk/toolkits/basemap/doc/users/figures/ortho_partial.py 2008-06-11 12:37:21 UTC (rev 5469)
@@ -0,0 +1,28 @@
+from mpl_toolkits.basemap import Basemap
+import numpy as np
+import matplotlib.pyplot as plt
+fig = plt.figure()
+# global ortho map centered on lon_0,lat_0
+lat_0=10.; lon_0=57.
+# resolution = None means don't process the boundary datasets.
+m1 = Basemap(projection='ortho',lon_0=lon_0,lat_0=lat_0,resolution=None)
+# add an axes with a black background
+ax = fig.add_axes([0.1,0.1,0.8,0.8],axisbg='k')
+# plot just upper right quadrant (corners determined from global map).
+# keywords llcrnrx,llcrnry,urcrnrx,urcrnry used to define the lower
+# left and upper right corners in map projection coordinates.
+# llcrnrlat,llcrnrlon,ucrnrlon,urcrnrlat could be used to define
+# lat/lon values of corners - but this won't work in cases such as this
+# where one of the corners does not lie on the earth.
+m = Basemap(projection='ortho',lon_0=lon_0,lat_0=lat_0,resolution='l',\
+ llcrnrx=0.,llcrnry=0.,urcrnrx=m1.urcrnrx/2.,urcrnry=m1.urcrnry/2.)
+m.drawcoastlines()
+m.drawmapboundary(fill_color='aqua')
+m.fillcontinents(color='coral',lake_color='aqua')
+m.drawcountries()
+# draw parallels and meridians.
+m.drawparallels(np.arange(-90.,120.,30.))
+m.drawmeridians(np.arange(0.,360.,60.))
+m.drawmapboundary()
+plt.title('Orthographic Map Showing A Quadrant of the Globe')
+plt.savefig('ortho_partial.png')
Modified: trunk/toolkits/basemap/doc/users/index.rst
===================================================================
--- trunk/toolkits/basemap/doc/users/index.rst 2008-06-11 12:23:05 UTC (rev 5468)
+++ trunk/toolkits/basemap/doc/users/index.rst 2008-06-11 12:37:21 UTC (rev 5469)
@@ -10,3 +10,4 @@
.. toctree::
intro.rst
+ mapsetup.rst
Added: trunk/toolkits/basemap/doc/users/mapsetup.rst
===================================================================
--- trunk/toolkits/basemap/doc/users/mapsetup.rst (rev 0)
+++ trunk/toolkits/basemap/doc/users/mapsetup.rst 2008-06-11 12:37:21 UTC (rev 5469)
@@ -0,0 +1,31 @@
+.. _mapsetup:
+
+Setting up the map
+==================
+
+In order to represent the curved surface of the earth on a two-dimensional
+map, a map projection is needed. Since this cannot be done without
+distortion, there are many map projections, each with it's own advantages
+and disadvantages. Basemap provides 19 different map projections.
+Some are global, some can only represent a portion of the globe. When
+a Basemap class instance is created, the desired map projection must
+be specified, along with information about the portion of the earth's
+surface that the map projection will describe. There are two basic
+ways of doing this. One is to provide the latitude and longitude values
+of each of the four corners of the rectangular map projection region.
+The other is to provide the lat/lon value of the center of the map
+projection region along with the width and height of the region in
+map projection coordinates.
+
+The class variable ``supported_projections`` is a dictionary containing
+information about all the projections supported by Basemap. The keys
+are the short names (used with the ``projection`` keyword to define
+a projection when creating a ``Basemap`` class instance), and the values
+are longer, more descriptive names. The class variable ``projection_params``
+is a dictionary that provides a list of parameters that can be used to
+define the properties of each projection. Following are examples that
+illustrate how to set up each of the supported projections.
+
+.. toctree::
+
+ ortho.rst
Added: trunk/toolkits/basemap/doc/users/ortho.rst
===================================================================
--- trunk/toolkits/basemap/doc/users/ortho.rst (rev 0)
+++ trunk/toolkits/basemap/doc/users/ortho.rst 2008-06-11 12:37:21 UTC (rev 5469)
@@ -0,0 +1,15 @@
+.. _ortho:
+
+Orthographic Projection
+=======================
+
+The orthographic projection displays the earth as a satellite
+(in an orbit infinitely high above the earth) would see it.
+
+.. literalinclude:: figures/ortho_full.py
+
+.. image:: figures/ortho_full.png
+
+.. literalinclude:: figures/ortho_partial.py
+
+.. image:: figures/ortho_partial.png
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-11 12:24:52
|
Revision: 5468
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5468&view=rev
Author: jdh2358
Date: 2008-06-11 05:23:05 -0700 (Wed, 11 Jun 2008)
Log Message:
-----------
some more backend bases rest fixes
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backend_bases.py
Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-06-11 01:26:29 UTC (rev 5467)
+++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-06-11 12:23:05 UTC (rev 5468)
@@ -631,8 +631,8 @@
class Event:
"""
A matplotlib event. Attach additional attributes as defined in
- :meth:`FigureCanvasBase.connect`. The following attributes are defined and
- shown with their default values
+ :meth:`FigureCanvasBase.mpl_connect`. The following attributes
+ are defined and shown with their default values
``name``
the event name
@@ -655,7 +655,7 @@
"""
An event triggered by a draw operation on the canvas
- In addition to the :class`Event` attributes, the following event attributes are defined:
+ In addition to the :class:`Event` attributes, the following event attributes are defined:
``renderer``
the :class:`RendererBase` instance for the draw event
@@ -669,7 +669,7 @@
"""
An event triggered by a canvas resize
- In addition to the :class`Event` attributes, the following event attributes are defined:
+ In addition to the :class:`Event` attributes, the following event attributes are defined:
``width``
width of the canvas in pixels
@@ -689,7 +689,7 @@
The following additional attributes are defined and shown with
their default values
- In addition to the :class`Event` attributes, the following event attributes are defined:
+ In addition to the :class:`Event` attributes, the following event attributes are defined:
``x``
x position - pixels from left of canvas
@@ -752,7 +752,7 @@
A mouse event ('button_press_event', 'button_release_event', 'scroll_event',
'motion_notify_event').
- In addition to the :class`Event` and :class:`LocationEvent`
+ In addition to the :class:`Event` and :class:`LocationEvent`
attributes, the following attributes are defined:
``button``
@@ -832,9 +832,9 @@
A key event (key press, key release).
Attach additional attributes as defined in
- :meth:`FigureCanvasBase.connect`.
+ :meth:`FigureCanvasBase.mpl_connect`.
- In addition to the :class`Event` and :class:`LocationEvent`
+ In addition to the :class:`Event` and :class:`LocationEvent`
attributes, the following attributes are defined:
``key``
@@ -1468,38 +1468,40 @@
backends must implement a canvas that handles connections for
'button_press_event' and 'button_release_event'. See
- :meth:`FigureCanvasBase.connect` for more information
+ :meth:`FigureCanvasBase.mpl_connect` for more information
They must also define
- :meth:`save_figure`
- save the current figure
+ :meth:`save_figure`
+ save the current figure
- :meth:`set_cursor`
- if you want the pointer icon to change
+ :meth:`set_cursor`
+ if you want the pointer icon to change
- :meth:`_init_toolbar`
- create your toolbar widget
+ :meth:`_init_toolbar`
+ create your toolbar widget
- :meth:`draw_rubberband` (optional)
- draw the zoom to rect "rubberband" rectangle
+ :meth:`draw_rubberband` (optional)
+ draw the zoom to rect "rubberband" rectangle
- :meth:`press` (optional)
- whenever a mouse button is pressed, you'll be
- notified with the event
+ :meth:`press` (optional)
+ whenever a mouse button is pressed, you'll be
+ notified with the event
:meth:`release` (optional)
- whenever a mouse button is released, you'll be notified with the event
+ whenever a mouse button is released, you'll be notified with
+ the event
- :meth:`dynamic_update` ptional)
- dynamically update the window while navigating
+ :meth:`dynamic_update` (optional)
+ dynamically update the window while navigating
- :meth:`set_message` ptional)
- display message
+ :meth:`set_message` (optional)
+ display message
- :meth:`set_history_buttons` (optional)
- you can change the history back / forward buttons to indicate disabled / enabled state.
+ :meth:`set_history_buttons` (optional)
+ you can change the history back / forward buttons to
+ indicate disabled / enabled state.
That's it, we'll do the rest!
"""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-11 01:26:34
|
Revision: 5467
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5467&view=rev
Author: jdh2358
Date: 2008-06-10 18:26:29 -0700 (Tue, 10 Jun 2008)
Log Message:
-----------
added usetex review
Modified Paths:
--------------
trunk/matplotlib/doc/devel/coding_guide.rst
trunk/matplotlib/doc/devel/documenting_mpl.rst
trunk/matplotlib/doc/devel/outline.rst
trunk/matplotlib/doc/users/usetex.rst
Modified: trunk/matplotlib/doc/devel/coding_guide.rst
===================================================================
--- trunk/matplotlib/doc/devel/coding_guide.rst 2008-06-11 00:29:14 UTC (rev 5466)
+++ trunk/matplotlib/doc/devel/coding_guide.rst 2008-06-11 01:26:29 UTC (rev 5467)
@@ -1,12 +1,12 @@
.. _coding-guide:
************
-Coding Guide
+Coding guide
************
.. _version-control:
-Version Control
+Version control
===============
svn checkouts
@@ -35,18 +35,25 @@
* if your changes are non-trivial, please make an entry in the
:file:`CHANGELOG`
-* if you change the API, please document it in :file:`API_CHANGES`, and
- consider posting to mpl-devel
-* Are your changes python2.4 compatible? We are still trying to
- support 2.4, so avoid features new to 2.5
+
+* if you change the API, please document it in :file:`API_CHANGES`,
+ and consider posting to `mpl-devel
+ <http://lists.sourceforge.net/mailman/listinfo/matplotlib-devel>`_
+
+* Are your changes python2.4 compatible? We still support 2.4, so
+ avoid features new to 2.5
+
* Can you pass :file:`examples/tests/backend_driver.py`? This is our
poor man's unit test.
+
* If you have altered extension code, do you pass
:file:`unit/memleak_hawaii.py`?
+
* if you have added new files or directories, or reorganized existing
ones, are the new files included in the match patterns in
:file:`MANIFEST.in`. This file determines what goes into the source
distribution of the mpl build.
+
* Keep the maintenance branch and trunk in sync where it makes sense.
If there is a bug on both that needs fixing, use `svnmerge.py
<http://www.orcaware.com/svn/wiki/Svnmerge.py>`_ to keep them in
@@ -58,6 +65,7 @@
svnmerge/svnmerge.py
* get a svn copy of the maintenance branch and the trunk (see above)
+
* Michael advises making the change on the branch and committing
it. Make sure you svn upped on the trunk and have no local
modifications, and then from the svn trunk do::
@@ -87,7 +95,7 @@
.. _style-guide:
-Style Guide
+Style guide
===========
Importing and name spaces
@@ -278,7 +286,7 @@
.. _docstrings:
-Documentation and Docstrings
+Documentation and docstrings
============================
matplotlib uses artist introspection of docstrings to support
Modified: trunk/matplotlib/doc/devel/documenting_mpl.rst
===================================================================
--- trunk/matplotlib/doc/devel/documenting_mpl.rst 2008-06-11 00:29:14 UTC (rev 5466)
+++ trunk/matplotlib/doc/devel/documenting_mpl.rst 2008-06-11 01:26:29 UTC (rev 5467)
@@ -1,10 +1,10 @@
.. _documenting-matplotlib:
**********************
-Documenting Matplotlib
+Documenting matplotlib
**********************
-Getting Started
+Getting started
===============
The documentation for matplotlib is generated from ReStructured Text
@@ -33,7 +33,7 @@
The output produced by Sphinx can be configured by editing the `conf.py`
file located in the `doc/`.
-Organization of Matplotlib's Documentation
+Organization of matplotlib's documentation
==========================================
The actual ReStructured Text files are kept in `doc/users`, `doc/devel`,
@@ -96,8 +96,14 @@
Each guide will have its own `figures/` directory for scripts to generate images
to be included in the dcoumentation. It is not necessary to explicitly save
the figure in the script, a figure will be saved with the same name as the
-filename when the documentation is generated.
+filename when the documentation is generated. For example, use::
+ .. literalinclude:: figures/pyplot_simple.py
+
+ .. image:: figures/pyplot_simple.png
+ :scale: 75
+
+
Any figures that rely on optional system configurations should be generated
with a script residing in doc/static_figs. The resulting figures will be saved
to doc/_static, and will be named based on the name of the script, so we can
@@ -105,6 +111,8 @@
the README in doc/static-figs for any additional requirements necessary to
generate a new figure.
+
+
.. _referring-to-mpl-docs:
Referring to mpl documents
@@ -131,6 +139,8 @@
.. literalinclude:: ../mpl_data/matplotlibrc
+
+
.. _internal-section-refs:
Internal section references
@@ -161,6 +171,13 @@
.. _emacs-helpers:
+Section names, etc
+==================
+
+For everything but top level chapters, please use ``Upper lower`` for
+section titles, eg ``Possible hangups`` rather than ``Possible
+Hangups``
+
Emacs helpers
=============
@@ -182,7 +199,7 @@
C-c TAB - rst-toc-insert
Insert table of contents at point
-
+
C-c C-u - rst-toc-update
Update the table of contents at point
Modified: trunk/matplotlib/doc/devel/outline.rst
===================================================================
--- trunk/matplotlib/doc/devel/outline.rst 2008-06-11 00:29:14 UTC (rev 5466)
+++ trunk/matplotlib/doc/devel/outline.rst 2008-06-11 01:26:29 UTC (rev 5467)
@@ -28,7 +28,7 @@
animation John has author ?
collections ? no author ?
text - mathtext Michael in review John
-text - usetex Darren submitted ?
+text - usetex Darren in review John
text - annotations John submitted ?
fonts et al Michael ? no author Darren
pyplot tut John submitted Eric
@@ -177,4 +177,40 @@
sub-packages with the gamut of licenses, GPL to MIT?
+usetex user's guide-- reviewed by JDH
+-------------------------------------
+Review of :ref:`usetex-tutorial`:
+
+#. In the section on the ps distiller, you might mention that it is
+ the rasterization which some users find objectionable, and the
+ distiller pram (eg 6000) is a dpi setting for the rasterizer. Not
+ everyone will immediately grasp the controversy surrounding dumping
+ high res bitmaps into a ps file.
+
+#. ``= Possible Hangups =`` - this is moin, not rest. I have fixed
+ this already, just wanted to point it out. Also, for everything
+ but top level chapters, I refer ``Upper lower`` for section
+ titles, eg ``Possible hangups``.
+
+#. in the troubleshooting section, could you add a FAQ showing how to
+ find their .matplotlib dir (matplotlib.get_data_path) and link to
+ it. Also link to the PATH var and properly format
+ ``text.latex.preample``. For the dirs, do we want `tex.cache` or
+ ``tex.cache``? I've been using the latter. We could use rest
+ specific markup for files and dirs, but I've been resisting goin
+ whle hog onthe markup... But we may eventually decide that is the
+ better choice.
+
+#. try and use internal reference links for every section and be
+ generous with the sections. Eg, I added a section headers and
+ internal linka for the postscript and unicode sections (we will
+ want to be able to refer people to these easily from FAQs and mail
+ list posts, etc)::
+
+ .. _usetex-postscript:
+
+ Postscript options
+ ==================
+
+Looks good!
Modified: trunk/matplotlib/doc/users/usetex.rst
===================================================================
--- trunk/matplotlib/doc/users/usetex.rst 2008-06-11 00:29:14 UTC (rev 5466)
+++ trunk/matplotlib/doc/users/usetex.rst 2008-06-11 01:26:29 UTC (rev 5467)
@@ -52,7 +52,7 @@
Here is the standard example, `tex_demo.py`:
- .. literalinclude:: ../mpl_examples/pylab_examples/tex_demo.py
+.. literalinclude:: ../mpl_examples/pylab_examples/tex_demo.py
.. image:: ../_static/tex_demo.png
@@ -60,13 +60,22 @@
command ``\displaystyle``, as in `tex_demo.py`, will produce the same
results.
+.. _usetex-unicode:
+
+usetex with unicode
+===================
It is also possible to use unicode strings with the LaTeX text manager, here is
an example taken from `tex_unicode_demo.py`:
- .. literalinclude:: ../mpl_examples/pylab_examples/tex_unicode_demo.py
+.. literalinclude:: ../mpl_examples/pylab_examples/tex_unicode_demo.py
.. image:: ../_static/tex_unicode_demo.png
+.. _usetex-postscript:
+
+Postscript options
+==================
+
In order to produce encapsulated postscript files that can be embedded in a new
LaTeX document, the default behavior of matplotlib is to distill the output,
which removes some postscript operators used by LaTeX that are illegal in an
@@ -77,51 +86,60 @@
alternative produces postscript with text that can be edited in Adobe
Illustrator, and searched text in pdf documents.
+.. _usetex-hangups:
-= Possible Hangups =
+Possible hangups
+================
- * On Windows, the PATH environment variable may need to be modified to find
- the latex, dvipng and ghostscript executables. This is done by going to the
- control panel, selecting the "system" icon, selecting the "advanced" tab,
- and clicking the "environment variables" button (and people think Linux is
- complicated. Sheesh.) Select the PATH variable, and add the appropriate
- directories.
+* On Windows, the PATH environment variable may need to be modified to
+ find the latex, dvipng and ghostscript executables. This is done by
+ going to the control panel, selecting the "system" icon, selecting
+ the "advanced" tab, and clicking the "environment variables" button
+ (and people think Linux is complicated. Sheesh.) Select the PATH
+ variable, and add the appropriate directories.
- * Using MiKTeX with Computer Modern fonts, if you get odd -Agg and PNG
- results, go to MiKTeX/Options and update your format files
+* Using MiKTeX with Computer Modern fonts, if you get odd -Agg and PNG
+ results, go to MiKTeX/Options and update your format files
- * The fonts look terrible on screen. You are probably running Mac OS, and
- there is some funny business with dvipng on the mac. Set text.dvipnghack :
- True in your matplotlibrc file.
+* The fonts look terrible on screen. You are probably running Mac OS,
+ and there is some funny business with dvipng on the mac. Set
+ text.dvipnghack : True in your matplotlibrc file.
- * On Ubuntu and Gentoo, the base texlive install does not ship with the
- type1cm package. You may need to install some of the extra packages to get
- all the goodies that come bundled with other latex distributions.
+* On Ubuntu and Gentoo, the base texlive install does not ship with
+ the type1cm package. You may need to install some of the extra
+ packages to get all the goodies that come bundled with other latex
+ distributions.
- * Some progress has been made so Matplotlib uses the dvi files directly for
- text layout. This allows latex to be used for text layout with the pdf and
- svg backends, as well as the \*Agg and PS backends. In the future, a latex
- installation may be the only external dependency.
+* Some progress has been made so Matplotlib uses the dvi files
+ directly for text layout. This allows latex to be used for text
+ layout with the pdf and svg backends, as well as the \*Agg and PS
+ backends. In the future, a latex installation may be the only
+ external dependency.
-= In the event that things dont work =
- * Try deleting `tex.cache` from your `~/.matplotlib` directory
+.. _usetex-troubleshooting:
- * Make sure LaTeX, dvipng and ghostscript are each working and on your PATH.
+Trouble shooting
+================
- * Make sure what you are trying to do is possible in a LaTeX document, that
- your LaTeX syntax is valid and that you are using raw strings if necessary
- to avoid unintended escape sequences.
+* Try deleting `tex.cache` from your `~/.matplotlib` directory
- * Most problems reported on the mailing list have been cleared up by
- upgrading Ghostscript_. If possible, please try upgrading to the latest
- release before reporting problems to the list.
+* Make sure LaTeX, dvipng and ghostscript are each working and on your PATH.
- * The text.latex.preample rc setting is not officially supported. This option
- provides lots of flexibility, and lots of ways to cause problems. Please
- disable this option before reporting problems to the mailing list.
+* Make sure what you are trying to do is possible in a LaTeX document,
+ that your LaTeX syntax is valid and that you are using raw strings
+ if necessary to avoid unintended escape sequences.
- * If you still need help, please see :ref:`reporting-problems`
+* Most problems reported on the mailing list have been cleared up by
+ upgrading Ghostscript_. If possible, please try upgrading to the
+ latest release before reporting problems to the list.
+* The text.latex.preample rc setting is not officially supported. This
+ option provides lots of flexibility, and lots of ways to cause
+ problems. Please disable this option before reporting problems to
+ the mailing list.
+
+* If you still need help, please see :ref:`reporting-problems`
+
.. _LaTeX: http://www.tug.org
.. _dvipng: http://sourceforge.net/projects/dvipng
.. _Ghostscript: http://www.cs.wisc.edu/~ghost/
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-11 00:29:18
|
Revision: 5466
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5466&view=rev
Author: jdh2358
Date: 2008-06-10 17:29:14 -0700 (Tue, 10 Jun 2008)
Log Message:
-----------
remove typo from backend template
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backends/backend_template.py
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_template.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_template.py 2008-06-10 22:49:02 UTC (rev 5465)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_template.py 2008-06-11 00:29:14 UTC (rev 5466)
@@ -1,4 +1,4 @@
-M"""
+"""
This is a fully functional do nothing backend to provide a template to
backend writers. It is fully functional in that you can select it as
a backend with
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-10 22:49:05
|
Revision: 5465
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5465&view=rev
Author: jdh2358
Date: 2008-06-10 15:49:02 -0700 (Tue, 10 Jun 2008)
Log Message:
-----------
some tweaks to image size and backend docs
Modified Paths:
--------------
trunk/matplotlib/doc/devel/outline.rst
trunk/matplotlib/doc/users/annotations.rst
trunk/matplotlib/doc/users/event_handling.rst
trunk/matplotlib/doc/users/figures/make.py
trunk/matplotlib/doc/users/figures/pyplot_simple.py
trunk/matplotlib/doc/users/mathtext.rst
trunk/matplotlib/doc/users/pyplot_tutorial.rst
trunk/matplotlib/doc/users/text_intro.rst
trunk/matplotlib/doc/users/text_props.rst
trunk/matplotlib/lib/matplotlib/backend_bases.py
trunk/matplotlib/lib/matplotlib/backends/backend_template.py
Modified: trunk/matplotlib/doc/devel/outline.rst
===================================================================
--- trunk/matplotlib/doc/devel/outline.rst 2008-06-10 18:36:33 UTC (rev 5464)
+++ trunk/matplotlib/doc/devel/outline.rst 2008-06-10 22:49:02 UTC (rev 5465)
@@ -103,20 +103,20 @@
submission, you can put them here. As the author cleans them up or
addresses them, they should be removed.
-mathtext user's guide-- reviewd by JDH
---------------------------------------
+mathtext user's guide-- reviewed by JDH
+---------------------------------------
This looks good (see :ref:`mathtext-tutorial`) -- there are a few
-minor things to close the book on this chapter.
+minor things to close the book on this chapter:
#. The main thing to wrap this up is getting the mathtext module
-ported over to rest and included in the API so the links from the
-user's guide tutorial work.
+ ported over to rest and included in the API so the links from the
+ user's guide tutorial work.
#. This section might also benefit from a little more detail on the
-customizations that are possible (eg an example fleshing out the rc
-options a little bit). Admittedly, this is pretty clear from readin
-ghte rc file, but it might be helpful to a newbie.
+ customizations that are possible (eg an example fleshing out the rc
+ options a little bit). Admittedly, this is pretty clear from
+ readin ghte rc file, but it might be helpful to a newbie.
#. There is still a TODO in the file to include a complete list of symbols
Modified: trunk/matplotlib/doc/users/annotations.rst
===================================================================
--- trunk/matplotlib/doc/users/annotations.rst 2008-06-10 18:36:33 UTC (rev 5464)
+++ trunk/matplotlib/doc/users/annotations.rst 2008-06-10 22:49:02 UTC (rev 5465)
@@ -15,7 +15,7 @@
.. literalinclude:: figures/annotation_basic.py
.. image:: figures/annotation_basic.png
- :scale: 50
+ :scale: 75
In this example, both the ``xy`` (arrow tip) and ``xytext`` locations
(text location) are in data coordinates. There are a variety of other
@@ -76,7 +76,7 @@
.. literalinclude:: figures/annotation_polar.py
.. image:: figures/annotation_polar.png
- :scale: 50
+ :scale: 75
See the `annotations demo
<http://matplotlib.sf.net/examples/pylab_examples/annotation_demo.py>`_ for more
Modified: trunk/matplotlib/doc/users/event_handling.rst
===================================================================
--- trunk/matplotlib/doc/users/event_handling.rst 2008-06-10 18:36:33 UTC (rev 5464)
+++ trunk/matplotlib/doc/users/event_handling.rst 2008-06-10 22:49:02 UTC (rev 5465)
@@ -70,16 +70,18 @@
================
All matplotlib events inherit from the base class
-:class:`matplotlib.backend_bases.Event`, which store the attributes
+:class:`matplotlib.backend_bases.Event`, which store the attributes:
-=============== =================================================
-Event attribute Description
-=============== =================================================
-``name`` the event name
-``canvas`` the FigureCanvas instance generating the event
-``guiEvent`` the GUI event that triggered the matplotlib event
-=============== =================================================
+ ``name``
+ the event name
+ ``canvas``
+ the FigureCanvas instance generating the event
+
+ ``guiEvent``
+ the GUI event that triggered the matplotlib event
+
+
The most common events that are the bread and butter of event handling
are key press/release events and mouse press/release and movement
events. The :class:`~matplotlib.backend_bases.KeyEvent` and
@@ -87,17 +89,21 @@
these events are both derived from the LocationEvent, which has the
following attributes
-======================= ========================================
-LocationEvent attribute Description
-======================= ========================================
-``x`` x position - pixels from left of canvas
-``y`` y position - pixels from right of canvas
-``button`` button pressed None, 1, 2, 3
-``inaxes`` the Axes instance if mouse us over axes
-``xdata`` x coord of mouse in data coords
-``ydata`` y coord of mouse in data coords
-======================= ========================================
+ ``x``
+ x position - pixels from left of canvas
+ ``y``
+ y position - pixels from bottom of canvas
+
+ ``inaxes``
+ the :class:`~matplotlib.axes.Axes` instance if mouse is over axes
+
+ ``xdata``
+ x coord of mouse in data coords
+
+ ``ydata``
+ y coord of mouse in data coords
+
Let's look a simple example of a canvas, where a simple line segment
is created every time a mouse is pressed::
@@ -129,13 +135,12 @@
the data and pixel coordinates in event.x and event.xdata. In
addition to the ``LocationEvent`` attributes, it has
-==================== ==============================================================
-MouseEvent attribute Description
-==================== ==============================================================
-``button`` button pressed None, 1, 2, 3
-``key`` the key pressed: None, chr(range(255)), shift, win, or control
-==================== ==============================================================
+ ``button``
+ button pressed None, 1, 2, 3, 'up', 'down' (up and down are used for scroll events)
+ ``key``
+ the key pressed: None, chr(range(255), 'shift', 'win', or 'control'
+
Draggable Rectangle Exercise
----------------------------
@@ -281,7 +286,6 @@
self.rect.set_x(x0+dx)
self.rect.set_y(y0+dy)
-
canvas = self.rect.figure.canvas
axes = self.rect.axes
# restore the background region
@@ -293,8 +297,6 @@
# blit just the redrawn area
canvas.blit(axes.bbox)
-
-
def on_release(self, event):
'on release we reset the press data'
if DraggableRectangle.lock is not self:
@@ -309,6 +311,7 @@
# redraw the full figure
self.rect.figure.canvas.draw()
+
def disconnect(self):
'disconnect all the stored connection ids'
self.rect.figure.canvas.mpl_disconnect(self.cidpress)
@@ -340,24 +343,29 @@
There are a variety of meanings of the ``picker`` property:
-- ``None`` : picking is disabled for this artist (default)
+ ``None``
+ picking is disabled for this artist (default)
-- ``boolean`` : if True then picking will be enabled and the artist will
- fire a pick event if the mouse event is over the artist
+ ``boolean``
+ if True then picking will be enabled and the artist will fire a
+ pick event if the mouse event is over the artist
-- ``float`` : if picker is a number it is interpreted as an epsilon
- tolerance in points and the the artist will fire off an event if its
- data is within epsilon of the mouse event. For some artists like
- lines and patch collections, the artist may provide additional data
- to the pick event that is generated, eg the indices of the data
- within epsilon of the pick event.
+ ``float``
+ if picker is a number it is interpreted as an epsilon tolerance in
+ points and the the artist will fire off an event if its data is
+ within epsilon of the mouse event. For some artists like lines
+ and patch collections, the artist may provide additional data to
+ the pick event that is generated, eg the indices of the data
+ within epsilon of the pick event.
-- ``function`` : if picker is callable, it is a user supplied function
- which determines whether the artist is hit by the mouse event. The
- signature is ``hit, props = picker(artist, mouseevent)`` to
- determine the hit test. If the mouse event is over the artist,
- return ``hit=True`` and props is a dictionary of properties you want
- added to the :class:`~matplotlib.backend_bases.PickEvent` attributes
+ ``function``
+ if picker is callable, it is a user supplied function which
+ determines whether the artist is hit by the mouse event. The
+ signature is ``hit, props = picker(artist, mouseevent)`` to
+ determine the hit test. If the mouse event is over the artist,
+ return ``hit=True`` and props is a dictionary of properties you
+ want added to the :class:`~matplotlib.backend_bases.PickEvent`
+ attributes
After you have enabled an artist for picking by setting the ``picker``
@@ -373,16 +381,18 @@
The :class:`~matplotlib.backend_bases.PickEvent` which is passed to
your callback is always fired with two attributes:
-- ``mouseevent`` : the mouse event that generate the pick event. The
- mouse event in turn has attributes like ``x`` and ``y`` (the coords in
- display space, eg pixels from left, bottom) and xdata, ydata (the
- coords in data space). Additionally, you can get information about
- which buttons were pressed, which keys were pressed, which Axes the
- mouse is over, etc. See :class:`matplotlib.backend_bases.MouseEvent` for
- details.
+ ``mouseevent`` the mouse event that generate the pick event. The
+ mouse event in turn has attributes like ``x`` and ``y`` (the
+ coords in display space, eg pixels from left, bottom) and xdata,
+ ydata (the coords in data space). Additionally, you can get
+ information about which buttons were pressed, which keys were
+ pressed, which :class:`~matplotlib.axes.Axes` the mouse is over,
+ etc. See :class:`matplotlib.backend_bases.MouseEvent` for
+ details.
-- ``artist`` : the :class:`matplotlib.artist.Artist` that generated
- the pick event.
+ ``artist``
+ the :class:`~matplotlib.artist.Artist` that generated the pick
+ event.
Additionally, certain artists like :class:`~matplotlib.lines.Line2D`
and :class:`~matplotlib.collections.PatchCollection` may attach
Modified: trunk/matplotlib/doc/users/figures/make.py
===================================================================
--- trunk/matplotlib/doc/users/figures/make.py 2008-06-10 18:36:33 UTC (rev 5464)
+++ trunk/matplotlib/doc/users/figures/make.py 2008-06-10 22:49:02 UTC (rev 5465)
@@ -2,7 +2,7 @@
import sys, os, glob
import matplotlib
import IPython.Shell
-matplotlib.rcdefaults()
+#matplotlib.rcdefaults()
matplotlib.use('Agg')
mplshell = IPython.Shell.MatplotlibShell('mpl')
Modified: trunk/matplotlib/doc/users/figures/pyplot_simple.py
===================================================================
--- trunk/matplotlib/doc/users/figures/pyplot_simple.py 2008-06-10 18:36:33 UTC (rev 5464)
+++ trunk/matplotlib/doc/users/figures/pyplot_simple.py 2008-06-10 22:49:02 UTC (rev 5465)
@@ -1,4 +1,4 @@
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.ylabel('some numbers')
-
+plt.show()
Modified: trunk/matplotlib/doc/users/mathtext.rst
===================================================================
--- trunk/matplotlib/doc/users/mathtext.rst 2008-06-10 18:36:33 UTC (rev 5464)
+++ trunk/matplotlib/doc/users/mathtext.rst 2008-06-10 22:49:02 UTC (rev 5465)
@@ -233,7 +233,7 @@
.. literalinclude:: figures/pyplot_mathtext.py
.. image:: figures/pyplot_mathtext.png
- :scale: 50
+ :scale: 75
Modified: trunk/matplotlib/doc/users/pyplot_tutorial.rst
===================================================================
--- trunk/matplotlib/doc/users/pyplot_tutorial.rst 2008-06-10 18:36:33 UTC (rev 5464)
+++ trunk/matplotlib/doc/users/pyplot_tutorial.rst 2008-06-10 22:49:02 UTC (rev 5465)
@@ -4,18 +4,18 @@
pyplot tutorial
***************
-:mod:`matplotlib.pyplot` is a collection of functions that make
-matplotlib work like matlab. Each ``pyplot`` function makes some
-change to a figure: eg, create a figure, create a plotting area in a
-figure, plot some lines in a plotting area, decorate the plot with
-labels, etc.... :mod:`matplotlib.pyplot` is stateful, in that it
+:mod:`matplotlib.pyplot` is a collection of command style functions
+that make matplotlib work like matlab. Each ``pyplot`` function makes
+some change to a figure: eg, create a figure, create a plotting area
+in a figure, plot some lines in a plotting area, decorate the plot
+with labels, etc.... :mod:`matplotlib.pyplot` is stateful, in that it
keeps track of the current figure and plotting area, and the plotting
functions are directed to the current axes
.. literalinclude:: figures/pyplot_simple.py
.. image:: figures/pyplot_simple.png
- :scale: 50
+ :scale: 75
You may be wondering why the x-axis ranges from 0-3 and the y-axis
@@ -42,7 +42,7 @@
.. literalinclude:: figures/pyplot_formatstr.py
.. image:: figures/pyplot_formatstr.png
- :scale: 50
+ :scale: 75
See the :func:`~matplotlib.pyplot.plot` documentation for a complete
list of line styles and format strings. The
@@ -60,10 +60,8 @@
.. literalinclude:: figures/pyplot_three.py
.. image:: figures/pyplot_three.png
- :scale: 50
+ :scale: 75
-
-
.. _controlling-line-properties:
Controlling line properties
@@ -169,7 +167,7 @@
.. literalinclude:: figures/pyplot_two_subplots.py
.. image:: figures/pyplot_two_subplots.png
- :scale: 50
+ :scale: 75
The :func:`~matplotlib.pyplot.figure` command here is optional because
``figure(1)`` will be created by default, just as a ``subplot(111)``
@@ -230,7 +228,7 @@
.. literalinclude:: figures/pyplot_text.py
.. image:: figures/pyplot_text.png
- :scale: 50
+ :scale: 75
All of the :func:`~matplotlib.pyplot.text` commands return an
@@ -278,7 +276,7 @@
.. literalinclude:: figures/pyplot_annotate.py
.. image:: figures/pyplot_annotate.png
- :scale: 50
+ :scale: 75
In this basic example, both the ``xy`` (arrow tip) and ``xytext``
locations (text location) are in data coordinates. There are a
Modified: trunk/matplotlib/doc/users/text_intro.rst
===================================================================
--- trunk/matplotlib/doc/users/text_intro.rst 2008-06-10 18:36:33 UTC (rev 5464)
+++ trunk/matplotlib/doc/users/text_intro.rst 2008-06-10 22:49:02 UTC (rev 5465)
@@ -58,5 +58,5 @@
.. literalinclude:: figures/text_commands.py
.. image:: figures/text_commands.png
- :scale: 50
+ :scale: 75
Modified: trunk/matplotlib/doc/users/text_props.rst
===================================================================
--- trunk/matplotlib/doc/users/text_props.rst 2008-06-10 18:36:33 UTC (rev 5464)
+++ trunk/matplotlib/doc/users/text_props.rst 2008-06-10 22:49:02 UTC (rev 5465)
@@ -60,4 +60,4 @@
.. literalinclude:: figures/text_layout.py
.. image:: figures/text_layout.png
- :scale: 50
+ :scale: 75
Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-06-10 18:36:33 UTC (rev 5464)
+++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-06-10 22:49:02 UTC (rev 5465)
@@ -640,6 +640,10 @@
``canvas``
the FigureCanvas instance generating the event
+ ``guiEvent``
+ the GUI event that triggered the matplotlib event
+
+
"""
def __init__(self, name, canvas,guiEvent=None):
self.name = name
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_template.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_template.py 2008-06-10 18:36:33 UTC (rev 5464)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_template.py 2008-06-10 22:49:02 UTC (rev 5465)
@@ -1,4 +1,4 @@
-"""
+M"""
This is a fully functional do nothing backend to provide a template to
backend writers. It is fully functional in that you can select it as
a backend with
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-10 18:38:10
|
Revision: 5464
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5464&view=rev
Author: jdh2358
Date: 2008-06-10 11:36:33 -0700 (Tue, 10 Jun 2008)
Log Message:
-----------
added backend bases api
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backend_bases.py
Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-06-10 18:08:50 UTC (rev 5463)
+++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-06-10 18:36:33 UTC (rev 5464)
@@ -19,6 +19,7 @@
:class:`MouseEvent` store the meta data like keys and buttons
pressed, x and y locations in pixel and
:class:`~matplotlib.axes.Axes` coordinates.
+
"""
from __future__ import division
@@ -38,17 +39,17 @@
The following methods *must* be implemented in the backend:
- * draw_path
- * draw_image
- * draw_text
- * get_text_width_height_descent
+ * :meth:`draw_path`
+ * :meth:`draw_image`
+ * :meth:`draw_text`
+ * :meth:`get_text_width_height_descent`
The following methods *should* be implemented in the backend for
optimization reasons:
- * draw_markers
- * draw_path_collection
- * draw_quad_mesh
+ * :meth:`draw_markers`
+ * :meth:`draw_path_collection`
+ * :meth:`draw_quad_mesh`
"""
def __init__(self):
self._texmanager = None
@@ -81,9 +82,15 @@
that behavior, those vertices should be removed before calling
this function.
- ``marker_trans`` is an affine transform applied to the marker.
- ``trans`` is an affine transform applied to the path.
+ ``gc``
+ the :class:`GraphicsContextBase` instance
+ ``marker_trans``
+ is an affine transform applied to the marker.
+
+ ``trans``
+ is an affine transform applied to the path.
+
This provides a fallback implementation of draw_markers that
makes multiple calls to
:meth:`draw_path`. Some
@@ -271,14 +278,23 @@
def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None):
"""
- Draw the :class:`~matplotlib.image.Image` instance into the
- current axes; ``x`` is the distance in pixels from the left
- hand side of the canvas. ``y`` is the distance from the
- origin. That is, if origin is upper, y is the distance from
- top. If origin is lower, y is the distance from bottom
+ Draw the image instance into the current axes;
- bbox is a :class:`~matplotlib.transforms.Bbox` instance for clipping, or
- None
+ ``x``
+ is the distance in pixels from the left hand side of the canvas.
+
+ ``y``
+ the distance from the origin. That is, if origin is
+ upper, y is the distance from top. If origin is lower, y
+ is the distance from bottom
+
+ ``im``
+ the :class:`matplotlib._image.Image` instance
+
+ ``bbox``
+ a :class:`matplotlib.transforms.Bbox` instance for clipping, or
+ None
+
"""
raise NotImplementedError
@@ -294,18 +310,33 @@
def draw_text(self, gc, x, y, s, prop, angle, ismath=False):
"""
- Draw the :class:`~matplotlib.text.Text` instance s at ``x``,
- ``y`` (display coords) with
- :class:`~matplotlib.font_manager.FontProperties` instance
- ``prop`` at ``angle`` in degrees, using :class:`GraphicsContextBase` gc
+ Draw the text instance
+ ``gc``
+ the :class:`GraphicsContextBase` instance
+
+ ``x``
+ the x location of the text in display coords
+
+ ``y``
+ the y location of the text in display coords
+
+ ``s``
+ a :class:`matplotlib.text.Text` instance
+
+ ``prop``
+ a :class:`matplotlib.font_manager.FontProperties` instance
+
+ ``angle``
+ the rotation angle in degrees
+
**backend implementers note**
When you are trying to determine if you have gotten your bounding box
right (which is what enables the text layout/alignment to work
- properly), it helps to change the line in text.py
+ properly), it helps to change the line in text.py::
- if 0: bbox_artist(self, renderer)
+ if 0: bbox_artist(self, renderer)
to if 1, and then the actual bounding box will be blotted along with
your text.
@@ -326,7 +357,7 @@
def get_texmanager(self):
"""
- return the :class:matplotlib.texmanager.TexManager` instance
+ return the :class:`matplotlib.texmanager.TexManager` instance
"""
if self._texmanager is None:
from matplotlib.texmanager import TexManager
@@ -350,12 +381,15 @@
def points_to_pixels(self, points):
"""
Convert points to display units
- points - a float or a numpy array of float
+
+ ``points``
+ a float or a numpy array of float
+
return points converted to pixels
- You need to override this function (unless your backend doesn't have a
- dpi, eg, postscript or svg).
- Some imaging systems assume some value for pixels per inch""
+ You need to override this function (unless your backend
+ doesn't have a dpi, eg, postscript or svg). Some imaging
+ systems assume some value for pixels per inch::
points to pixels = points * pixels_per_inch/72.0 * dpi/72.0
"""
@@ -530,6 +564,7 @@
``dash_list``
specifies the on-off sequence as points. ``(None, None)`` specifies a solid line
+
"""
self._dashes = dash_offset, dash_list
@@ -620,6 +655,7 @@
``renderer``
the :class:`RendererBase` instance for the draw event
+
"""
def __init__(self, name, canvas, renderer):
Event.__init__(self, name, canvas)
@@ -636,6 +672,7 @@
``height``
height of the canvas in pixels
+
"""
def __init__(self, name, canvas):
Event.__init__(self, name, canvas)
@@ -716,9 +753,18 @@
``button``
button pressed None, 1, 2, 3, 'up', 'down' (up and down are used for scroll events)
+
``key``
- the key pressed: None, chr(range(255), shift, win, or control
+ the key pressed: None, chr(range(255), 'shift', 'win', or 'control'
+
+ Example usage::
+
+ def on_press(event):
+ print 'you pressed', event.button, event.xdata, event.ydata
+
+ cid = fig.canvas.mpl_connect('button_press_event', on_press)
+
"""
x = None # x position - pixels from left of canvas
y = None # y position - pixels from right of canvas
@@ -750,10 +796,25 @@
``artist``
the :class:`~matplotlib.artist.Artist` picked
- extra class dependent attrs -- eg a
- :class:`~matplotlib.lines.Line2D` pick may define different extra
- attributes than a :class:`~matplotlib.collections.PatchCollection`
- pick event
+ other
+ extra class dependent attrs -- eg a
+ :class:`~matplotlib.lines.Line2D` pick may define different
+ extra attributes than a
+ :class:`~matplotlib.collections.PatchCollection` pick event
+
+
+ Example usage::
+
+ line, = ax.plot(rand(100), 'o', picker=5) # 5 points tolerance
+
+ def on_pick(event):
+ thisline = event.artist
+ xdata, ydata = thisline.get_data()
+ ind = event.ind
+ print 'on pick line:', zip(xdata[ind], ydata[ind])
+
+ cid = fig.canvas.mpl_connect('pick_event', on_pick)
+
"""
def __init__(self, name, canvas, mouseevent, artist, guiEvent=None, **kwargs):
Event.__init__(self, name, canvas, guiEvent)
@@ -776,7 +837,16 @@
the key pressed: None, chr(range(255), shift, win, or control
This interface may change slightly when better support for
- modifier keys is included
+ modifier keys is included.
+
+
+ Example usage::
+
+ def on_key(event):
+ print 'you pressed', event.key, event.xdata, event.ydata
+
+ cid = fig.canvas.mpl_connect('key_press_event', on_key)
+
"""
def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None):
LocationEvent.__init__(self, name, canvas, x, y, guiEvent=guiEvent)
@@ -1001,9 +1071,18 @@
def button_release_event(self, x, y, button, guiEvent=None):
"""
Backend derived classes should call this function on any mouse
- button release. x,y are the canvas coords: 0,0 is lower, left.
- button and key are as defined in :class:`MouseEvent`
+ button release.
+ ``x``
+ the canvas coordinates where 0=left
+
+ ``y``
+ the canvas coordinates where 0=bottom
+
+ ``guiEvent``
+ the native UI event that generated the mpl event
+
+
This method will be call all functions connected to the
'button_release_event' with a :class:`MouseEvent` instance.
@@ -1016,9 +1095,18 @@
def motion_notify_event(self, x, y, guiEvent=None):
"""
Backend derived classes should call this function on any
- motion-notify-event. x,y are the canvas coords: 0,0 is lower, left.
- button and key are as defined in MouseEvent
+ motion-notify-event.
+ ``x``
+ the canvas coordinates where 0=left
+
+ ``y``
+ the canvas coordinates where 0=bottom
+
+ ``guiEvent``
+ the native UI event that generated the mpl event
+
+
This method will be call all functions connected to the
'motion_notify_event' with a :class:`MouseEvent` instance.
@@ -1241,14 +1329,23 @@
- 'resize_event'
- 'scroll_event'
- For the three events above, if the mouse is over the axes,
- the variable event.inaxes will be set to the axes it is over,
- and additionally, the variables event.xdata and event.ydata
- will be defined. This is the mouse location in data coords.
- See :class`MplEvent`
+ For the location events (button and key press/release), if the
+ mouse is over the axes, the variable event.inaxes will be set
+ to the :class:`~matplotlib.axes.Axes` the event occurs is
+ over, and additionally, the variables ``event.xdata`` and
+ ``event.ydata`` will be defined. This is the mouse location in
+ data coords. See :class:`KeyEvent` and:class:`MouseEvent` for more info.
return value is a connection id that can be used with
- :meth:`mpl_disconnect`
+ :meth:`mpl_disconnect`.
+
+ Example usage::
+
+ def on_press(event):
+ print 'you pressed', event.button, event.xdata, event.ydata
+
+ cid = canvas.mpl_connect('button_press_event', on_press)
+
"""
return self.callbacks.connect(s, func)
@@ -1256,11 +1353,18 @@
def mpl_disconnect(self, cid):
"""
disconnect callback id cid
+
+ Example usage::
+
+ cid = canvas.mpl_connect('button_press_event', on_press)
+ #...later
+ canvas.mpl_disconnect(cid)
"""
return self.callbacks.disconnect(cid)
def flush_events(self):
- """ Flush the GUI events for the figure. Implemented only for
+ """
+ Flush the GUI events for the figure. Implemented only for
backends with GUIs.
"""
raise NotImplementedError
@@ -1365,28 +1469,33 @@
They must also define
- * save_figure - save the current figure
+ :meth:`save_figure`
+ save the current figure
- * set_cursor - if you want the pointer icon to change
+ :meth:`set_cursor`
+ if you want the pointer icon to change
- * _init_toolbar - create your toolbar widget
+ :meth:`_init_toolbar`
+ create your toolbar widget
- * draw_rubberband (optional) : draw the zoom to rect
- "rubberband" rectangle
+ :meth:`draw_rubberband` (optional)
+ draw the zoom to rect "rubberband" rectangle
- * press : (optional) whenever a mouse button is pressed, you'll be
- notified with the event
+ :meth:`press` (optional)
+ whenever a mouse button is pressed, you'll be
+ notified with the event
- * release : (optional) whenever a mouse button is released,
- you'll be notified with the event
+ :meth:`release` (optional)
+ whenever a mouse button is released, you'll be notified with the event
- * dynamic_update (optional) dynamically update the window while
- navigating
+ :meth:`dynamic_update` ptional)
+ dynamically update the window while navigating
- * set_message (optional) - display message
+ :meth:`set_message` ptional)
+ display message
- * set_history_buttons (optional) - you can change the history
- back / forward buttons to indicate disabled / enabled state.
+ :meth:`set_history_buttons` (optional)
+ you can change the history back / forward buttons to indicate disabled / enabled state.
That's it, we'll do the rest!
"""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-10 18:10:15
|
Revision: 5463
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5463&view=rev
Author: jdh2358
Date: 2008-06-10 11:08:50 -0700 (Tue, 10 Jun 2008)
Log Message:
-----------
added backend bases api
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/doc/api/index.rst
trunk/matplotlib/doc/users/event_handling.rst
trunk/matplotlib/doc/users/figures/text_commands.py
trunk/matplotlib/lib/matplotlib/backend_bases.py
trunk/matplotlib/lib/matplotlib/text.py
Added Paths:
-----------
trunk/matplotlib/doc/api/backend_api.rst
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-06-10 15:53:19 UTC (rev 5462)
+++ trunk/matplotlib/CHANGELOG 2008-06-10 18:08:50 UTC (rev 5463)
@@ -1,6 +1,8 @@
-2008-06-10 Bar now applies the label only to the frist patch, and
- sets _nolegend_ for the other patch labels. This let's
- autolegend work as expected for hist and bar
+2008-06-10 Bar now applies the label only to the first patch only, and
+ sets '_nolegend_' for the other patch labels. This lets
+ autolegend work as expected for hist and bar - see
+ https://sourceforge.net/tracker/index.php?func=detail&aid=1986597&group_id=80706&atid=560720
+ JDH
2008-06-10 Fix text baseline alignment bug. [ 1985420 ] Repair of
baseline alignment in Text._get_layout. Thanks Stan West -
Added: trunk/matplotlib/doc/api/backend_api.rst
===================================================================
--- trunk/matplotlib/doc/api/backend_api.rst (rev 0)
+++ trunk/matplotlib/doc/api/backend_api.rst 2008-06-10 18:08:50 UTC (rev 5463)
@@ -0,0 +1,11 @@
+*******************
+matplotlib backends
+*******************
+
+
+:mod:`matplotlib.backend_bases`
+================================
+
+.. automodule:: matplotlib.backend_bases
+ :members:
+ :undoc-members:
Modified: trunk/matplotlib/doc/api/index.rst
===================================================================
--- trunk/matplotlib/doc/api/index.rst 2008-06-10 15:53:19 UTC (rev 5462)
+++ trunk/matplotlib/doc/api/index.rst 2008-06-10 18:08:50 UTC (rev 5463)
@@ -7,11 +7,9 @@
:Release: |version|
:Date: |today|
-Introduction to developer's guide here **TODO**.
-
.. toctree::
artist_api.rst
axes_api.rst
pyplot_api.rst
-
+ backend_api.rst
Modified: trunk/matplotlib/doc/users/event_handling.rst
===================================================================
--- trunk/matplotlib/doc/users/event_handling.rst 2008-06-10 15:53:19 UTC (rev 5462)
+++ trunk/matplotlib/doc/users/event_handling.rst 2008-06-10 18:08:50 UTC (rev 5463)
@@ -13,9 +13,10 @@
handling API is GUI neutral, it is based on the GTK model, which was
the first user interface matplotlib supported. The events that are
triggered are also a bit richer vis-a-vis matplotlib than standard GUI
-events, including information like which Axes the event occurred in.
-The events also understand the matplotlib coordinate system, and
-report event locations in both pixel and data coordinates.
+events, including information like which :class:`matplotlib.axes.Axes`
+the event occurred in. The events also understand the matplotlib
+coordinate system, and report event locations in both pixel and data
+coordinates.
.. _event-connections:
@@ -24,8 +25,9 @@
To receive events, you need to write a callback function and then
connect your function to the event manager, which is part of the
-FigureCanvas. Here is a simple example that prints the location of
-the mouse click and which button was pressed::
+:class:`~matplotlib.backend_bases.FigureCanvasBase`. Here is a simple
+example that prints the location of the mouse click and which button
+was pressed::
fig = plt.figure()
ax = fig.add_subplot(111)
@@ -37,9 +39,10 @@
cid = fig.canvas.mpl_connect('button_press_event', onclick)
-The FigureCanvas method mpl_connect returns a connection id which is
-simply an integer. When you want to disconnect the callback, just
-call::
+The ``FigureCanvas`` method
+:meth:`~matplotlib.backend_bases.FigureCanvasBase.mpl_connect` returns
+a connection id which is simply an integer. When you want to
+disconnect the callback, just call::
fig.canvas.mpl_disconnect(cid)
@@ -47,19 +50,19 @@
are sent back to you when the event occurs, and the event descriptions
-===================== =========== ===================================
-Event name Class Description
-===================== =========== ===================================
-button_press_event MouseEvent mouse button is pressed
-button_release_event MouseEvent mouse button is released
-draw_event DrawEvent canvas draw
-key_press_event KeyEvent key is pressed
-key_release_event KeyEvent key is released
-motion_notify_event MouseEvent mouse motion
-pick_event PickEvent an object in the canvas is selected
-resize_event ResizeEvent figure canvas is resized
-scroll_event MouseEvent mouse scroll wheel is rolled
-===================== =========== ===================================
+======================= ======================================================================================
+Event name Class and description
+======================= ======================================================================================
+'button_press_event' :class:`~matplotlib.backend_bases.MouseEvent` - mouse button is pressed
+'button_release_event' :class:`~matplotlib.backend_bases.MouseEvent` - mouse button is released
+'draw_event' :class:`~matplotlib.backend_bases.DrawEvent` - canvas draw
+'key_press_event' :class:`~matplotlib.backend_bases.KeyEvent` - key is pressed
+'key_release_event' :class:`~matplotlib.backend_bases.KeyEvent` - key is released
+'motion_notify_event' :class:`~matplotlib.backend_bases.MouseEvent` - mouse motion
+'pick_event' :class:`~matplotlib.backend_bases.PickEvent` - an object in the canvas is selected
+'resize_event' :class:`~matplotlib.backend_bases.ResizeEvent` - figure canvas is resized
+'scroll_event' :class:`~matplotlib.backend_bases.MouseEvent` - mouse scroll wheel is rolled
+======================= ======================================================================================
.. _event-attributes:
@@ -67,31 +70,32 @@
================
All matplotlib events inherit from the base class
-matplotlib.backend_bases.Event, which store the attributes
+:class:`matplotlib.backend_bases.Event`, which store the attributes
=============== =================================================
Event attribute Description
=============== =================================================
-name the event name
-canvas the FigureCanvas instance generating the event
-guiEvent the GUI event that triggered the matplotlib event
+``name`` the event name
+``canvas`` the FigureCanvas instance generating the event
+``guiEvent`` the GUI event that triggered the matplotlib event
=============== =================================================
The most common events that are the bread and butter of event handling
are key press/release events and mouse press/release and movement
-events. The KeyEvent and MouseEvent classes that handle these events
-are both derived from the LocationEvent, which has the following
-attributes
+events. The :class:`~matplotlib.backend_bases.KeyEvent` and
+:class:`~matplotlib.backend_bases.MouseEvent` classes that handle
+these events are both derived from the LocationEvent, which has the
+following attributes
======================= ========================================
LocationEvent attribute Description
======================= ========================================
-x x position - pixels from left of canvas
-y y position - pixels from right of canvas
-button button pressed None, 1, 2, 3
-inaxes the Axes instance if mouse us over axes
-xdata x coord of mouse in data coords
-ydata y coord of mouse in data coords
+``x`` x position - pixels from left of canvas
+``y`` y position - pixels from right of canvas
+``button`` button pressed None, 1, 2, 3
+``inaxes`` the Axes instance if mouse us over axes
+``xdata`` x coord of mouse in data coords
+``ydata`` y coord of mouse in data coords
======================= ========================================
Let's look a simple example of a canvas, where a simple line segment
@@ -120,31 +124,33 @@
-The MouseEvent that we just used is a LocationEvent, so we have access
-to the data and pixel coordinates in event.x and event.xdata. In
-addition to the LocationEvent attributes, it has
+The :class:`~matplotlib.backend_bases.MouseEvent` that we just used is a
+:class:`~matplotlib.backend_bases.LocationEvent`, so we have access to
+the data and pixel coordinates in event.x and event.xdata. In
+addition to the ``LocationEvent`` attributes, it has
==================== ==============================================================
MouseEvent attribute Description
==================== ==============================================================
-button button pressed None, 1, 2, 3
-key the key pressed: None, chr(range(255)), shift, win, or control
+``button`` button pressed None, 1, 2, 3
+``key`` the key pressed: None, chr(range(255)), shift, win, or control
==================== ==============================================================
Draggable Rectangle Exercise
----------------------------
-Write draggable rectangle class that is initialized with a Rectangle
-instance but will move its x,y location when dragged. Hint: you will
-need to store the orginal xy location of the rectangle which is stored
-as rect.xy and connect to the press, motion and release mouse events.
-When the mouse is pressed, check to see if the click occurs over your
-rectangle (see rect.contains) and if it does, store the rectangle xy
-and the location of the mouse click in data coords. In the motion
-event callback, compute the deltax and deltay of the mouse movement,
-and add those deltas to the origin of the rectangle you stored. The
-redraw the figure. On the button release event, just reset all the
-button press data you stored as None.
+Write draggable rectangle class that is initialized with a
+:class:`~matplotlib.patches.Rectangle` instance but will move its x,y
+location when dragged. Hint: you will need to store the orginal
+``xy`` location of the rectangle which is stored as rect.xy and
+connect to the press, motion and release mouse events. When the mouse
+is pressed, check to see if the click occurs over your rectangle (see
+:meth:`matplotlib.patches.Rectangle.contains`) and if it does, store
+the rectangle xy and the location of the mouse click in data coords.
+In the motion event callback, compute the deltax and deltay of the
+mouse movement, and add those deltas to the origin of the rectangle
+you stored. The redraw the figure. On the button release event, just
+reset all the button press data you stored as None.
Here is the solution::
@@ -212,8 +218,9 @@
plt.show()
-**Extra credit**: use the animation blit techniques discussed at
-http://www.scipy.org/Cookbook/Matplotlib/Animations to make the
+**Extra credit**: use the animation blit techniques discussed in the
+`animations recipe
+<http://www.scipy.org/Cookbook/Matplotlib/Animations>`_ to make the
animated drawing faster and smoother.
Extra credit solution::
@@ -325,30 +332,32 @@
Object Picking
==============
-You can enable picking by setting the ``picker`` property of an Artist
-(eg a matplotlib Line2D, Text, Patch, Polygon, AxesImage,
-etc...)
+You can enable picking by setting the ``picker`` property of an
+:class:`~matplotlib.artist.Artist` (eg a matplotlib
+:class:`~matplotlib.lines.Line2D`, :class:`~matplotlib.text.Text`,
+:class:`~matplotlib.patches.Patch`, :class:`~matplotlib.patches.Polygon`,
+:class:`~matplotlib.patches.AxesImage`, etc...)
-There are a variety of meanings of the picker property:
+There are a variety of meanings of the ``picker`` property:
-- None : picking is disabled for this artist (default)
+- ``None`` : picking is disabled for this artist (default)
-- boolean : if True then picking will be enabled and the artist will
+- ``boolean`` : if True then picking will be enabled and the artist will
fire a pick event if the mouse event is over the artist
-- float : if picker is a number it is interpreted as an epsilon
+- ``float`` : if picker is a number it is interpreted as an epsilon
tolerance in points and the the artist will fire off an event if its
data is within epsilon of the mouse event. For some artists like
lines and patch collections, the artist may provide additional data
to the pick event that is generated, eg the indices of the data
within epsilon of the pick event.
-- function : if picker is callable, it is a user supplied function
+- ``function`` : if picker is callable, it is a user supplied function
which determines whether the artist is hit by the mouse event. The
signature is ``hit, props = picker(artist, mouseevent)`` to
determine the hit test. If the mouse event is over the artist,
- return hit=True and props is a dictionary of properties you want
- added to the PickEvent attributes
+ return ``hit=True`` and props is a dictionary of properties you want
+ added to the :class:`~matplotlib.backend_bases.PickEvent` attributes
After you have enabled an artist for picking by setting the ``picker``
@@ -361,22 +370,24 @@
# now do something with this...
-The pick event (matplotlib.backend_bases.PickEvent) which is passed to
+The :class:`~matplotlib.backend_bases.PickEvent` which is passed to
your callback is always fired with two attributes:
-- mouseevent : the mouse event that generate the pick event. The
- mouse event in turn has attributes like x and y (the coords in
+- ``mouseevent`` : the mouse event that generate the pick event. The
+ mouse event in turn has attributes like ``x`` and ``y`` (the coords in
display space, eg pixels from left, bottom) and xdata, ydata (the
coords in data space). Additionally, you can get information about
which buttons were pressed, which keys were pressed, which Axes the
- mouse is over, etc. See matplotlib.backend_bases.MouseEvent for
+ mouse is over, etc. See :class:`matplotlib.backend_bases.MouseEvent` for
details.
-- artist : the matplotlib.artist that generated the pick event.
+- ``artist`` : the :class:`matplotlib.artist.Artist` that generated
+ the pick event.
-Additionally, certain artists like Line2D and PatchCollection may
-attach additional meta data like the indices into the data that meet
-the picker criteria (eg all the points in the line that are within the
+Additionally, certain artists like :class:`~matplotlib.lines.Line2D`
+and :class:`~matplotlib.collections.PatchCollection` may attach
+additional meta data like the indices into the data that meet the
+picker criteria (eg all the points in the line that are within the
specified epsilon tolerance)
Simple picking example
@@ -389,10 +400,10 @@
vertices that are within the pick distance tolerance. Our onpick
callback function simply prints the data that are under the pick
location. Different matplotlib Artists can attach different data to
-the PickEvent. For example, Line2D attaches the ind property, which
-are the indices into the line data under the pick point. See
-Line2D.pick for details on the PickEvent properties of the line. Here
-is the code::
+the PickEvent. For example, ``Line2D`` attaches the ind property,
+which are the indices into the line data under the pick point. See
+:meth:`~matplotlib.lines.Line2D.pick` for details on the ``PickEvent``
+properties of the line. Here is the code::
import numpy as np
import matplotlib.pyplot as plt
Modified: trunk/matplotlib/doc/users/figures/text_commands.py
===================================================================
--- trunk/matplotlib/doc/users/figures/text_commands.py 2008-06-10 15:53:19 UTC (rev 5462)
+++ trunk/matplotlib/doc/users/figures/text_commands.py 2008-06-10 18:08:50 UTC (rev 5463)
@@ -10,10 +10,15 @@
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
-ax.text(5, 8, 'italics text in data coords', style='italic')
+
+ax.text(5, 8, 'boxed italics text in data coords', style='italic',
+ bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})
+
ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=20)
-ax.text(0.95, 0.01, 'text in axes coords',
+ax.text(4, 3, unicode('unicode: Institut f\374r Festk\366rperphysik', 'latin-1'))
+
+ax.text(0.95, 0.01, 'colored text in axes coords',
verticalalignment='bottom', horizontalalignment='right',
transform=ax.transAxes,
color='green', fontsize=20)
Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-06-10 15:53:19 UTC (rev 5462)
+++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-06-10 18:08:50 UTC (rev 5463)
@@ -1,6 +1,24 @@
"""
Abstract base classes define the primitives that renderers and
graphics contexts must implement to serve as a matplotlib backend
+
+:class:`RendererBase`
+ An abstract base class to handle drawing/rendering operations.
+
+:class:`FigureCanvasBase`
+ The abstraction layer that separates the
+ :class:`matplotlib.figure.Figure` from the backend specific
+ details like a user interface drawing area
+
+:class:`GraphicsContextBase`
+ An abstract base class that provides color, line styles, etc...
+
+:class:`Event`
+ The base class for all of the matplotlib event
+ handling. Derived classes suh as :class:`KeyEvent` and
+ :class:`MouseEvent` store the meta data like keys and buttons
+ pressed, x and y locations in pixel and
+ :class:`~matplotlib.axes.Axes` coordinates.
"""
from __future__ import division
@@ -20,36 +38,39 @@
The following methods *must* be implemented in the backend:
- draw_path
- draw_image
- draw_text
- get_text_width_height_descent
+ * draw_path
+ * draw_image
+ * draw_text
+ * get_text_width_height_descent
The following methods *should* be implemented in the backend for
optimization reasons:
- draw_markers
- draw_path_collection
- draw_quad_mesh
+ * draw_markers
+ * draw_path_collection
+ * draw_quad_mesh
"""
def __init__(self):
self._texmanager = None
def open_group(self, s):
- """open a grouping element with label s
- Is only currently used by backend_svg
"""
+ Open a grouping element with label ``s.`` Is only currently used by
+ :mod:`~matplotlib.backends.backend_svg`
+ """
pass
def close_group(self, s):
- """close a grouping element with label s
- Is only currently used by backend_svg
"""
+ Close a grouping element with label ``s``
+ Is only currently used by :mod:`~matplotlib.backends.backend_svg`
+ """
pass
def draw_path(self, gc, path, transform, rgbFace=None):
"""
- Draws a Path instance using the given affine transform.
+ Draws a :class:`~matplotlib.path.Path` instance using the
+ given affine transform.
"""
raise NotImplementedError
@@ -60,13 +81,14 @@
that behavior, those vertices should be removed before calling
this function.
- marker_trans is an affine transform applied to the marker.
- trans is an affine transform applied to the path.
+ ``marker_trans`` is an affine transform applied to the marker.
+ ``trans`` is an affine transform applied to the path.
This provides a fallback implementation of draw_markers that
- makes multiple calls to draw_path. Some backends may want to
- override this method in order to draw the marker only once and
- reuse it multiple times.
+ makes multiple calls to
+ :meth:`draw_path`. Some
+ backends may want to override this method in order to draw the
+ marker only once and reuse it multiple times.
"""
tpath = trans.transform_path(path)
for x, y in tpath.vertices:
@@ -80,20 +102,24 @@
linestyles, antialiaseds):
"""
Draws a collection of paths, selecting drawing properties from
- the lists facecolors, edgecolors, linewidths, linestyles and
- antialiaseds. offsets is a list of offsets to apply to each
- of the paths. The offsets in offsets are first transformed by
- offsetTrans before being applied.
+ the lists ``facecolors``, ``edgecolors``, ``linewidths``,
+ ``linestyles`` and ``antialiaseds``. `` offsets`` is a list of
+ offsets to apply to each of the paths. The offsets in
+ ``offsets`` are first transformed by ``offsetTrans`` before
+ being applied.
This provides a fallback implementation of
draw_path_collection that makes multiple calls to draw_path.
Some backends may want to override this in order to render
each set of path data only once, and then reference that path
multiple times with the different offsets, colors, styles etc.
- The generator methods _iter_collection_raw_paths and
- _iter_collection are provided to help with (and standardize)
- the implementation across backends. It is highly recommended
- to use those generators, so that changes to the behavior of
+ The generator methods
+ :meth:`_iter_collection_raw_paths`
+ and
+ :meth:`_iter_collection`
+ are provided to help with (and standardize) the implementation
+ across backends. It is highly recommended to use those
+ generators, so that changes to the behavior of
draw_path_collection can be made globally.
"""
path_ids = []
@@ -115,7 +141,7 @@
showedges):
"""
This provides a fallback implementation of draw_quad_mesh that
- generates paths and then calls draw_path_collection.
+ generates paths and then calls :meth:`draw_path_collection`.
"""
from matplotlib.collections import QuadMesh
paths = QuadMesh.convert_mesh_to_paths(
@@ -135,8 +161,8 @@
def _iter_collection_raw_paths(self, master_transform, paths, all_transforms):
"""
- This is a helper method (along with _iter_collection) to make
- it easier to write a space-efficent draw_path_collection
+ This is a helper method (along with :meth:`_iter_collection`) to make
+ it easier to write a space-efficent :meth:`draw_path_collection`
implementation in a backend.
This method yields all of the base path/transform
@@ -144,7 +170,7 @@
list of transforms.
The arguments should be exactly what is passed in to
- draw_path_collection.
+ :meth:`draw_path_collection`.
The backend should take each yielded path and transform and
create an object can be referenced (reused) later.
@@ -168,8 +194,8 @@
linewidths, linestyles, antialiaseds):
"""
This is a helper method (along with
- _iter_collection_raw_paths) to make it easier to write a
- space-efficent draw_path_collection implementation in a
+ :meth:`_iter_collection_raw_paths`) to make it easier to write
+ a space-efficent :meth:`draw_path_collection` implementation in a
backend.
This method yields all of the path, offset and graphics
@@ -237,7 +263,7 @@
def get_image_magnification(self):
"""
- Get the factor by which to magnify images passed to draw_image.
+ Get the factor by which to magnify images passed to :meth:`draw_image`.
Allows a backend to have images at a different resolution to other
artists.
"""
@@ -245,13 +271,13 @@
def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None):
"""
- Draw the Image instance into the current axes; x is the
- distance in pixels from the left hand side of the canvas. y is
- the distance from the origin. That is, if origin is upper, y
- is the distance from top. If origin is lower, y is the
- distance from bottom
+ Draw the :class:`~matplotlib.image.Image` instance into the
+ current axes; ``x`` is the distance in pixels from the left
+ hand side of the canvas. ``y`` is the distance from the
+ origin. That is, if origin is upper, y is the distance from
+ top. If origin is lower, y is the distance from bottom
- bbox is a matplotlib.transforms.BBox instance for clipping, or
+ bbox is a :class:`~matplotlib.transforms.Bbox` instance for clipping, or
None
"""
raise NotImplementedError
@@ -268,8 +294,10 @@
def draw_text(self, gc, x, y, s, prop, angle, ismath=False):
"""
- Draw the text.Text instance s at x,y (display coords) with font
- properties instance prop at angle in degrees, using GraphicsContext gc
+ Draw the :class:`~matplotlib.text.Text` instance s at ``x``,
+ ``y`` (display coords) with
+ :class:`~matplotlib.font_manager.FontProperties` instance
+ ``prop`` at ``angle`` in degrees, using :class:`GraphicsContextBase` gc
**backend implementers note**
@@ -285,9 +313,11 @@
raise NotImplementedError
def flipy(self):
- """return true if y small numbers are top for renderer
- Is used for drawing text (text.py) and images (image.py) only
"""
+ Return true if y small numbers are top for renderer Is used
+ for drawing text (:mod:`matplotlib.text`) and images
+ (:mod:`matplotlib.image`) only
+ """
return True
def get_canvas_width_height(self):
@@ -295,6 +325,9 @@
return 1, 1
def get_texmanager(self):
+ """
+ return the :class:matplotlib.texmanager.TexManager` instance
+ """
if self._texmanager is None:
from matplotlib.texmanager import TexManager
self._texmanager = TexManager()
@@ -304,13 +337,13 @@
"""
get the width and height, and the offset from the bottom to the
baseline (descent), in display coords of the string s with
- FontPropertry prop
+ :class:`~matplotlib.font_manager.FontProperties` prop
"""
raise NotImplementedError
def new_gc(self):
"""
- Return an instance of a GraphicsContextBase
+ Return an instance of a :class:`GraphicsContextBase`
"""
return GraphicsContextBase()
@@ -322,8 +355,9 @@
You need to override this function (unless your backend doesn't have a
dpi, eg, postscript or svg).
- Some imaging systems assume some value for pixels per inch.
- points to pixels = points * pixels_per_inch/72.0 * dpi/72.0
+ Some imaging systems assume some value for pixels per inch""
+
+ points to pixels = points * pixels_per_inch/72.0 * dpi/72.0
"""
return points
@@ -338,8 +372,9 @@
class GraphicsContextBase:
- """An abstract base class that provides color, line styles, etc...
"""
+ An abstract base class that provides color, line styles, etc...
+ """
# a mapping from dash styles to suggested offset, dash pairs
dashd = {
@@ -395,15 +430,15 @@
def get_clip_rectangle(self):
"""
- Return the clip rectangle as a Bbox instance
+ Return the clip rectangle as a :class:`~matplotlib.transforms.Bbox` instance
"""
return self._cliprect
def get_clip_path(self):
"""
Return the clip path in the form (path, transform), where path
- is a path.Path instance, and transform as an affine transform
- to apply to the path before clipping.
+ is a :class:`~matplotlib.path.Path` instance, and transform as
+ an affine transform to apply to the path before clipping.
"""
if self._clippath is not None:
return self._clippath.get_transformed_path_and_affine()
@@ -413,7 +448,9 @@
"""
Return the dash information as an offset dashlist tuple The
dash list is a even size list that gives the ink on, ink off
- in pixels. See p107 of to postscript BLUEBOOK for more info
+ in pixels. See p107 of to postscript `BLUEBOOK
+ <http://www-cdf.fnal.gov/offline/PostScript/BLUEBOOK.PDF>`_
+ for more info
Default value is None
"""
@@ -479,7 +516,7 @@
def set_clip_path(self, path):
"""
Set the clip path and transformation. Path should be a
- transforms.TransformedPath instance.
+ :class:`~matplotlib.transforms.TransformedPath` instance.
"""
assert path is None or isinstance(path, transforms.TransformedPath)
self._clippath = path
@@ -487,9 +524,12 @@
def set_dashes(self, dash_offset, dash_list):
"""
Set the dash style for the gc.
- dash_offset is the offset (usually 0).
- dash_list specifies the on-off sequence as points
- (None, None) specifies a solid line
+
+ ``dash_offset``
+ is the offset (usually 0).
+
+ ``dash_list``
+ specifies the on-off sequence as points. ``(None, None)`` specifies a solid line
"""
self._dashes = dash_offset, dash_list
@@ -499,8 +539,8 @@
html hex color string, an rgb unit tuple, or a float between 0
and 1. In the latter case, grayscale is used.
- The GraphicsContext converts colors to rgb internally. If you
- know the color is rgb already, you can set isRGB to True to
+ The :class:`GraphicsContextBase` converts colors to rgb internally. If you
+ know the color is rgb already, you can set ``isRGB=True`` to
avoid the performace hit of the conversion
"""
if isRGB:
@@ -510,7 +550,7 @@
def set_graylevel(self, frac):
"""
- Set the foreground color to be a gray level with frac frac
+ Set the foreground color to be a gray level with ``frac`` frac
"""
self._rgb = (frac, frac, frac)
@@ -556,11 +596,15 @@
class Event:
"""
A matplotlib event. Attach additional attributes as defined in
- FigureCanvas.connect. The following attributes are defined and
+ :meth:`FigureCanvasBase.connect`. The following attributes are defined and
shown with their default values
- name # the event name
- canvas # the FigureCanvas instance generating the event
+ ``name``
+ the event name
+
+ ``canvas``
+ the FigureCanvas instance generating the event
+
"""
def __init__(self, name, canvas,guiEvent=None):
self.name = name
@@ -572,10 +616,10 @@
"""
An event triggered by a draw operation on the canvas
- Attributes are
- name
- canvas
- renderer - the Renderer instance
+ In addition to the :class`Event` attributes, the following event attributes are defined:
+
+ ``renderer``
+ the :class:`RendererBase` instance for the draw event
"""
def __init__(self, name, canvas, renderer):
Event.__init__(self, name, canvas)
@@ -585,11 +629,13 @@
"""
An event triggered by a canvas resize
- Attributes are
- name
- canvas
- width # width of the canvas in pixels
- height # height of the canvas in pixels
+ In addition to the :class`Event` attributes, the following event attributes are defined:
+
+ ``width``
+ width of the canvas in pixels
+
+ ``height``
+ height of the canvas in pixels
"""
def __init__(self, name, canvas):
Event.__init__(self, name, canvas)
@@ -602,24 +648,33 @@
The following additional attributes are defined and shown with
their default values
- x = None # x position - pixels from left of canvas
- y = None # y position - pixels from bottom of canvas
- inaxes = None # the Axes instance if mouse us over axes
- xdata = None # x coord of mouse in data coords
- ydata = None # y coord of mouse in data coords
+ In addition to the :class`Event` attributes, the following event attributes are defined:
+ ``x``
+ x position - pixels from left of canvas
+
+ ``y``
+ y position - pixels from bottom of canvas
+
+ ``inaxes``
+ the :class:`~matplotlib.axes.Axes` instance if mouse is over axes
+
+ ``xdata``
+ x coord of mouse in data coords
+
+ ``ydata``
+ y coord of mouse in data coords
+
"""
x = None # x position - pixels from left of canvas
y = None # y position - pixels from right of canvas
- button = None # button pressed None, 1, 2, 3
inaxes = None # the Axes instance if mouse us over axes
xdata = None # x coord of mouse in data coords
ydata = None # y coord of mouse in data coords
def __init__(self, name, canvas, x, y,guiEvent=None):
"""
- x, y in figure coords, 0,0 = bottom, left
- button pressed None, 1, 2, 3
+ ``x``, ``y`` in figure coords, 0,0 = bottom, left
"""
Event.__init__(self, name, canvas,guiEvent=guiEvent)
self.x = x
@@ -653,20 +708,16 @@
class MouseEvent(LocationEvent):
"""
- A mouse event (button_press_event, button_release_event, scroll_event,
- motion_notify_event).
+ A mouse event ('button_press_event', 'button_release_event', 'scroll_event',
+ 'motion_notify_event').
- The following attributes are defined and shown with their default
- values
+ In addition to the :class`Event` and :class:`LocationEvent`
+ attributes, the following attributes are defined:
- x = None # x position - pixels from left of canvas
- y = None # y position - pixels from bottom of canvas
- button = None # button pressed None, 1, 2, 3, 'up', 'down'
- (up and down are used for scroll events)
- key = None # the key pressed: None, chr(range(255), shift, win, or control
- inaxes = None # the Axes instance if mouse us over axes
- xdata = None # x coord of mouse in data coords
- ydata = None # y coord of mouse in data coords
+ ``button``
+ button pressed None, 1, 2, 3, 'up', 'down' (up and down are used for scroll events)
+ ``key``
+ the key pressed: None, chr(range(255), shift, win, or control
"""
x = None # x position - pixels from left of canvas
@@ -691,12 +742,18 @@
a pick event, fired when the user picks a location on the canvas
sufficiently close to an artist.
- Attrs: all the Event attrs plus
- mouseevent : the MouseEvent that generated the pick
- artist : the artist picked
+ Attrs: all the :class:`Event` attributes plus
- extra class dependent attrs -- eg a Line2D pick may define
- different extra attributes than a PatchCollection pick event
+ ``mouseevent``
+ the :class:`MouseEvent` that generated the pick
+
+ ``artist``
+ the :class:`~matplotlib.artist.Artist` picked
+
+ extra class dependent attrs -- eg a
+ :class:`~matplotlib.lines.Line2D` pick may define different extra
+ attributes than a :class:`~matplotlib.collections.PatchCollection`
+ pick event
"""
def __init__(self, name, canvas, mouseevent, artist, guiEvent=None, **kwargs):
Event.__init__(self, name, canvas, guiEvent)
@@ -710,17 +767,13 @@
A key event (key press, key release).
Attach additional attributes as defined in
- FigureCanvas.connect.
+ :meth:`FigureCanvasBase.connect`.
- The following attributes are defined and shown with their default
- values
+ In addition to the :class`Event` and :class:`LocationEvent`
+ attributes, the following attributes are defined:
- x = None # x position - pixels from left of canvas
- y = None # y position - pixels from bottom of canvas
- key = None # the key pressed: None, chr(range(255), shift, win, or control
- inaxes = None # the Axes instance if mouse us over axes
- xdata = None # x coord of mouse in data coords
- ydata = None # y coord of mouse in data coords
+ ``key``
+ the key pressed: None, chr(range(255), shift, win, or control
This interface may change slightly when better support for
modifier keys is included
@@ -735,9 +788,10 @@
"""
The canvas the figure renders into.
- Public attribute
+ Public attributes
- figure - A Figure instance
+ ``figure``
+ A :class:`matplotlib.figure.Figure` instance
"""
events = (
@@ -775,8 +829,10 @@
def onRemove(self, ev):
"""
Mouse event processor which removes the top artist
- under the cursor. Connect this to the mouse_press_event
- using canvas.mpl_connect('mouse_press_event',canvas.onRemove)
+ under the cursor. Connect this to the 'mouse_press_event'
+ using::
+
+ canvas.mpl_connect('mouse_press_event',canvas.onRemove)
"""
def sort_artists(artists):
# This depends on stable sort and artists returned
@@ -807,8 +863,10 @@
def onHilite(self, ev):
"""
Mouse event processor which highlights the artists
- under the cursor. Connect this to the motion_notify_event
- using canvas.mpl_connect('motion_notify_event',canvas.onHilite)
+ under the cursor. Connect this to the 'motion_notify_event'
+ using::
+
+ canvas.mpl_connect('motion_notify_event',canvas.onHilite)
"""
if not hasattr(self,'_active'): self._active = dict()
@@ -862,22 +920,40 @@
pass
def draw_event(self, renderer):
+ """
+ This method will be call all functions connected to the
+ 'draw_event' with a :class:`DrawEvent`
+ """
+
s = 'draw_event'
event = DrawEvent(s, self, renderer)
self.callbacks.process(s, event)
def resize_event(self):
+ """
+ This method will be call all functions connected to the
+ 'resize_event' with a :class:`ResizeEvent`
+ """
+
s = 'resize_event'
event = ResizeEvent(s, self)
self.callbacks.process(s, event)
def key_press_event(self, key, guiEvent=None):
+ """
+ This method will be call all functions connected to the
+ 'key_press_event' with a :class:`KeyEvent`
+ """
self._key = key
s = 'key_press_event'
event = KeyEvent(s, self, key, self._lastx, self._lasty, guiEvent=guiEvent)
self.callbacks.process(s, event)
def key_release_event(self, key, guiEvent=None):
+ """
+ This method will be call all functions connected to the
+ 'key_release_event' with a :class:`KeyEvent`
+ """
s = 'key_release_event'
event = KeyEvent(s, self, key, self._lastx, self._lasty, guiEvent=guiEvent)
self.callbacks.process(s, event)
@@ -886,7 +962,7 @@
def pick_event(self, mouseevent, artist, **kwargs):
"""
This method will be called by artists who are picked and will
- fire off PickEvent callbacks registered listeners
+ fire off :class:`PickEvent` callbacks registered listeners
"""
s = 'pick_event'
event = PickEvent(s, self, mouseevent, artist, **kwargs)
@@ -896,7 +972,10 @@
"""
Backend derived classes should call this function on any
scroll wheel event. x,y are the canvas coords: 0,0 is lower,
- left. button and key are as defined in MouseEvent
+ left. button and key are as defined in MouseEvent.
+
+ This method will be call all functions connected to the
+ 'scroll_event' with a :class:`MouseEvent` instance.
"""
self._button = button
s = 'scroll_event'
@@ -908,7 +987,11 @@
"""
Backend derived classes should call this function on any mouse
button press. x,y are the canvas coords: 0,0 is lower, left.
- button and key are as defined in MouseEvent
+ button and key are as defined in :class:`MouseEvent`.
+
+ This method will be call all functions connected to the
+ 'button_press_event' with a :class:`MouseEvent` instance.
+
"""
self._button = button
s = 'button_press_event'
@@ -919,7 +1002,11 @@
"""
Backend derived classes should call this function on any mouse
button release. x,y are the canvas coords: 0,0 is lower, left.
- button and key are as defined in MouseEvent
+ button and key are as defined in :class:`MouseEvent`
+
+ This method will be call all functions connected to the
+ 'button_release_event' with a :class:`MouseEvent` instance.
+
"""
s = 'button_release_event'
event = MouseEvent(s, self, x, y, button, self._key, guiEvent=guiEvent)
@@ -931,6 +1018,10 @@
Backend derived classes should call this function on any
motion-notify-event. x,y are the canvas coords: 0,0 is lower, left.
button and key are as defined in MouseEvent
+
+ This method will be call all functions connected to the
+ 'motion_notify_event' with a :class:`MouseEvent` instance.
+
"""
self._lastx, self._lasty = x, y
s = 'motion_notify_event'
@@ -940,13 +1031,13 @@
def draw(self, *args, **kwargs):
"""
- Render the figure
+ Render the :class:`~matplotlib.figure.Figure`
"""
pass
def draw_idle(self, *args, **kwargs):
"""
- draw only if idle; defaults to draw but backends can overrride
+ :meth:`draw` only if idle; defaults to draw but backends can overrride
"""
self.draw(*args, **kwargs)
@@ -958,8 +1049,10 @@
pass
def get_width_height(self):
- """return the figure width and height in points or pixels
- (depending on the backend), truncated to integers"""
+ """
+ return the figure width and height in points or pixels
+ (depending on the backend), truncated to integers
+ """
return int(self.figure.bbox.width), int(self.figure.bbox.height)
filetypes = {
@@ -1038,13 +1131,28 @@
face color background and you'll probably want to override this on
hardcopy.
- filename - can also be a file object on image backends
- orientation - only currently applies to PostScript printing.
- dpi - the dots per inch to save the figure in; if None, use savefig.dpi
- facecolor - the facecolor of the figure
- edgecolor - the edgecolor of the figure
- orientation - 'landscape' | 'portrait' (not supported on all backends)
- format - when set, forcibly set the file format to save to
+ Arguments are:
+
+ ``filename``
+ can also be a file object on image backends
+
+ ``orientation``
+ only currently applies to PostScript printing.
+
+ ``dpi``
+ the dots per inch to save the figure in; if None, use savefig.dpi
+
+ ``facecolor``
+ the facecolor of the figure
+
+ ``edgecolor``
+ the edgecolor of the figure
+
+ ``orientation`` '
+ landscape' | 'portrait' (not supported on all backends)
+
+ ``format``
+ when set, forcibly set the file format to save to
"""
if format is None:
if cbook.is_string_like(filename):
@@ -1123,24 +1231,24 @@
where event is a MplEvent. The following events are recognized
- * 'resize_event'
- * 'draw_event'
- * 'key_press_event'
- * 'key_release_event'
- * 'button_press_event'
- * 'button_release_event'
- * 'scroll_event'
- * 'motion_notify_event'
- * 'pick_event'
+ - 'button_press_event'
+ - 'button_release_event'
+ - 'draw_event'
+ - 'key_press_event'
+ - 'key_release_event'
+ - 'motion_notify_event'
+ - 'pick_event'
+ - 'resize_event'
+ - 'scroll_event'
For the three events above, if the mouse is over the axes,
the variable event.inaxes will be set to the axes it is over,
and additionally, the variables event.xdata and event.ydata
will be defined. This is the mouse location in data coords.
- See backend_bases.MplEvent.
+ See :class`MplEvent`
return value is a connection id that can be used with
- mpl_disconnect
+ :meth:`mpl_disconnect`
"""
return self.callbacks.connect(s, func)
@@ -1162,9 +1270,13 @@
"""
Helper class for matlab mode, wraps everything up into a neat bundle
- Public attibutes
- canvas - A FigureCanvas instance
- num - The figure number
+ Public attibutes:
+
+ ``canvas``
+ A :class:`FigureCanvasBase` instance
+
+ ``num``
+ The figure nuamber
"""
def __init__(self, canvas, num):
self.canvas = canvas
@@ -1248,7 +1360,7 @@
backends must implement a canvas that handles connections for
'button_press_event' and 'button_release_event'. See
- FigureCanvas.connect for more information
+ :meth:`FigureCanvasBase.connect` for more information
They must also define
@@ -1262,18 +1374,18 @@
* draw_rubberband (optional) : draw the zoom to rect
"rubberband" rectangle
- * press : (optional) whenever a mouse button is pressed, you'll be
+ * press : (optional) whenever a mouse button is pressed, you'll be
notified with the event
- * release : (optional) whenever a mouse button is released,
- you'll be notified with the event
+ * release : (optional) whenever a mouse button is released,
+ you'll be notified with the event
- * dynamic_update (optional) dynamically update the window while
- navigating
+ * dynamic_update (optional) dynamically update the window while
+ navigating
- * set_message (optional) - display message
+ * set_message (optional) - display message
- * set_history_buttons (optional) - you can change the history
+ * set_history_buttons (optional) - you can change the history
back / forward buttons to indicate disabled / enabled state.
That's it, we'll do the rest!
@@ -1332,8 +1444,8 @@
def _init_toolbar(self):
"""
This is where you actually build the GUI widgets (called by
- __init__). The icons home.xpm, back.xpm, forward.xpm,
- hand.xpm, zoom_to_rect.xpm and filesave.xpm are standard
+ __init__). The icons ``home.xpm``, ``back.xpm``, ``forward.xpm``,
+ ``hand.xpm``, ``zoom_to_rect.xpm`` and ``filesave.xpm`` are standard
across backends (there are ppm versions in CVS also).
You just need to set the callbacks
@@ -1647,7 +1759,7 @@
def set_cursor(self, cursor):
"""
- Set the current cursor to one of the backend_bases.Cursors
+ Set the current cursor to one of the :class:`Cursors`
enums values
"""
pass
Modified: trunk/matplotlib/lib/matplotlib/text.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/text.py 2008-06-10 15:53:19 UTC (rev 5462)
+++ trunk/matplotlib/lib/matplotlib/text.py 2008-06-10 18:08:50 UTC (rev 5463)
@@ -42,35 +42,38 @@
# class is build so we define an initial set here for the init
# function and they will be overridden after object defn
artist.kwdocd['Text'] = """\
- alpha: float
- animated: [True | False]
- backgroundcolor: any matplotlib color
- bbox: rectangle prop dict plus key 'pad' which is a pad in points
- clip_box: a matplotlib.transform.Bbox instance
- clip_on: [True | False]
- color: any matplotlib color
- family: [ 'serif' | 'sans-serif' | 'cursive' | 'fantasy' | 'monospace' ]
- figure: a matplotlib.figure.Figure instance
- fontproperties: a matplotlib.font_manager.FontProperties instance
- horizontalalignment or ha: [ 'center' | 'right' | 'left' ]
- label: any string
- linespacing: float
- lod: [True | False]
- multialignment: ['left' | 'right' | 'center' ]
- name or fontname: string eg, ['Sans' | 'Courier' | 'Helvetica' ...]
- position: (x,y)
- rotation: [ angle in degrees 'vertical' | 'horizontal'
- size or fontsize: [ size in points | relative size eg 'smaller', 'x-large' ]
- style or fontstyle: [ 'normal' | 'italic' | 'oblique']
- text: string
- transform: a matplotlib.transform transformation instance
- variant: [ 'normal' | 'small-caps' ]
- verticalalignment or va: [ 'center' | 'top' | 'bottom' | 'baseline' ]
- visible: [True | False]
- weight or fontweight: [ 'normal' | 'bold' | 'heavy' | 'light' | 'ultrabold' | 'ultralight']
- x: float
- y: float
- zorder: any number
+ ========================== =========================================================================
+ alpha float
+ ========================== =========================================================================
+ animated [True | False]
+ backgroundcolor any matplotlib color
+ bbox rectangle prop dict plus key 'pad' which is a pad in points
+ clip_box a matplotlib.transform.Bbox instance
+ clip_on [True | False]
+ color any matplotlib color
+ family [ 'serif' | 'sans-serif' | 'cursive' | 'fantasy' | 'monospace' ]
+ figure a matplotlib.figure.Figure instance
+ fontproperties a matplotlib.font_manager.FontProperties instance
+ horizontalalignment or ha [ 'center' | 'right' | 'left' ]
+ label any string
+ linespacing float
+ lod [True | False]
+ multialignment ['left' | 'right' | 'center' ]
+ name or fontname string eg, ['Sans' | 'Courier' | 'Helvetica' ...]
+ position (x,y)
+ rotation [ angle in degrees 'vertical' | 'horizontal'
+ size or fontsize [ size in points | relative size eg 'smaller', 'x-large' ]
+ style or fontstyle [ 'normal' | 'italic' | 'oblique']
+ text string
+ transform a matplotlib.transform transformation instance
+ variant [ 'normal' | 'small-caps' ]
+ verticalalignment or va [ 'center' | 'top' | 'bottom' | 'baseline' ]
+ visible [True | False]
+ weight or fontweight [ 'normal' | 'bold' | 'heavy' | 'light' | 'ultrabold' | 'ultralight']
+ x float
+ y float
+ zorder any number
+ ========================== =========================================================================
"""
class Text(Artist):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-10 15:54:00
|
Revision: 5462
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5462&view=rev
Author: jdh2358
Date: 2008-06-10 08:53:19 -0700 (Tue, 10 Jun 2008)
Log Message:
-----------
fixed auto-legend wart for bar and friends
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-06-10 15:50:55 UTC (rev 5461)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-06-10 15:53:19 UTC (rev 5462)
@@ -5773,6 +5773,16 @@
#fig.savefig('histogram_demo',dpi=72)
plt.show()
+
+ You can use labels for your histogram, and only the first
+ Rectangle gets the label (the others get the magic string
+ '_nolegend_'. This will make the histograms work in the
+ intuitive way for bar charts::
+
+ ax.hist(10+2*np.random.randn(1000), label='men')
+ ax.hist(12+3*np.random.randn(1000), label='women', alpha=0.5)
+ ax.legend()
+
"""
if not self._hold: self.cla()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|