diff --git a/doc/_static/mpl.css b/doc/_static/mpl.css index c6b8b5327e60..bd174f670d49 100644 --- a/doc/_static/mpl.css +++ b/doc/_static/mpl.css @@ -508,7 +508,7 @@ ul.keywordmatches li.goodmatch a { table.docutils { border-spacing: 2px; - border: collapse; + border-collapse: collapse; border-top-width: 1px; border-right-width: 0px; border-bottom-width: 1px; @@ -535,3 +535,34 @@ table.docutils th { table.docutils td { border-width: 1px 0 1px 0; } + +#matplotlib-examples ul li{ + font-size: large; +} + +#matplotlib-examples ul li ul{ + margin-bottom:20px; + overflow:hidden; + border-top:1px solid #ccc; +} + +#matplotlib-examples ul li ul li { + font-size: small; + line-height:1.75em; + display:inline; + float: left; + width: 22em; +} + +#overview ul li ul{ + margin-bottom:20px; + overflow:hidden; + border-top:1px solid #ccc; +} + +#overview ul li ul li { + display:inline; + float: left; + width: 30em; +} + diff --git a/doc/_templates/index.html b/doc/_templates/index.html index 1d88871b96f6..2768472bc8c8 100644 --- a/doc/_templates/index.html +++ b/doc/_templates/index.html @@ -1,34 +1,44 @@ {% extends "layout.html" %} {% set title = 'matplotlib: python plotting' %} +{% block extrahead %} + + + {{ super() }} +{% endblock %} {% block body %} -

John Hunter (1968-2012)

- - - - - - -
- - -

- On August 28 2012, John D. Hunter, the creator of matplotlib, died - from complications arising from cancer treatment, after a brief but - intense battle with this terrible illness. John is survived by his - wife Miriam, his three daughters Rahel, Ava and Clara, his sisters - Layne and Mary, and his mother Sarah.

- -

- If you have benefited from John's many contributions, please say - thanks in the way that would matter most to him. Please consider - making a donation to - the John Hunter Memorial - Fund.

-
-

Introduction

matplotlib is a python 2D plotting library which produces @@ -66,6 +76,32 @@

Introduction

properties, axes properties, etc, via an object oriented interface or via a set of functions familiar to MATLAB users.

+
+

John Hunter (1968-2012)

+ + + + + +
+ + +

+ On August 28 2012, John D. Hunter, the creator of matplotlib, died + from complications arising from cancer treatment, after a brief but + intense battle with this terrible illness. John is survived by his + wife Miriam, his three daughters Rahel, Ava and Clara, his sisters + Layne and Mary, and his mother Sarah.

+ +

+ If you have benefited from John's many contributions, please say + thanks in the way that would matter most to him. Please consider + making a donation to + the John Hunter Memorial + Fund.

+
+
+

Download

Visit the @@ -132,41 +168,41 @@

Need help?

Toolkits

-

There are several matplotlib add-on toolkits, including the projection -and mapping toolkit -basemap, 3d plotting with mplot3d, axes and axis helpers in axes_grid and more. +

There are several matplotlib add-on toolkits, +including a choice of two projection and mapping toolkits basemap and +cartopy, +3d plotting with mplot3d, +axes and axis helpers in axes_grid and more.

Citing matplotlib

- matplotlib is the brainchild of John Hunter (1968-2012), who has put an - inordinate amount of effort into producing a piece of software utilized by - thousands of scientists worldwide. + matplotlib is the brainchild of John Hunter (1968-2012), who, along with its many + contributors, have put an immeasurable amount of time and effort into producing a + piece of software utilized by thousands of scientists worldwide. If matplotlib contributes to a project that leads to a scientific publication, - please acknowledge this fact by citing the project. You can use this + please acknowledge this work by citing the project. You can use this ready-made citation entry.

Open source

-

Please -consider donating -to support matplotlib development or to -the John Hunter Memorial -Fund.

+

+Please consider donating +to support matplotlib development or to the John Hunter Memorial Fund. +

-

The matplotlib license -is based on the Python Software Foundation -(PSF) license.

+

+The matplotlib license is based on the Python Software Foundation +(PSF) license. +

-

There is an active developer community and a long list of people -who have made significant contributions.

+

+There is an active developer community and a long list of people +who have made significant contributions. +

@@ -178,6 +214,4 @@

Open source

Mathematica is a registered trademark of Wolfram Research, Inc.

- - {% endblock %} diff --git a/doc/_templates/layout.html b/doc/_templates/layout.html index ea623edd65e4..890ffcc2f009 100644 --- a/doc/_templates/layout.html +++ b/doc/_templates/layout.html @@ -1,44 +1,10 @@ {% extends "!layout.html" %} - - {% block rootrellink %}
  • home
  • -
  • downloads
  • -
  • search
  • examples
  • gallery
  • -
  • citation
  • +
  • pyplot
  • docs »
  • {% endblock %} diff --git a/doc/api/cm_api.rst b/doc/api/cm_api.rst index 86b87cd4cda7..6cf4a262a62d 100644 --- a/doc/api/cm_api.rst +++ b/doc/api/cm_api.rst @@ -2,7 +2,6 @@ cm (colormap) ************* - :mod:`matplotlib.cm` ==================== diff --git a/doc/api/colors_api.rst b/doc/api/colors_api.rst index 766eb763f612..bd577af02ed4 100644 --- a/doc/api/colors_api.rst +++ b/doc/api/colors_api.rst @@ -2,6 +2,9 @@ colors ****** +For a visual representation of the matplotlib colormaps, see the +"Color" section in the gallery. + :mod:`matplotlib.colors` ======================== diff --git a/doc/api/matplotlib_configuration_api.rst b/doc/api/matplotlib_configuration_api.rst index e8788289d162..90ba3183ad55 100644 --- a/doc/api/matplotlib_configuration_api.rst +++ b/doc/api/matplotlib_configuration_api.rst @@ -1,13 +1,7 @@ -************* -configuration -************* - - -:mod:`matplotlib` -================= +The top level :mod:`matplotlib` module +====================================== .. automodule:: matplotlib :members: rc, rcdefaults, use :undoc-members: :show-inheritance: - diff --git a/doc/api/nxutils_api.rst b/doc/api/nxutils_api.rst deleted file mode 100644 index 6c17d8341370..000000000000 --- a/doc/api/nxutils_api.rst +++ /dev/null @@ -1,12 +0,0 @@ -******* -nxutils -******* - -:mod:`matplotlib.nxutils` -=========================== - -.. automodule:: matplotlib.nxutils - :members: - :undoc-members: - :show-inheritance: - diff --git a/doc/conf.py b/doc/conf.py index f6ad0f7818cd..0c786ba2fa04 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -105,7 +105,6 @@ plot_formats = [('png', 80), ('hires.png', 200), ('pdf', 50)] # Subdirectories in 'examples/' directory of package and titles for gallery -# TODO: Change to OrderedDict when Matplotlib drops support for Python < 2.7 mpl_example_sections = ( ('lines_bars_and_markers', 'Lines, bars, and markers'), ('shapes_and_collections', 'Shapes and collections'), @@ -251,3 +250,9 @@ 'Matplotlib', "Python plotting package", 'Programming', 1), ] + + +################# numpydoc config #################### +numpydoc_show_class_members = False + + diff --git a/doc/mpl_toolkits/index.rst b/doc/mpl_toolkits/index.rst index b3c17fa92cb9..ba010b225e1a 100644 --- a/doc/mpl_toolkits/index.rst +++ b/doc/mpl_toolkits/index.rst @@ -22,13 +22,31 @@ Toolkits are collections of application-specific functions that extend matplotli .. _toolkit_basemap: -Basemap -======= +Basemap (*Not distributed with matplotlib*) +============================================ Plots data on map projections, with continental and political -boundaries, see `basemap `_ +boundaries, see `basemap `_ docs. +.. image:: http://matplotlib.org/basemap/_images/contour1.png + :height: 400px + + + +Cartopy (*Not distributed with matplotlib*) +============================================ +An alternative mapping library written for matplotlib ``v1.2`` and beyond. +`Cartopy `_ builds on top of +matplotlib to provide object oriented map projection definitions and close +integration with Shapely for powerful yet easy-to-use vector data processing +tools. An example plot from the +`Cartopy gallery `_: + +.. image:: http://scitools.org.uk/cartopy/docs/latest/_images/hurricane_katrina_01_00.png + :height: 400px + + .. _toolkit_gtk: GTK Tools @@ -38,6 +56,7 @@ mpl_toolkits.gtktools provides some utilities for working with GTK. This toolkit ships with matplotlib, but requires `pygtk `_. + .. _toolkit_excel: Excel Tools @@ -47,10 +66,11 @@ mpl_toolkits.exceltools provides some utilities for working with Excel. This toolkit ships with matplotlib, but requires `xlwt `_ + .. _toolkit_natgrid: -Natgrid -======== +Natgrid (*Not distributed with matplotlib*) +=========================================== mpl_toolkits.natgrid is an interface to natgrid C library for gridding irregularly spaced data. This requires a separate installation of the @@ -58,27 +78,27 @@ natgrid toolkit from the sourceforge `download `_ page. + .. _toolkit_mplot3d: mplot3d =========== -mpl_toolkits.mplot3d provides some basic 3D plotting (scatter, surf, +:ref:`mpl_toolkits.mplot3d ` provides some basic 3D plotting (scatter, surf, line, mesh) tools. Not the fastest or feature complete 3D library out there, but ships with matplotlib and thus may be a lighter weight solution for some use cases. -See :ref:`toolkit_mplot3d-index` for more documentation and examples. +.. image:: /_images/contourf3d_demo21.png + .. _toolkit_axes_grid: AxesGrid ======== -The matplotlib AxesGrid toolkit is a collection of helper classes to +The matplotlib :ref:`AxesGrid ` toolkit is a collection of helper classes to ease displaying multiple images in matplotlib. The AxesGrid toolkit is distributed with matplotlib source. -.. image:: ../_static/demo_axes_grid.png - -See :ref:`toolkit_axesgrid-index` for documentations. +.. image:: /_static/demo_axes_grid.png diff --git a/examples/images_contours_and_fields/pcolormesh_levels.py b/examples/images_contours_and_fields/pcolormesh_levels.py new file mode 100644 index 000000000000..a042e9236d33 --- /dev/null +++ b/examples/images_contours_and_fields/pcolormesh_levels.py @@ -0,0 +1,53 @@ +""" +Shows how to combine Normalization and Colormap instances to draw +"levels" in pcolor, pcolormesh and imshow type plots in a similar +way to the levels keyword argument to contour/contourf. + +""" + +import matplotlib.pyplot as plt +from matplotlib.colors import BoundaryNorm +from matplotlib.ticker import MaxNLocator +import numpy as np + + +# make these smaller to increase the resolution +dx, dy = 0.05, 0.05 + +# generate 2 2d grids for the x & y bounds +y, x = np.mgrid[slice(1, 5 + dy, dy), + slice(1, 5 + dx, dx)] + +z = np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x) + +# x and y are bounds, so z should be the value *inside* those bounds. +# Therefore, remove the last value from the z array. +z = z[:-1, :-1] +levels = MaxNLocator(nbins=15).tick_values(z.min(), z.max()) + + +# pick the desired colormap, sensible levels, and define a normalization +# instance which takes data values and translates those into levels. +cmap = plt.get_cmap('PiYG') +norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) + +plt.subplot(2, 1, 1) +im = plt.pcolormesh(x, y, z, cmap=cmap, norm=norm) +plt.colorbar() +# set the limits of the plot to the limits of the data +plt.axis([x.min(), x.max(), y.min(), y.max()]) +plt.title('pcolormesh with levels') + + + +plt.subplot(2, 1, 2) +# contours are *point* based plots, so convert our bound into point +# centers +plt.contourf(x[:-1, :-1] + dx / 2., + y[:-1, :-1] + dy / 2., z, levels=levels, + cmap=cmap) +plt.colorbar() +plt.title('contourf with levels') + + +plt.show() \ No newline at end of file diff --git a/examples/pylab_examples/legend_demo.py b/examples/pylab_examples/legend_demo.py index 5151dfe203a0..34a4a56981f2 100644 --- a/examples/pylab_examples/legend_demo.py +++ b/examples/pylab_examples/legend_demo.py @@ -1,8 +1,9 @@ #!/usr/bin/env python # Thanks to Charles Twardy for this example # -#See http://matplotlib.sf.net/examples/legend_demo2.py for an example -#controlling which lines the legend uses and the order +#See http://matplotlib.org/examples/pylab_examples/legend_demo2.html +# for an example controlling which lines the legend uses and the order +# they are drawn in. import numpy as np import matplotlib.pyplot as plt diff --git a/examples/pylab_examples/legend_demo2.py b/examples/pylab_examples/legend_demo2.py index d8db01bc6f71..f1209eea920c 100644 --- a/examples/pylab_examples/legend_demo2.py +++ b/examples/pylab_examples/legend_demo2.py @@ -1,24 +1,23 @@ -#!/usr/bin/env python -# # Make a legend for specific lines. -from pylab import * +import matplotlib.pyplot as plt +import numpy as np -t1 = arange(0.0, 2.0, 0.1) -t2 = arange(0.0, 2.0, 0.01) + +t1 = np.arange(0.0, 2.0, 0.1) +t2 = np.arange(0.0, 2.0, 0.01) # note that plot returns a list of lines. The "l1, = plot" usage -# extracts the first element of the list inot l1 using tuple +# extracts the first element of the list into l1 using tuple # unpacking. So l1 is a Line2D instance, not a sequence of lines -l1, = plot(t2, exp(-t2)) -l2, l3 = plot(t2, sin(2*pi*t2), '--go', t1, log(1+t1), '.') -l4, = plot(t2, exp(-t2)*sin(2*pi*t2), 'rs-.') +l1, = plt.plot(t2, np.exp(-t2)) +l2, l3 = plt.plot(t2, np.sin(2 * np.pi * t2), '--go', t1, np.log(1 + t1), '.') +l4, = plt.plot(t2, np.exp(-t2) * np.sin(2 * np.pi * t2), 'rs-.') -legend( (l2, l4), ('oscillatory', 'damped'), 'upper right', shadow=True) -xlabel('time') -ylabel('volts') -title('Damped oscillation') -#axis([0,2,-1,1]) -show() +plt.legend( (l2, l4), ('oscillatory', 'damped'), 'upper right', shadow=True) +plt.xlabel('time') +plt.ylabel('volts') +plt.title('Damped oscillation') +plt.show() diff --git a/examples/pylab_examples/marker_path.py b/examples/pylab_examples/marker_path.py index f8e53c7ed3f0..ac18d1335133 100644 --- a/examples/pylab_examples/marker_path.py +++ b/examples/pylab_examples/marker_path.py @@ -5,9 +5,9 @@ star = mpath.Path.unit_regular_star(6) circle = mpath.Path.unit_circle() -# concatenate the star with an internal cutout of the circle -verts = np.concatenate([star.vertices, circle.vertices[::-1, ...]]) -codes = np.concatenate([star.codes, circle.codes]) +# concatenate the circle with an internal cutout of the star +verts = np.concatenate([circle.vertices, star.vertices[::-1, ...]]) +codes = np.concatenate([circle.codes, star.codes]) cut_star = mpath.Path(verts, codes) diff --git a/examples/pylab_examples/pcolor_demo.py b/examples/pylab_examples/pcolor_demo.py index 015b4a7f63d8..4a1639c03c42 100644 --- a/examples/pylab_examples/pcolor_demo.py +++ b/examples/pylab_examples/pcolor_demo.py @@ -1,28 +1,57 @@ -#!/usr/bin/env python """ -See pcolor_demo2 for an alternative way of generating pcolor plots -using imshow that is likely faster for large grids +Demonstrates similarities between pcolor, pcolormesh, imshow and pcolorfast +for drawing quadrilateral grids. + """ -from __future__ import division -from matplotlib.patches import Patch -from pylab import * +import matplotlib.pyplot as plt +import numpy as np -def func3(x,y): - return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) +# make these smaller to increase the resolution +dx, dy = 0.15, 0.05 +# generate 2 2d grids for the x & y bounds +y, x = np.mgrid[slice(-3, 3 + dy, dy), + slice(-3, 3 + dx, dx)] +z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) +# x and y are bounds, so z should be the value *inside* those bounds. +# Therefore, remove the last value from the z array. +z = z[:-1, :-1] +z_min, z_max = -np.abs(z).max(), np.abs(z).max() + + + +plt.subplot(2, 2, 1) +plt.pcolor(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max) +plt.title('pcolor') +# set the limits of the plot to the limits of the data +plt.axis([x.min(), x.max(), y.min(), y.max()]) +plt.colorbar() + + + +plt.subplot(2, 2, 2) +plt.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max) +plt.title('pcolormesh') +# set the limits of the plot to the limits of the data +plt.axis([x.min(), x.max(), y.min(), y.max()]) +plt.colorbar() + + + +plt.subplot(2, 2, 3) +plt.imshow(z, cmap='RdBu', vmin=z_min, vmax=z_max, + extent=[x.min(), x.max(), y.min(), y.max()], + interpolation='nearest', origin='lower') +plt.title('image (interp. nearest)') +plt.colorbar() -# make these smaller to increase the resolution -dx, dy = 0.05, 0.05 -x = arange(-3.0, 3.0001, dx) -y = arange(-3.0, 3.0001, dy) -X,Y = meshgrid(x, y) -Z = func3(X, Y) -pcolor(X, Y, Z, cmap=cm.RdBu, vmax=abs(Z).max(), vmin=-abs(Z).max()) -colorbar() -axis([-3,3,-3,3]) +ax = plt.subplot(2, 2, 4) +ax.pcolorfast(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max) +plt.title('pcolorfast') +plt.colorbar() -show() +plt.show() \ No newline at end of file diff --git a/examples/pylab_examples/pcolor_demo2.py b/examples/pylab_examples/pcolor_demo2.py deleted file mode 100644 index f5ae2c9fa3ea..000000000000 --- a/examples/pylab_examples/pcolor_demo2.py +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env python -""" -See pcolor_demo2 for a much faster way of generating pcolor plots -""" -from __future__ import division -from pylab import * - -def func3(x,y): - return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) - - -# make these smaller to increase the resolution -dx, dy = 0.05, 0.05 - -x = arange(-3.0, 3.0, dx) -y = arange(-3.0, 3.0, dy) -X,Y = meshgrid(x, y) - -Z = func3(X, Y) - - -ax = subplot(111) -im = imshow(Z, cmap=cm.RdBu, vmax=abs(Z).max(), vmin=-abs(Z).max()) -#im.set_interpolation('nearest') -#im.set_interpolation('bicubic') -im.set_interpolation('bilinear') -#ax.set_image_extent(-3, 3, -3, 3) - -show() - - diff --git a/examples/pylab_examples/pcolor_log.py b/examples/pylab_examples/pcolor_log.py index 4cdb9bf2a2bb..84f831bca17e 100644 --- a/examples/pylab_examples/pcolor_log.py +++ b/examples/pylab_examples/pcolor_log.py @@ -1,27 +1,25 @@ -from pylab import * - +import matplotlib.pyplot as plt from matplotlib.colors import LogNorm +import numpy as np +from matplotlib.mlab import bivariate_normal N = 100 -x = linspace(-3.0, 3.0, N) -y = linspace(-2.0, 2.0, N) - -X, Y = meshgrid(x, y) +X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] # A low hump with a spike coming out of the top right. # Needs to have z/colour axis on a log scale so we see both hump and spike. # linear scale only shows the spike. -Z1 = bivariate_normal(X, Y, 0.1, 0.2, 1.0, 1.0) + 0.1*bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) +Z1 = bivariate_normal(X, Y, 0.1, 0.2, 1.0, 1.0) + 0.1 * bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -subplot(2,1,1) -pcolor(X, Y, Z1, norm=LogNorm(vmin=Z1.min(), vmax=Z1.max()), cmap=cm.PuBu_r) -colorbar() +plt.subplot(2,1,1) +plt.pcolor(X, Y, Z1, norm=LogNorm(vmin=Z1.min(), vmax=Z1.max()), cmap='PuBu_r') +plt.colorbar() -subplot(2,1,2) -pcolor(X, Y, Z1, cmap=cm.PuBu_r) -colorbar() +plt.subplot(2,1,2) +plt.pcolor(X, Y, Z1, cmap='PuBu_r') +plt.colorbar() -show() +plt.show() diff --git a/examples/pylab_examples/pcolor_small.py b/examples/pylab_examples/pcolor_small.py index b957b463502f..3ecd09d8aeac 100644 --- a/examples/pylab_examples/pcolor_small.py +++ b/examples/pylab_examples/pcolor_small.py @@ -1,15 +1,14 @@ -#!/usr/bin/env python - -from pylab import * +import matplotlib.pyplot as plt +from numpy.random import rand Z = rand(6,10) -subplot(2,1,1) -c = pcolor(Z) -title('default: no edges') +plt.subplot(2,1,1) +c = plt.pcolor(Z) +plt.title('default: no edges') -subplot(2,1,2) -c = pcolor(Z, edgecolors='k', linewidths=4) -title('thick edges') +plt.subplot(2,1,2) +c = plt.pcolor(Z, edgecolors='k', linewidths=4) +plt.title('thick edges') -show() +plt.show() diff --git a/examples/pylab_examples/pie_demo2.py b/examples/pylab_examples/pie_demo2.py index 9e37ea513bcf..c3cd16fcb37e 100644 --- a/examples/pylab_examples/pie_demo2.py +++ b/examples/pylab_examples/pie_demo2.py @@ -1,19 +1,19 @@ """ Make a pie charts of varying size - see -http://matplotlib.sf.net/matplotlib.pylab.html#-pie for the docstring. +http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pie for the docstring. This example shows a basic pie charts with labels optional features, like autolabeling the percentage, offsetting a slice with "explode" and adding a shadow, in different sizes. """ -from pylab import * +import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec # Some data labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' -fracs = [15,30,45, 10] +fracs = [15, 30, 45, 10] explode=(0, 0.05, 0, 0) @@ -21,21 +21,19 @@ the_grid = GridSpec(2, 2) -figure(1, figsize=(6,6)) +plt.subplot(the_grid[0, 0], aspect=1) -subplot(the_grid[0, 0]) +plt.pie(fracs, labels=labels, autopct='%1.1f%%', shadow=True) -pie(fracs, labels=labels, autopct='%1.1f%%', shadow=True) +plt.subplot(the_grid[0, 1], aspect=1) -subplot(the_grid[0, 1]) +plt.pie(fracs, explode=explode, labels=labels, autopct='%.0f%%', shadow=True) -pie(fracs, explode=explode, labels=labels, autopct='%.0f%%', shadow=True) +plt.subplot(the_grid[1, 0], aspect=1) -subplot(the_grid[1, 0]) - -patches, texts, autotexts = pie(fracs, labels=labels, - autopct='%.0f%%', - shadow=True, radius=0.5) +patches, texts, autotexts = plt.pie(fracs, labels=labels, + autopct='%.0f%%', + shadow=True, radius=0.5) # Make the labels on the small plot easier to read. for t in texts: @@ -44,9 +42,9 @@ t.set_size('x-small') autotexts[0].set_color('y') -subplot(the_grid[1, 1]) +plt.subplot(the_grid[1, 1], aspect=1) -patches, texts, autotexts = pie(fracs, explode=explode, +patches, texts, autotexts = plt.pie(fracs, explode=explode, labels=labels, autopct='%.0f%%', shadow=False, radius=0.5) # Turn off shadow for tiny plot @@ -57,4 +55,4 @@ t.set_size('x-small') autotexts[0].set_color('y') -show() +plt.show() diff --git a/examples/pylab_examples/poormans_contour.py b/examples/pylab_examples/poormans_contour.py deleted file mode 100644 index 5a518e1a6963..000000000000 --- a/examples/pylab_examples/poormans_contour.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python -""" -Use a pcolor or imshow with a custom colormap to make a contour plot. - -Since this example was initially written, a proper contour routine was -added to matplotlib - see contour_demo.py and -http://matplotlib.sf.net/matplotlib.pylab.html#-contour. -""" - -from pylab import * - - -delta = 0.01 -x = arange(-3.0, 3.0, delta) -y = arange(-3.0, 3.0, delta) -X,Y = meshgrid(x, y) -Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -Z = Z2 - Z1 # difference of Gaussians - -cmap = cm.get_cmap('PiYG', 11) # 11 discrete colors - -im = imshow(Z, cmap=cmap, interpolation='bilinear', - vmax=abs(Z).max(), vmin=-abs(Z).max()) -axis('off') -colorbar() - -show() - diff --git a/examples/pylab_examples/tex_demo.py b/examples/pylab_examples/tex_demo.py index 64e10386e3b6..c9963d4b4506 100644 --- a/examples/pylab_examples/tex_demo.py +++ b/examples/pylab_examples/tex_demo.py @@ -1,33 +1,30 @@ -#!/usr/bin/env python """ You can use TeX to render all of your matplotlib text if the rc parameter text.usetex is set. This works currently on the agg and ps backends, and requires that you have tex and the other dependencies -described at http://matplotlib.sf.net/matplotlib.texmanager.html +described at http://matplotlib.org/users/usetex.html properly installed on your system. The first time you run a script you will see a lot of output from tex and associated tools. The next time, the run may be silent, as a lot of the information is cached in ~/.tex.cache """ -from matplotlib import rc -from numpy import arange, cos, pi -from matplotlib.pyplot import figure, axes, plot, xlabel, ylabel, title, \ - grid, savefig, show +import numpy as np +import matplotlib.pyplot as plt -rc('text', usetex=True) -rc('font', family='serif') -figure(1, figsize=(6,4)) -ax = axes([0.1, 0.1, 0.8, 0.7]) -t = arange(0.0, 1.0+0.01, 0.01) -s = cos(2*2*pi*t)+2 -plot(t, s) +plt.rc('text', usetex=True) +plt.rc('font', family='serif') +plt.figure(1, figsize=(6,4)) +ax = plt.axes([0.1, 0.1, 0.8, 0.7]) +t = np.linspace(0.0, 1.0, 100) +s = np.cos(4 * np.pi * t) + 2 +plt.plot(t, s) -xlabel(r'\textbf{time (s)}') -ylabel(r'\textit{voltage (mV)}',fontsize=16) -title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!", - fontsize=16, color='r') -grid(True) -savefig('tex_demo') -show() +plt.xlabel(r'\textbf{time (s)}') +plt.ylabel(r'\textit{voltage (mV)}',fontsize=16) +plt.title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty" + r"\frac{-e^{i\pi}}{2^n}$!", fontsize=16, color='r') +plt.grid(True) +plt.savefig('tex_demo') +plt.show() diff --git a/examples/pylab_examples/webapp_demo.py b/examples/pylab_examples/webapp_demo.py index fb8e3bd8f6a9..ad3702a62bf9 100644 --- a/examples/pylab_examples/webapp_demo.py +++ b/examples/pylab_examples/webapp_demo.py @@ -1,66 +1,59 @@ #!/usr/bin/env python # -*- noplot -*- -# This example shows how to use the agg backend directly to create -# images, which may be of use to web application developers who want -# full control over their code without using the pylab interface to -# manage figures, figure closing etc. -# -# The rc command is used to create per-script default figure -# customizations of the rc parameters; see -# http://matplotlib.sf.net/matplotlibrc . You may prefer to set the -# rc parameters in the rc file itself. Note that you can keep -# directory level default configurations by placing different rc files -# in the directory that the script runs in. -# -# I am making no effort here to make a figure that looks good -- -# rather I am just trying to show the various ways to use matplotlib -# to customize your figure using the matplotlib API +""" +This example shows how to use the agg backend directly to create +images, which may be of use to web application developers who want +full control over their code without using the pyplot interface to +manage figures, figure closing etc. + +.. note:: + + It is not necessary to avoid using the pyplot interface in order to + create figures without a graphical front-end - simply setting + the backend to "Agg" would be sufficient. + + +It is also worth noting that, because matplotlib can save figures to file-like +object, matplotlib can also be used inside a cgi-script *without* needing to +write a figure to disk. + +""" -import matplotlib -matplotlib.use('Agg') # force the antigrain backend -from matplotlib import rc from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure -from matplotlib.cbook import iterable import numpy as np + def make_fig(): """ - make a figure + Make a figure and save it to "webagg.png". - No need to close figures or clean up since the objects will be - destroyed when they go out of scope """ fig = Figure() - #ax = fig.add_subplot(111) # add a standard subplot - - # add an axes at left, bottom, width, height; by making the bottom - # at 0.3, we save some extra room for tick labels - ax = fig.add_axes([0.2, 0.3, 0.7, 0.6]) + ax = fig.add_subplot(1, 1, 1) - line, = ax.plot([1,2,3], 'ro--', markersize=12, markerfacecolor='g') + ax.plot([1, 2, 3], 'ro--', markersize=12, markerfacecolor='g') # make a translucent scatter collection x = np.random.rand(100) y = np.random.rand(100) - area = np.pi*(10 * np.random.rand(100))**2 # 0 to 10 point radiuses - c = ax.scatter(x,y,area) + area = np.pi * (10 * np.random.rand(100)) ** 2 # 0 to 10 point radiuses + c = ax.scatter(x, y, area) c.set_alpha(0.5) # add some text decoration ax.set_title('My first image') ax.set_ylabel('Some numbers') - ax.set_xticks( (.2,.4,.6,.8) ) + ax.set_xticks((.2, .4, .6, .8)) labels = ax.set_xticklabels(('Bill', 'Fred', 'Ted', 'Ed')) # To set object properties, you can either iterate over the # objects manually, or define you own set command, as in setapi # above. - for l in labels: - l.set_rotation(45) - l.set_fontsize(12) + for label in labels: + label.set_rotation(45) + label.set_fontsize(12) - canvas = FigureCanvasAgg(fig) - canvas.print_figure('webapp', dpi=150) + FigureCanvasAgg(fig).print_png('webapp.png', dpi=150) -make_fig() +make_fig() \ No newline at end of file diff --git a/lib/matplotlib/artist.py b/lib/matplotlib/artist.py index 1066b3b53949..3aae133152bc 100644 --- a/lib/matplotlib/artist.py +++ b/lib/matplotlib/artist.py @@ -752,10 +752,7 @@ def findobj(self, match=None, include_self=True): """ Find artist objects. - pyplot signature: - findobj(o=gcf(), match=None, include_self=True) - - Recursively find all :class:matplotlib.artist.Artist instances + Recursively find all :class:`~matplotlib.artist.Artist` instances contained in self. *match* can be @@ -770,9 +767,7 @@ def findobj(self, match=None, include_self=True): If *include_self* is True (default), include self in the list to be checked for a match. - .. plot:: mpl_examples/pylab_examples/findobj_demo.py """ - if match is None: # always return True def matchfunc(x): return True diff --git a/lib/matplotlib/axes.py b/lib/matplotlib/axes.py index b1f8e7fc9e06..edda4876bbdd 100644 --- a/lib/matplotlib/axes.py +++ b/lib/matplotlib/axes.py @@ -4726,9 +4726,10 @@ def legend(self, *args, **kwargs): columnspacing the spacing between columns ================ ==================================================== - .. Note:: Not all kinds of artist are supported by the legend command. - See LINK (FIXME) for details. + .. note:: + Not all kinds of artist are supported by the legend command. + See :ref:`plotting-guide-legend` for details. **Example:** @@ -5360,11 +5361,15 @@ def pie(self, x, explode=None, labels=None, colors=None, The radius of the pie, if *radius* is *None* it will be set to 1. The pie chart will probably look best if the figure and axes are - square. e.g.:: + square, or the Axes aspect is equal. e.g.:: figure(figsize=(8,8)) ax = axes([0.1, 0.1, 0.8, 0.8]) + or:: + + axes(aspect=1) + Return value: If *autopct* is *None*, return the tuple (*patches*, *texts*): @@ -7342,9 +7347,11 @@ def pcolor(self, *args, **kwargs): """ Create a pseudocolor plot of a 2-D array. - Note: pcolor can be very slow for large arrays; consider - using the similar but much faster - :func:`~matplotlib.pyplot.pcolormesh` instead. + .. note:: + + pcolor can be very slow for large arrays; consider + using the similar but much faster + :func:`~matplotlib.pyplot.pcolormesh` instead. Call signatures:: @@ -7467,14 +7474,16 @@ def pcolor(self, *args, **kwargs): %(PolyCollection)s - Note: the default *antialiaseds* is False if the default - *edgecolors*="none" is used. This eliminates artificial lines - at patch boundaries, and works regardless of the value of - alpha. If *edgecolors* is not "none", then the default - *antialiaseds* is taken from - rcParams['patch.antialiased'], which defaults to *True*. - Stroking the edges may be preferred if *alpha* is 1, but - will cause artifacts otherwise. + .. note:: + + The default *antialiaseds* is False if the default + *edgecolors*="none" is used. This eliminates artificial lines + at patch boundaries, and works regardless of the value of + alpha. If *edgecolors* is not "none", then the default + *antialiaseds* is taken from + rcParams['patch.antialiased'], which defaults to *True*. + Stroking the edges may be preferred if *alpha* is 1, but + will cause artifacts otherwise. .. seealso:: @@ -8861,10 +8870,12 @@ def specgram(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, - *Pxx* is an array of shape `(len(times), len(freqs))` of power - *im* is a :class:`~matplotlib.image.AxesImage` instance - Note: If *x* is real (i.e. non-complex), only the positive - spectrum is shown. If *x* is complex, both positive and - negative parts of the spectrum are shown. This can be - overridden using the *sides* keyword argument. + .. note:: + + If *x* is real (i.e. non-complex), only the positive + spectrum is shown. If *x* is complex, both positive and + negative parts of the spectrum are shown. This can be + overridden using the *sides* keyword argument. Also note that while the plot is in dB, the *Pxx* array returned is linear in power. diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py index 0566adc59195..30407c283d6b 100644 --- a/lib/matplotlib/cm.py +++ b/lib/matplotlib/cm.py @@ -102,12 +102,12 @@ def register_cmap(name=None, cmap=None, data=None, lut=None): register_cmap(name='choppy', data=choppydata, lut=128) - In the first case, *cmap* must be a :class:`colors.Colormap` + In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap` instance. The *name* is optional; if absent, the name will - be the :attr:`name` attribute of the *cmap*. + be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*. In the second case, the three arguments are passed to - the :class:`colors.LinearSegmentedColormap` initializer, + the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer, and the resulting colormap is registered. """ @@ -136,9 +136,9 @@ def get_cmap(name=None, lut=None): Get a colormap instance, defaulting to rc values if *name* is None. Colormaps added with :func:`register_cmap` take precedence over - builtin colormaps. + built-in colormaps. - If *name* is a :class:`colors.Colormap` instance, it will be + If *name* is a :class:`matplotlib.colors.Colormap` instance, it will be returned. If *lut* is not None it must be an integer giving the number of @@ -163,15 +163,22 @@ def get_cmap(name=None, lut=None): class ScalarMappable: """ - This is a mixin class to support scalar -> RGBA mapping. Handles - normalization and colormapping - """ + This is a mixin class to support scalar data to RGBA mapping. + The ScalarMappable makes use of data normalization before returning + RGBA colors from the given colormap. + """ def __init__(self, norm=None, cmap=None): - """ - *norm* is an instance of :class:`colors.Normalize` or one of - its subclasses, used to map luminance to 0-1. *cmap* is a - :mod:`cm` colormap instance, for example :data:`cm.jet` + r""" + + Parameters + ---------- + norm : :class:`matplotlib.colors.Normalize` instance + The normalizing object which scales data, typically into the + interval ``[0, 1]``. + cmap : str or :class:`~matplotlib.colors.Colormap` instance + The colormap used to map normalized data values to RGBA colors. + """ self.callbacksSM = cbook.CallbackRegistry() @@ -181,8 +188,10 @@ def __init__(self, norm=None, cmap=None): if norm is None: norm = colors.Normalize() - self._A = None + self._A = None; + #; The Normalization instance of this ScalarMappable. self.norm = norm + #; The Colormap instance of this ScalarMappable. self.cmap = get_cmap(cmap) self.colorbar = None self.update_dict = {'array': False} diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index 4f2110ca3a35..cc57a9489f9a 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -19,8 +19,8 @@ :class:`ColorConverter` class providing methods for converting single color specifications or sequences of them to *RGB* or *RGBA*. -Commands which take color arguments can use several formats to specify the -colors. For the basic builtin colors, you can use a single letter +Commands which take color arguments can use several formats to specify +the colors. For the basic built-in colors, you can use a single letter - b: blue - g: green @@ -477,19 +477,25 @@ def makeMappingArray(N, data, gamma=1.0): class Colormap(object): - """Base class for all scalar to rgb mappings + """ + Baseclass for all scalar to RGBA mappings. - Important methods: + Typically Colormap instances are used to convert data values (floats) from + the interval ``[0, 1]`` to the RGBA color that the respective Colormap + represents. For scaling of data into the ``[0, 1]`` interval see + :class:`matplotlib.colors.Normalize`. It is worth noting that + :class:`matplotlib.cm.ScalarMappable` subclasses make heavy use of this + ``data->normalize->map-to-color`` processing chain. - * :meth:`set_bad` - * :meth:`set_under` - * :meth:`set_over` """ def __init__(self, name, N=256): - """ - Public class attributes: - :attr:`N` : number of rgb quantization levels - :attr:`name` : name of colormap + r""" + Parameters + ---------- + name : str + The name of the colormap. + N : int + The number of rgb quantization levels. """ self.name = name @@ -502,20 +508,30 @@ def __init__(self, name, N=256): self._i_bad = N + 2 self._isinit = False - # FIXME FIXME FIXME bytes is a *keyword* in python def __call__(self, X, alpha=None, bytes=False): """ - *X* is either a scalar or an array (of any dimension). - If scalar, a tuple of rgba values is returned, otherwise - an array with the new shape = oldshape+(4,). If the X-values - are integers, then they are used as indices into the array. - If they are floating point, then they must be in the - interval (0.0, 1.0). - Alpha must be a scalar between 0 and 1, or None. - If bytes is False, the rgba values will be floats on a - 0-1 scale; if True, they will be uint8, 0-255. - """ + Parameters + ---------- + X : scalar, ndarray + The data value(s) to convert to RGBA. + For floats, X should be in the interval ``[0.0, 1.0]`` to + return the RGBA values ``X*100`` percent along the Colormap line. + For integers, X should be in the interval ``[0, Colormap.N)`` to + return RGBA values *indexed* from the Colormap with index ``X``. + alpha : float, None + Alpha must be a scalar between 0 and 1, or None. + bytes : bool + If False (default), the returned RGBA values will be floats in the + interval ``[0, 1]`` otherwise they will be uint8s in the interval + ``[0, 255]``. + + Returns + ------- + Tuple of RGBA values if X is scalar, othewise an array of + RGBA values with a shape of ``X.shape + (4, )``. + """ + # See class docstring for arg/kwarg documentation. if not self._isinit: self._init() mask_bad = None @@ -690,8 +706,8 @@ def __init__(self, name, segmentdata, N=256, gamma=1.0): :func:`makeMappingArray` For information about making a mapping array. """ - self.monochrome = False # True only if all colors in map are - # identical; needed for contouring. + # True only if all colors in map are identical; needed for contouring. + self.monochrome = False Colormap.__init__(self, name, N) self._segmentdata = segmentdata self._gamma = gamma @@ -762,7 +778,7 @@ def __init__(self, colors, name='from_list', N=None): *colors* a list of matplotlib color specifications, - or an equivalent Nx3 or Nx4 floating point array + or an equivalent Nx3 or Nx4 floating point array (*N* rgb or rgba values) *name* a string to identify the colormap @@ -815,7 +831,9 @@ def _init(self): class Normalize(object): """ - Normalize a given value to the 0-1 range + A class which, when called, can normalize data into + the ``[0, 1]`` interval. + """ def __init__(self, vmin=None, vmax=None, clip=False): """ diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index aea04004ab39..fc1a3a9267c5 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -102,10 +102,10 @@ def _backend_selection(): @docstring.copy_dedent(Artist.findobj) -def findobj(o=None, match=None): +def findobj(o=None, match=None, include_self=True): if o is None: o = gcf() - return o.findobj(match) + return o.findobj(match, include_self=include_self) def switch_backend(newbackend): @@ -1253,7 +1253,9 @@ def title(s, *args, **kwargs): def axis(*v, **kwargs): """ - Set or get the axis properties.:: + Convenience method to get or set axis properties. + + Calling with no arguments:: >>> axis() @@ -1754,8 +1756,8 @@ def colors(): def colormaps(): """ Matplotlib provides a number of colormaps, and others can be added using - :func:`register_cmap`. This function documents the built-in colormaps, - and will also return a list of all registered colormaps if called. + :func:`~matplotlib.cm.register_cmap`. This function documents the built-in + colormaps, and will also return a list of all registered colormaps if called. You can set the colormap for an image, pcolor, scatter, etc, using a keyword argument:: @@ -2086,15 +2088,16 @@ def clim(vmin=None, vmax=None): def set_cmap(cmap): - ''' + """ Set the default colormap. Applies to the current image if any. See help(colormaps) for more information. - *cmap* must be a :class:`colors.Colormap` instance, or + *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or the name of a registered colormap. - See :func:`register_cmap` and :func:`get_cmap`. - ''' + See :func:`matplotlib.cm.register_cmap` and + :func:`matplotlib.cm.get_cmap`. + """ cmap = cm.get_cmap(cmap) rc('image', cmap=cmap.name) diff --git a/lib/matplotlib/sankey.py b/lib/matplotlib/sankey.py index 349f0decfb02..fbfe1880df22 100755 --- a/lib/matplotlib/sankey.py +++ b/lib/matplotlib/sankey.py @@ -297,7 +297,7 @@ def _add_output(self, path, angle, flow, length): """ Append an output to a path and return its tip and label locations. - Note: *flow* is negative for an output. + .. note:: *flow* is negative for an output. """ if angle is None: return [0, 0], [0, 0] diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index ea6c15a3edce..6ec3a26f0dc0 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -910,7 +910,8 @@ def view_limits(self, vmin, vmax): """ select a scale for the range from vmin to vmax - Normally This will be overridden. + Normally this method is overridden by subclasses to + change locator behaviour. """ return mtransforms.nonsingular(vmin, vmax)