diff --git a/doc/conf.py b/doc/conf.py index 445ced4c048b..b2bc7118323a 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -82,6 +82,29 @@ 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'), + ('statistics', 'Statistical plots'), + ('images_contours_and_fields', 'Images, contours, and fields'), + ('pie_and_polar_charts', 'Pie and polar charts'), + ('color', 'Color'), + ('text_labels_and_annotations', 'Text, labels, and annotations'), + ('ticks_and_spines', 'Ticks and spines'), + ('subplots_axes_and_figures', 'Subplots, axes, and figures'), + ('specialty_plots', 'Specialty plots'), + ('showcase', 'Showcase'), + ('api', 'API'), + ('pylab_examples', 'pylab examples'), + ('mplot3d', 'mplot3d toolkit'), + ('axes_grid', 'axes_grid toolkit'), + ('units', 'units'), + ('widgets', 'widgets'), + ) + + # Github extension github_project_url = "http://github.com/matplotlib/matplotlib/" diff --git a/doc/sphinxext/gen_gallery.py b/doc/sphinxext/gen_gallery.py index 609829262933..51e9a7b82ed5 100644 --- a/doc/sphinxext/gen_gallery.py +++ b/doc/sphinxext/gen_gallery.py @@ -1,37 +1,62 @@ # -*- coding: UTF-8 -*- +import os +import re +import glob +import warnings + +import sphinx.errors + +import matplotlib.image as image + + +exclude_example_sections = ['units'] +multiimage = re.compile('(.*?)(_\d\d){1,2}') # generate a thumbnail gallery of examples -template = """\ -{%% extends "layout.html" %%} -{%% set title = "Thumbnail gallery" %%} +gallery_template = """\ +{{% extends "layout.html" %}} +{{% set title = "Thumbnail gallery" %}} -{%% block body %%} +{{% block body %}}

Click on any image to see full size image and source code


-
  • Gallery +
  • Gallery +
  • -%s -{%% endblock %%} +{gallery} + +{{% endblock %}} """ -import os, glob, re, sys, warnings -import matplotlib.image as image +header_template = """\ +
    +

    + {title} +

    """ + +link_template = """\ +{basename} +""" + +toc_template = """\ +
  • {title}
  • """ -multiimage = re.compile('(.*?)(_\d\d){1,2}') def make_thumbnail(args): image.thumbnail(args[0], args[1], 0.3) + def out_of_date(original, derived): return (not os.path.exists(derived) or os.stat(derived).st_mtime < os.stat(original).st_mtime) + def gen_gallery(app, doctree): if app.builder.name != 'html': return @@ -39,6 +64,11 @@ def gen_gallery(app, doctree): outdir = app.builder.outdir rootdir = 'plot_directive/mpl_examples' + example_sections = list(app.builder.config.mpl_example_sections) + for i, (subdir, title) in enumerate(example_sections): + if subdir in exclude_example_sections: + example_sections.pop(i) + # images we want to skip for the gallery because they are an unusual # size that doesn't layout well in a table, or because they may be # redundant with other images or uninteresting @@ -53,21 +83,9 @@ def gen_gallery(app, doctree): rows = [] toc_rows = [] - link_template = """\ - %s - """ - - header_template = """
    \ -

    %s

    """ - - toc_template = """\ -
  • %s
  • """ - - dirs = ('api', 'pylab_examples', 'mplot3d', 'widgets', 'axes_grid' ) - - for subdir in dirs : - rows.append(header_template % (subdir, subdir, subdir)) - toc_rows.append(toc_template % (subdir, subdir)) + for subdir, title in example_sections: + rows.append(header_template.format(title=title, section=subdir)) + toc_rows.append(toc_template.format(title=title, section=subdir)) origdir = os.path.join('build', rootdir, subdir) thumbdir = os.path.join(outdir, rootdir, subdir, 'thumbnails') @@ -99,13 +117,12 @@ def gen_gallery(app, doctree): data.append((subdir, basename, os.path.join(rootdir, subdir, 'thumbnails', filename))) - - - for (subdir, basename, thumbfile) in data: if thumbfile is not None: link = 'examples/%s/%s.html'%(subdir, basename) - rows.append(link_template%(link, thumbfile, basename)) + rows.append(link_template.format(link=link, + thumb=thumbfile, + basename=basename)) if len(data) == 0: warnings.warn("No thumbnails were found in %s" % subdir) @@ -113,19 +130,21 @@ def gen_gallery(app, doctree): # Close out the
    opened up at the top of this loop rows.append("
    ") - content = template % ('\n'.join(toc_rows), - '\n'.join(rows)) + content = gallery_template.format(toc='\n'.join(toc_rows), + gallery='\n'.join(rows)) # Only write out the file if the contents have actually changed. # Otherwise, this triggers a full rebuild of the docs - gallery_path = os.path.join(app.builder.srcdir, '_templates', 'gallery.html') + gallery_path = os.path.join(app.builder.srcdir, + '_templates', 'gallery.html') if os.path.exists(gallery_path): fh = file(gallery_path, 'r') regenerate = fh.read() != content fh.close() else: regenerate = True + if regenerate: fh = file(gallery_path, 'w') fh.write(content) @@ -136,5 +155,11 @@ def gen_gallery(app, doctree): length=len(thumbnails)): image.thumbnail(key, thumbnails[key], 0.3) + def setup(app): app.connect('env-updated', gen_gallery) + + try: # multiple plugins may use mpl_example_sections + app.add_config_value('mpl_example_sections', [], True) + except sphinx.errors.ExtensionError: + pass # mpl_example_sections already defined diff --git a/doc/sphinxext/gen_rst.py b/doc/sphinxext/gen_rst.py index e8135bf4abdb..1ea5c2286120 100644 --- a/doc/sphinxext/gen_rst.py +++ b/doc/sphinxext/gen_rst.py @@ -2,12 +2,17 @@ generate the rst files for the examples by iterating over the pylab examples """ from __future__ import print_function -import os, glob import os import re import sys -fileList = [] + +import sphinx.errors + + +exclude_example_sections = ['widgets'] +noplot_regex = re.compile(r"#\s*-\*-\s*noplot\s*-\*-") + def out_of_date(original, derived): """ @@ -21,14 +26,18 @@ def out_of_date(original, derived): return (not os.path.exists(derived) or os.stat(derived).st_mtime < os.stat(original).st_mtime) -noplot_regex = re.compile(r"#\s*-\*-\s*noplot\s*-\*-") - def generate_example_rst(app): rootdir = os.path.join(app.builder.srcdir, 'mpl_examples') exampledir = os.path.join(app.builder.srcdir, 'examples') if not os.path.exists(exampledir): os.makedirs(exampledir) + example_sections = list(app.builder.config.mpl_example_sections) + for i, (subdir, title) in enumerate(example_sections): + if subdir in exclude_example_sections: + example_sections.pop(i) + example_subdirs, titles = zip(*example_sections) + datad = {} for root, subFolders, files in os.walk(rootdir): for fname in files: @@ -114,13 +123,8 @@ def generate_example_rst(app): fhsubdirIndex.write(' %s <%s>\n'%(os.path.basename(basename),rstfile)) - do_plot = (subdir in ('api', - 'pylab_examples', - 'units', - 'mplot3d', - 'axes_grid', - ) and - not noplot_regex.search(contents)) + do_plot = (subdir in example_subdirs + and not noplot_regex.search(contents)) if not do_plot: fhstatic = file(outputfile, 'w') fhstatic.write(contents) @@ -157,3 +161,8 @@ def generate_example_rst(app): def setup(app): app.connect('builder-inited', generate_example_rst) + + try: # multiple plugins may use mpl_example_sections + app.add_config_value('mpl_example_sections', [], True) + except sphinx.errors.ExtensionError: + pass # mpl_example_sections already defined diff --git a/doc/users/image_tutorial.rst b/doc/users/image_tutorial.rst index 1ccfb5a8a395..bcc21132c450 100644 --- a/doc/users/image_tutorial.rst +++ b/doc/users/image_tutorial.rst @@ -228,7 +228,7 @@ object: There are many other colormap schemes available. See the `list and images of the colormaps -`_. +`_. .. _`Color Bars`: diff --git a/doc/users/screenshots.rst b/doc/users/screenshots.rst index 86f6c2687c30..e56f31d656ee 100644 --- a/doc/users/screenshots.rst +++ b/doc/users/screenshots.rst @@ -22,7 +22,7 @@ Subplot demo Multiple regular axes (numrows by numcolumns) are created with the :func:`~matplotlib.pyplot.subplot` command. -.. plot:: mpl_examples/pylab_examples/subplot_demo.py +.. plot:: mpl_examples/subplots_axes_and_figures/subplot_demo.py .. _screenshots_histogram_demo: @@ -32,7 +32,7 @@ Histograms The :func:`~matplotlib.pyplot.hist` command automatically generates histograms and will return the bin counts or probabilities -.. plot:: mpl_examples/pylab_examples/histogram_demo.py +.. plot:: mpl_examples/statistics/histogram_demo_features.py .. _screenshots_path_demo: @@ -43,7 +43,7 @@ Path demo You can add arbitrary paths in matplotlib as of release 0.98. See the :mod:`matplotlib.path`. -.. plot:: mpl_examples/api/path_patch_demo.py +.. plot:: mpl_examples/shapes_and_collections/path_patch_demo.py .. _screenshots_mplot3d_surface: @@ -103,7 +103,7 @@ or more wedges out from the center of the pie, and a shadow effect. Take a close look at the attached code that produced this figure; nine lines of code. -.. plot:: mpl_examples/pylab_examples/pie_demo.py +.. plot:: mpl_examples/pie_and_polar_charts/pie_demo_features.py .. _screenshots_table_demo: @@ -153,7 +153,7 @@ The :func:`~matplotlib.pyplot.fill` command lets you plot filled polygons. Thanks to Andrew Straw for providing this function -.. plot:: mpl_examples/pylab_examples/fill_demo.py +.. plot:: mpl_examples/lines_bars_and_markers/fill_demo.py .. _screenshots_date_demo: diff --git a/doc/users/whats_new.rst b/doc/users/whats_new.rst index 5ba32223fae4..e54dc4f1af7d 100644 --- a/doc/users/whats_new.rst +++ b/doc/users/whats_new.rst @@ -195,7 +195,7 @@ In addition to simply plotting the streamlines of the vector field, line widths of the streamlines to a separate parameter, such as the speed or local intensity of the vector field. -.. plot:: mpl_examples/pylab_examples/streamplot_demo.py +.. plot:: mpl_examples/images_contours_and_fields/streamplot_demo_features.py New hist functionality @@ -442,7 +442,7 @@ Other improvements * Pim Schellart added a new colormap called "cubehelix". Sameer Grover also added a colormap called "coolwarm". See it and all - other colormaps :ref:`here `. + other colormaps :ref:`here `. * Many bug fixes and documentation improvements. diff --git a/examples/api/artist_demo.py b/examples/api/artist_demo.py deleted file mode 100644 index 35dc77759c63..000000000000 --- a/examples/api/artist_demo.py +++ /dev/null @@ -1,119 +0,0 @@ -""" -Show examples of matplotlib artists -http://matplotlib.org/api/artist_api.html - -Several examples of standard matplotlib graphics primitives (artists) -are drawn using matplotlib API. Full list of artists and the -documentation is available at -http://matplotlib.org/api/artist_api.html - -Copyright (c) 2010, Bartosz Telenczuk - -License: This work is licensed under the BSD. A copy should be -included with this source code, and is also available at -http://www.opensource.org/licenses/bsd-license.php -""" - - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib -from matplotlib.collections import PatchCollection -import matplotlib.path as mpath -import matplotlib.patches as mpatches -import matplotlib.lines as mlines - -font = "sans-serif" -fig = plt.figure(figsize=(5,5)) -ax = plt.axes([0,0,1,1]) - -# create 3x3 grid to plot the artists -pos = np.mgrid[0.2:0.8:3j, 0.2:0.8:3j].reshape(2, -1) - -patches = [] - -# add a circle -art = mpatches.Circle(pos[:,0], 0.1,ec="none") -patches.append(art) -plt.text(pos[0,0], pos[1,0]-0.15, "Circle", ha="center", - family=font, size=14) - -# add a rectangle -art = mpatches.Rectangle(pos[:,1] - np.array([0.025, 0.05]), 0.05, 0.1, - ec="none") -patches.append(art) -plt.text(pos[0,1], pos[1,1]-0.15, "Rectangle", ha="center", - family=font, size=14) - -# add a wedge -wedge = mpatches.Wedge(pos[:,2], 0.1, 30, 270, ec="none") -patches.append(wedge) -plt.text(pos[0,2], pos[1,2]-0.15, "Wedge", ha="center", - family=font, size=14) - -# add a Polygon -polygon = mpatches.RegularPolygon(pos[:,3], 5, 0.1) -patches.append(polygon) -plt.text(pos[0,3], pos[1,3]-0.15, "Polygon", ha="center", - family=font, size=14) - -#add an ellipse -ellipse = mpatches.Ellipse(pos[:,4], 0.2, 0.1) -patches.append(ellipse) -plt.text(pos[0,4], pos[1,4]-0.15, "Ellipse", ha="center", - family=font, size=14) - -#add an arrow -arrow = mpatches.Arrow(pos[0,5]-0.05, pos[1,5]-0.05, 0.1, 0.1, width=0.1) -patches.append(arrow) -plt.text(pos[0,5], pos[1,5]-0.15, "Arrow", ha="center", - family=font, size=14) - -# add a path patch -Path = mpath.Path -verts = np.array([ - (0.158, -0.257), - (0.035, -0.11), - (-0.175, 0.20), - (0.0375, 0.20), - (0.085, 0.115), - (0.22, 0.32), - (0.3, 0.005), - (0.20, -0.05), - (0.158, -0.257), - ]) -verts = verts-verts.mean(0) -codes = [Path.MOVETO, - Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.LINETO, - Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CLOSEPOLY] - -path = mpath.Path(verts/2.5+pos[:,6], codes) -patch = mpatches.PathPatch(path) -patches.append(patch) -plt.text(pos[0,6], pos[1,6]-0.15, "PathPatch", ha="center", - family=font, size=14) - -# add a fancy box -fancybox = mpatches.FancyBboxPatch( - pos[:,7]-np.array([0.025, 0.05]), 0.05, 0.1, - boxstyle=mpatches.BoxStyle("Round", pad=0.02)) -patches.append(fancybox) -plt.text(pos[0,7], pos[1,7]-0.15, "FancyBoxPatch", ha="center", - family=font, size=14) - -# add a line -x,y = np.array([[-0.06, 0.0, 0.1], [0.05,-0.05, 0.05]]) -line = mlines.Line2D(x+pos[0,8], y+pos[1,8], lw=5., - alpha=0.4) -plt.text(pos[0,8], pos[1,8]-0.15, "Line2D", ha="center", - family=font, size=14) - -colors = 100*np.random.rand(len(patches)) -collection = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4) -collection.set_array(np.array(colors)) -ax.add_collection(collection) -ax.add_line(line) -ax.set_xticks([]) -ax.set_yticks([]) - -plt.show() diff --git a/examples/api/clippath_demo.py b/examples/api/clippath_demo.py deleted file mode 100644 index 7a07467524ba..000000000000 --- a/examples/api/clippath_demo.py +++ /dev/null @@ -1,19 +0,0 @@ -""" -Clipping to arbitrary patches and paths -""" -import numpy as np -import matplotlib.pyplot as plt -import matplotlib.patches as patches - - -fig = plt.figure() -ax = fig.add_subplot(111, frameon=False, xticks=[], yticks=[]) - -im = ax.imshow(np.random.rand(10,10)) - -patch = patches.Circle((300,300), radius=100) -im.set_clip_path(patch) - -plt.show() - - diff --git a/examples/api/color_cycle.py b/examples/api/color_cycle.py deleted file mode 100644 index 6b2abe873cd2..000000000000 --- a/examples/api/color_cycle.py +++ /dev/null @@ -1,28 +0,0 @@ -""" -Illustrate the API for changing the cycle of colors used -when plotting multiple lines on a single Axes. -""" - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib as mpl - -yy = np.arange(24) -yy.shape = 6,4 - -mpl.rc('lines', linewidth=4) - -fig = plt.figure() -mpl.rcParams['axes.color_cycle'] = ['r', 'g', 'b', 'c'] -ax = fig.add_subplot(2,1,1) -ax.plot(yy) -ax.set_title('Changed default color cycle to rgbc') - -ax = fig.add_subplot(2,1,2) -ax.set_color_cycle(['c', 'm', 'y', 'k']) -ax.plot(yy) -ax.set_title('This axes only, cycle is cmyk') - -plt.show() - - diff --git a/examples/api/hinton_demo.py b/examples/api/hinton_demo.py deleted file mode 100644 index 700e13c1bb65..000000000000 --- a/examples/api/hinton_demo.py +++ /dev/null @@ -1,60 +0,0 @@ -#Initial idea from David Warde-Farley on the SciPy Cookbook -import numpy as np -import matplotlib.pyplot as plt -from matplotlib.patches import Rectangle -from matplotlib.ticker import NullLocator -#from matplotlib.collections import RegularPolyCollection -#from matplotlib.colors import BoundaryNorm, ListedColormap - -def hinton(W, maxWeight=None, ax=None): - """ - Draws a Hinton diagram for visualizing a weight matrix. - """ - if not ax: - fig = plt.figure() - ax = fig.add_subplot(1, 1, 1) - - if not maxWeight: - maxWeight = 2**np.ceil(np.log(np.abs(W).max())/np.log(2)) - - ax.patch.set_facecolor('gray') - ax.set_aspect('equal', 'box') - ax.xaxis.set_major_locator(NullLocator()) - ax.yaxis.set_major_locator(NullLocator()) - - for (x,y),w in np.ndenumerate(W): - if w > 0: color = 'white' - else: color = 'black' - size = np.sqrt(np.abs(w)) - rect = Rectangle([x - size / 2, y - size / 2], size, size, - facecolor=color, edgecolor=color) - ax.add_patch(rect) - ax.autoscale_view() - - # Reverse the yaxis limits - ax.set_ylim(*ax.get_ylim()[::-1]) - -## Potential way using polygon collections that just has an issue with -## easily getting the squares scaled by the data. - -# height,width = W.shape -# x = np.arange(width) -# y = np.arange(height) -# X,Y = np.meshgrid(x, y) -# xy = np.array([X.flatten(),Y.flatten()]).T -# scaled_data = W.flatten() / maxWeight -# cmap = ListedColormap(['black', 'white']) -# norm = BoundaryNorm([-1., 0., 1.], cmap.N) - -# rect_col = RegularPolyCollection(4, rotation=np.pi/4, -# sizes=np.abs(scaled_data) * 72 / ax.figure.get_dpi(), offsets=xy, -# transOffset=ax.transData, norm=norm, cmap=cmap, edgecolor='none') -# ax.add_collection(rect_col) -# rect_col.set_array(scaled_data) -# ax.autoscale_view() - -if __name__ == '__main__': - hinton(np.random.rand(20, 20) - 0.5) - plt.title('Hinton Example') - plt.show() - diff --git a/examples/api/histogram_demo.py b/examples/api/histogram_demo.py deleted file mode 100644 index 11c4b0adaba1..000000000000 --- a/examples/api/histogram_demo.py +++ /dev/null @@ -1,34 +0,0 @@ -""" -Make a histogram of normally distributed random numbers and plot the -analytic PDF over it -""" -import numpy as np -import matplotlib.pyplot as plt -import matplotlib.mlab as mlab - -mu, sigma = 100, 15 -x = mu + sigma * np.random.randn(10000) - -fig = plt.figure() -ax = fig.add_subplot(111) - -# the histogram of the data -n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75) - -# hist uses np.histogram under the hood to create 'n' and 'bins'. -# np.histogram returns the bin edges, so there will be 50 probability -# density values in n, 51 bin edges in bins and 50 patches. To get -# everything lined up, we'll compute the bin centers -bincenters = 0.5*(bins[1:]+bins[:-1]) -# add a 'best fit' line for the normal PDF -y = mlab.normpdf( bincenters, mu, sigma) -l = ax.plot(bincenters, y, 'r--', linewidth=1) - -ax.set_xlabel('Smarts') -ax.set_ylabel('Probability') -#ax.set_title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$') -ax.set_xlim(40, 160) -ax.set_ylim(0, 0.03) -ax.grid(True) - -plt.show() diff --git a/examples/color/color_cycle_demo.py b/examples/color/color_cycle_demo.py new file mode 100644 index 000000000000..b453de4c1aed --- /dev/null +++ b/examples/color/color_cycle_demo.py @@ -0,0 +1,34 @@ +""" +Demo of custom color-cycle settings to control colors for multi-line plots. + +This example demonstrates two different APIs: + + 1. Setting the default rc-parameter specifying the color cycle. + This affects all subsequent plots. + 2. Setting the color cycle for a specific axes. This only affects a single + axes. +""" +import numpy as np +import matplotlib.pyplot as plt + +x = np.linspace(0, 2 * np.pi) +offsets = np.linspace(0, 2*np.pi, 4, endpoint=False) +# Create array with shifted-sine curve along each column +yy = np.transpose([np.sin(x + phi) for phi in offsets]) + +plt.rc('lines', linewidth=4) +fig, (ax0, ax1) = plt.subplots(nrows=2) + +plt.rc('axes', color_cycle=['r', 'g', 'b', 'y']) +ax0.plot(yy) +ax0.set_title('Set default color cycle to rgby') + +ax1.set_color_cycle(['c', 'm', 'y', 'k']) +ax1.plot(yy) +ax1.set_title('Set axes color cycle to cmyk') + +# Tweak spacing between subplots to prevent labels from overlapping +plt.subplots_adjust(hspace=0.3) +plt.show() + + diff --git a/examples/color/colormaps_reference.py b/examples/color/colormaps_reference.py new file mode 100644 index 000000000000..1c433794e4e1 --- /dev/null +++ b/examples/color/colormaps_reference.py @@ -0,0 +1,79 @@ +""" +Reference for colormaps included with Matplotlib. + +This reference example shows all colormaps included with Matplotlib. Note that +any colormap listed here can be reversed by appending "_r" (e.g., "pink_r"). +These colormaps are divided into the following categories: + +Sequential: + These colormaps are approximately monochromatic colormaps varying smoothly + between two color tones---usually from low saturation (e.g. white) to high + saturation (e.g. a bright blue). Sequential colormaps are ideal for + representing most scientific data since they show a clear progression from + low-to-high values. + +Diverging: + These colormaps have a median value (usually light in color) and vary + smoothly to two different color tones at high and low values. Diverging + colormaps are ideal when your data has a median value that is significant + (e.g. 0, such that positive and negative values are represented by + different colors of the colormap). + +Qualitative: + These colormaps vary rapidly in color. Qualitative colormaps are useful for + choosing a set of discrete colors. For example:: + + color_list = plt.cm.Set3(np.linspace(0, 1, 12)) + + gives a list of RGB colors that are good for plotting a series of lines on + a dark background. + +Miscellaneous: + Colormaps that don't fit into the categories above. + +""" +import numpy as np +import matplotlib.pyplot as plt + + +cmaps = [('Sequential', ['binary', 'Blues', 'BuGn', 'BuPu', 'gist_yarg', + 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', + 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu', + 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']), + ('Sequential (2)', ['afmhot', 'autumn', 'bone', 'cool', 'copper', + 'gist_gray', 'gist_heat', 'gray', 'hot', 'pink', + 'spring', 'summer', 'winter']), + ('Diverging', ['BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr', + 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'seismic']), + ('Qualitative', ['Accent', 'Dark2', 'hsv', 'Paired', 'Pastel1', + 'Pastel2', 'Set1', 'Set2', 'Set3', 'spectral']), + ('Miscellaneous', ['gist_earth', 'gist_ncar', 'gist_rainbow', + 'gist_stern', 'jet', 'brg', 'CMRmap', 'cubehelix', + 'gnuplot', 'gnuplot2', 'ocean', 'rainbow', + 'terrain', 'flag', 'prism'])] + + +nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps) +gradient = np.linspace(0, 1, 256) +gradient = np.vstack((gradient, gradient)) + +def plot_color_gradients(cmap_category, cmap_list): + fig, axes = plt.subplots(nrows=nrows) + fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99) + axes[0].set_title(cmap_category + ' colormaps', fontsize=14) + + for ax, name in zip(axes, cmap_list): + ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name)) + pos = list(ax.get_position().bounds) + x_text = pos[0] - 0.01 + y_text = pos[1] + pos[3]/2. + fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10) + + # Turn off *all* ticks & spines, not just the ones with colormaps. + for ax in axes: + ax.set_axis_off() + +for cmap_category, cmap_list in cmaps: + plot_color_gradients(cmap_category, cmap_list) + +plt.show() diff --git a/examples/images_contours_and_fields/image_demo.py b/examples/images_contours_and_fields/image_demo.py new file mode 100644 index 000000000000..6b73458153e4 --- /dev/null +++ b/examples/images_contours_and_fields/image_demo.py @@ -0,0 +1,14 @@ +""" +Simple demo of the imshow function. +""" +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.cbook as cbook + +image_file = cbook.get_sample_data('lena.npy') +image = np.load(image_file) + +plt.imshow(image) +plt.axis('off') # clear x- and y-axes +plt.show() + diff --git a/examples/images_contours_and_fields/image_demo_clip_path.py b/examples/images_contours_and_fields/image_demo_clip_path.py new file mode 100644 index 000000000000..ac61d4f0b8cd --- /dev/null +++ b/examples/images_contours_and_fields/image_demo_clip_path.py @@ -0,0 +1,19 @@ +""" +Demo of image that's been clipped by a circular patch. +""" +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.patches as patches +import matplotlib.cbook as cbook + + +image_file = cbook.get_sample_data('lena.npy') +image = np.load(image_file) + +fig, ax = plt.subplots() +im = ax.imshow(image) +patch = patches.Circle((130, 130), radius=100, transform=ax.transData) +im.set_clip_path(patch) + +plt.axis('off') +plt.show() diff --git a/examples/pylab_examples/streamplot_demo.py b/examples/images_contours_and_fields/streamplot_demo_features.py similarity index 57% rename from examples/pylab_examples/streamplot_demo.py rename to examples/images_contours_and_fields/streamplot_demo_features.py index f67e3515c908..2cc10bf877e8 100644 --- a/examples/pylab_examples/streamplot_demo.py +++ b/examples/images_contours_and_fields/streamplot_demo_features.py @@ -1,3 +1,13 @@ +""" +Demo of the `streamplot` function. + +A streamplot, or streamline plot, is used to display 2D vector fields. This +example shows a few features of the stream plot function: + + * Varying the color along a streamline. + * Varying the density of streamlines. + * Varying the line width along a stream line. +""" import numpy as np import matplotlib.pyplot as plt diff --git a/examples/pylab_examples/streamplot_with_mask.py b/examples/images_contours_and_fields/streamplot_demo_masking.py similarity index 55% rename from examples/pylab_examples/streamplot_with_mask.py rename to examples/images_contours_and_fields/streamplot_demo_masking.py index c989b0060620..ce0ac99b9410 100644 --- a/examples/pylab_examples/streamplot_with_mask.py +++ b/examples/images_contours_and_fields/streamplot_demo_masking.py @@ -1,6 +1,8 @@ """ -Demonstrate the use of the `streamplot` function using a masked array -and NaN values. +Demo of the streamplot function with masking. + +This example shows how streamlines created by the streamplot function skips +masked regions and NaN values. """ import numpy as np import matplotlib.pyplot as plt @@ -17,7 +19,9 @@ U[:20, :20] = np.nan plt.streamplot(X, Y, U, V, color='r') -plt.imshow(~mask, extent=(-w, w, -w, w), alpha=0.5, interpolation='nearest') + +plt.imshow(~mask, extent=(-w, w, -w, w), alpha=0.5, + interpolation='nearest', cmap=plt.cm.gray) plt.show() diff --git a/examples/lines_bars_and_markers/barh_demo.py b/examples/lines_bars_and_markers/barh_demo.py new file mode 100644 index 000000000000..b0087acb1eb3 --- /dev/null +++ b/examples/lines_bars_and_markers/barh_demo.py @@ -0,0 +1,21 @@ +""" +Simple demo of a horizontal bar chart. +""" +import matplotlib.pyplot as plt; plt.rcdefaults() +from mpltools import style; style.use('gallery') +import numpy as np +import matplotlib.pyplot as plt + + +# Example data +people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') +y_pos = np.arange(len(people)) +performance = 3 + 10 * np.random.rand(len(people)) +error = np.random.rand(len(people)) + +plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4) +plt.yticks(y_pos, people) +plt.xlabel('Performance') +plt.title('How fast do you want to go today?') + +plt.show() diff --git a/examples/lines_bars_and_markers/fill_demo.py b/examples/lines_bars_and_markers/fill_demo.py new file mode 100644 index 000000000000..fff88f2e503a --- /dev/null +++ b/examples/lines_bars_and_markers/fill_demo.py @@ -0,0 +1,13 @@ +""" +Simple demo of the fill function. +""" +import numpy as np +import matplotlib.pyplot as plt + + +x = np.linspace(0, 1) +y = np.sin(4 * np.pi * x) * np.exp(-5 * x) + +plt.fill(x, y, 'r') +plt.grid(True) +plt.show() diff --git a/examples/lines_bars_and_markers/fill_demo_features.py b/examples/lines_bars_and_markers/fill_demo_features.py new file mode 100644 index 000000000000..230f1631c0ad --- /dev/null +++ b/examples/lines_bars_and_markers/fill_demo_features.py @@ -0,0 +1,17 @@ +""" +Demo of the fill function with a few features. + +In addition to the basic fill plot, this demo shows a few optional features: + + * Multiple curves with a single command. + * Setting the fill color. + * Setting the opacity (alpha value). +""" +import numpy as np +import matplotlib.pyplot as plt + +x = np.linspace(0, 2 * np.pi, 100) +y1 = np.sin(x) +y2 = np.sin(3 * x) +plt.fill(x, y1, 'b', x, y2, 'r', alpha=0.3) +plt.show() diff --git a/examples/lines_bars_and_markers/line_demo_dash_control.py b/examples/lines_bars_and_markers/line_demo_dash_control.py new file mode 100644 index 000000000000..b884c7e28675 --- /dev/null +++ b/examples/lines_bars_and_markers/line_demo_dash_control.py @@ -0,0 +1,17 @@ +""" +Demo of a simple plot with a custom dashed line. + +A Line object's ``set_dashes`` method allows you to specify dashes with +a series of on/off lengths (in points). +""" +import numpy as np +import matplotlib.pyplot as plt + + +x = np.linspace(0, 10) +line, = plt.plot(x, np.sin(x), '--', linewidth=2) + +dashes = [10, 5, 100, 5] # 10 points on, 5 off, 100 on, 5 off +line.set_dashes(dashes) + +plt.show() diff --git a/examples/pie_and_polar_charts/pie_demo_features.py b/examples/pie_and_polar_charts/pie_demo_features.py new file mode 100644 index 000000000000..763d38461aee --- /dev/null +++ b/examples/pie_and_polar_charts/pie_demo_features.py @@ -0,0 +1,32 @@ +""" +Demo of a basic pie chart plus a few additional features. + +In addition to the basic pie chart, this demo shows a few optional features: + + * slice labels + * auto-labeling the percentage + * offsetting a slice with "explode" + * drop-shadow + * custom start angle + +Note about the custom start angle: + +The default ``startangle`` is 0, which would start the "Frogs" slice on the +positive x-axis. This example sets ``startangle = 90`` such that everything is +rotated counter-clockwise by 90 degrees, and the frog slice starts on the +positive y-axis. +""" +import matplotlib.pyplot as plt + + +# The slices will be ordered and plotted counter-clockwise. +labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' +sizes = [15, 30, 45, 10] +colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] +explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs') + +plt.pie(sizes, explode=explode, labels=labels, colors=colors, + autopct='%1.1f%%', shadow=True, startangle=90) +# Set aspect ratio to be equal so that pie is drawn as a circle. +plt.axis('equal') +plt.show() diff --git a/examples/pie_and_polar_charts/polar_bar_demo.py b/examples/pie_and_polar_charts/polar_bar_demo.py new file mode 100644 index 000000000000..459dd6f958f1 --- /dev/null +++ b/examples/pie_and_polar_charts/polar_bar_demo.py @@ -0,0 +1,21 @@ +""" +Demo of bar plot on a polar axis. +""" +import numpy as np +import matplotlib.pyplot as plt + + +N = 20 +theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False) +radii = 10 * np.random.rand(N) +width = np.pi / 4 * np.random.rand(N) + +ax = plt.subplot(111, polar=True) +bars = ax.bar(theta, radii, width=width, bottom=0.0) + +# Use custom colors and opacity +for r, bar in zip(radii, bars): + bar.set_facecolor(plt.cm.jet(r / 10.)) + bar.set_alpha(0.5) + +plt.show() diff --git a/examples/pie_and_polar_charts/polar_scatter_demo.py b/examples/pie_and_polar_charts/polar_scatter_demo.py new file mode 100644 index 000000000000..90eea4e2b3a8 --- /dev/null +++ b/examples/pie_and_polar_charts/polar_scatter_demo.py @@ -0,0 +1,21 @@ +""" +Demo of scatter plot on a polar axis. + +Size increases radially in this example and color increases with angle (just to +verify the symbols are being scattered correctly). +""" +import numpy as np +import matplotlib.pyplot as plt + + +N = 150 +r = 2 * np.random.rand(N) +theta = 2 * np.pi * np.random.rand(N) +area = 200 * r**2 * np.random.rand(N) +colors = theta + +ax = plt.subplot(111, polar=True) +c = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.hsv) +c.set_alpha(0.75) + +plt.show() diff --git a/examples/pylab_examples/barh_demo.py b/examples/pylab_examples/barh_demo.py deleted file mode 100644 index 0daef263fd37..000000000000 --- a/examples/pylab_examples/barh_demo.py +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env python -# make a horizontal bar chart - -from pylab import * -val = 3+10*rand(5) # the bar lengths -pos = arange(5)+.5 # the bar centers on the y axis - -figure(1) -barh(pos,val, align='center') -yticks(pos, ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')) -xlabel('Performance') -title('How fast do you want to go today?') -grid(True) - -figure(2) -barh(pos,val, xerr=rand(5), ecolor='r', align='center') -yticks(pos, ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')) -xlabel('Performance') - -show() diff --git a/examples/pylab_examples/dash_control.py b/examples/pylab_examples/dash_control.py deleted file mode 100644 index 1100882b8873..000000000000 --- a/examples/pylab_examples/dash_control.py +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env python - -""" -You can precisely specify dashes with an on/off ink rect sequence in -points. -""" -from pylab import * - -dashes = [5,2,10,5] # 5 points on, 2 off, 3 on, 1 off - -l, = plot(arange(20), '--') -l.set_dashes(dashes) - -show() diff --git a/examples/pylab_examples/errorbar_demo.py b/examples/pylab_examples/errorbar_demo.py deleted file mode 100644 index dbe6bdb2cd64..000000000000 --- a/examples/pylab_examples/errorbar_demo.py +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env python -import numpy as np -import matplotlib.pyplot as plt - -# example data -x = np.arange(0.1, 4, 0.5) -y = np.exp(-x) - -# example variable error bar values -yerr = 0.1 + 0.2*np.sqrt(x) -xerr = 0.1 + yerr - -# First illustrate basic pyplot interface, using defaults where possible. -plt.figure() -plt.errorbar(x, y, xerr=0.2, yerr=0.4) -plt.title("Simplest errorbars, 0.2 in x, 0.4 in y") - -# Now switch to a more OO interface to exercise more features. -fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True) -ax = axs[0,0] -ax.errorbar(x, y, yerr=yerr, fmt='o') -ax.set_title('Vert. symmetric') - -# With 4 subplots, reduce the number of axis ticks to avoid crowding. -ax.locator_params(nbins=4) - -ax = axs[0,1] -ax.errorbar(x, y, xerr=xerr, fmt='o') -ax.set_title('Hor. symmetric') - -ax = axs[1,0] -ax.errorbar(x, y, yerr=[yerr, 2*yerr], xerr=[xerr, 2*xerr], fmt='--o') -ax.set_title('H, V asymmetric') - -ax = axs[1,1] -ax.set_yscale('log') -# Here we have to be careful to keep all y values positive: -ylower = np.maximum(1e-2, y - yerr) -yerr_lower = y - ylower - -ax.errorbar(x, y, yerr=[yerr_lower, 2*yerr], xerr=xerr, - fmt='o', ecolor='g', capthick=2) -ax.set_title('Mixed sym., log y') - -fig.suptitle('Variable errorbars') - -plt.show() - diff --git a/examples/pylab_examples/fill_demo.py b/examples/pylab_examples/fill_demo.py deleted file mode 100644 index 1cfded4d60cb..000000000000 --- a/examples/pylab_examples/fill_demo.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python -import numpy as np -import matplotlib.pyplot as plt - -t = np.arange(0.0, 1.01, 0.01) -s = np.sin(2*2*np.pi*t) - -plt.fill(t, s*np.exp(-5*t), 'r') -plt.grid(True) -plt.show() diff --git a/examples/pylab_examples/fill_demo2.py b/examples/pylab_examples/fill_demo2.py deleted file mode 100644 index 77b86d79017e..000000000000 --- a/examples/pylab_examples/fill_demo2.py +++ /dev/null @@ -1,10 +0,0 @@ -from matplotlib.pyplot import figure, show -from numpy import arange, sin, pi - -fig = figure() -ax = fig.add_subplot(111) -t = arange(0.0,3.01,0.01) -s = sin(2*pi*t) -c = sin(4*pi*t) -ax.fill(t, s, 'b', t, c, 'g', alpha=0.2) -show() diff --git a/examples/pylab_examples/histogram_demo.py b/examples/pylab_examples/histogram_demo.py deleted file mode 100644 index 00919f78ea67..000000000000 --- a/examples/pylab_examples/histogram_demo.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env python -import numpy as np -import matplotlib.mlab as mlab -import matplotlib.pyplot as plt - -mu, sigma = 100, 15 -x = mu + sigma*np.random.randn(10000) - -# the histogram of the data -n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75) - -# add a 'best fit' line -y = mlab.normpdf( bins, mu, sigma) -l = plt.plot(bins, y, 'r--', linewidth=1) - -plt.xlabel('Smarts') -plt.ylabel('Probability') -plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$') -plt.axis([40, 160, 0, 0.03]) -plt.grid(True) - -plt.show() diff --git a/examples/pylab_examples/image_demo3.py b/examples/pylab_examples/image_demo3.py deleted file mode 100644 index a469b48cf79d..000000000000 --- a/examples/pylab_examples/image_demo3.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env python -from pylab import * -try: - from PIL import Image -except ImportError: - raise SystemExit("PIL must be installed to run this example") - -import matplotlib.cbook as cbook - -datafile = cbook.get_sample_data('lena.jpg') -lena = Image.open(datafile) -dpi = rcParams['figure.dpi'] -figsize = lena.size[0]/dpi, lena.size[1]/dpi - -figure(figsize=figsize) -ax = axes([0,0,1,1], frameon=False) -ax.set_axis_off() -im = imshow(lena) - -show() - diff --git a/examples/pylab_examples/integral_demo.py b/examples/pylab_examples/integral_demo.py deleted file mode 100644 index 436482ce189a..000000000000 --- a/examples/pylab_examples/integral_demo.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python - -# implement the example graphs/integral from pyx -from pylab import * -from matplotlib.patches import Polygon - -def func(x): - return (x-3)*(x-5)*(x-7)+85 - -ax = subplot(111) - -a, b = 2, 9 # integral area -x = arange(0, 10, 0.01) -y = func(x) -plot(x, y, linewidth=1) - -# make the shaded region -ix = arange(a, b, 0.01) -iy = func(ix) -verts = [(a,0)] + list(zip(ix,iy)) + [(b,0)] -poly = Polygon(verts, facecolor='0.8', edgecolor='k') -ax.add_patch(poly) - -text(0.5 * (a + b), 30, - r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment='center', - fontsize=20) - -axis([0,10, 0, 180]) -figtext(0.9, 0.05, 'x') -figtext(0.1, 0.9, 'y') -ax.set_xticks((a,b)) -ax.set_xticklabels(('a','b')) -ax.set_yticks([]) -show() diff --git a/examples/pylab_examples/pie_demo.py b/examples/pylab_examples/pie_demo.py deleted file mode 100644 index 0b0e9a3b8a7c..000000000000 --- a/examples/pylab_examples/pie_demo.py +++ /dev/null @@ -1,30 +0,0 @@ -""" -Make a pie chart - see -http://matplotlib.sf.net/matplotlib.pylab.html#-pie for the docstring. - -This example shows a basic pie chart with labels optional features, -like autolabeling the percentage, offsetting a slice with "explode", -adding a shadow, and changing the starting angle. - -""" -from pylab import * - -# make a square figure and axes -figure(1, figsize=(6,6)) -ax = axes([0.1, 0.1, 0.8, 0.8]) - -# The slices will be ordered and plotted counter-clockwise. -labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' -fracs = [15, 30, 45, 10] -explode=(0, 0.05, 0, 0) - -pie(fracs, explode=explode, labels=labels, - autopct='%1.1f%%', shadow=True, startangle=90) - # The default startangle is 0, which would start - # the Frogs slice on the x-axis. With startangle=90, - # everything is rotated counter-clockwise by 90 degrees, - # so the plotting starts on the positive y-axis. - -title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5}) - -show() diff --git a/examples/pylab_examples/polar_bar.py b/examples/pylab_examples/polar_bar.py deleted file mode 100644 index 14d8d7de0b43..000000000000 --- a/examples/pylab_examples/polar_bar.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env python - -import numpy as np -import matplotlib.cm as cm -from matplotlib.pyplot import figure, show, rc - - -# force square figure and square axes looks better for polar, IMO -fig = figure(figsize=(8,8)) -ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) - -N = 20 -theta = np.arange(0.0, 2*np.pi, 2*np.pi/N) -radii = 10*np.random.rand(N) -width = np.pi/4*np.random.rand(N) -bars = ax.bar(theta, radii, width=width, bottom=0.0) -for r,bar in zip(radii, bars): - bar.set_facecolor( cm.jet(r/10.)) - bar.set_alpha(0.5) - -show() diff --git a/examples/pylab_examples/polar_scatter.py b/examples/pylab_examples/polar_scatter.py deleted file mode 100644 index 196f6e847290..000000000000 --- a/examples/pylab_examples/polar_scatter.py +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env python -# a polar scatter plot; size increases radially in this example and -# color increases with angle (just to verify the symbols are being -# scattered correctly). In a real example, this would be wasting -# dimensionality of the plot -from pylab import * - -N = 150 -r = 2*rand(N) -theta = 2*pi*rand(N) -area = 200*r**2*rand(N) -colors = theta -ax = subplot(111, polar=True) -c = scatter(theta, r, c=colors, s=area, cmap=cm.hsv) -c.set_alpha(0.75) - -show() diff --git a/examples/pylab_examples/scatter_demo.py b/examples/pylab_examples/scatter_demo.py deleted file mode 100644 index 3adf52b1dd1f..000000000000 --- a/examples/pylab_examples/scatter_demo.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python -from pylab import * - -N = 30 -x = 0.9*rand(N) -y = 0.9*rand(N) -area = pi*(10 * rand(N))**2 # 0 to 10 point radiuses -scatter(x,y,s=area, marker='^', c='r') - -show() diff --git a/examples/pylab_examples/show_colormaps.py b/examples/pylab_examples/show_colormaps.py deleted file mode 100644 index 0146a93c07ed..000000000000 --- a/examples/pylab_examples/show_colormaps.py +++ /dev/null @@ -1,25 +0,0 @@ -# This example comes from the Cookbook on www.scipy.org. According to the -# history, Andrew Straw did the conversion from an old page, but it is -# unclear who the original author is. -import numpy as np -import matplotlib.pyplot as plt - -a = np.linspace(0, 1, 256).reshape(1,-1) -a = np.vstack((a,a)) - -# Get a list of the colormaps in matplotlib. Ignore the ones that end with -# '_r' because these are simply reversed versions of ones that don't end -# with '_r' -maps = sorted(m for m in plt.cm.datad if not m.endswith("_r")) -nmaps = len(maps) + 1 - -fig = plt.figure(figsize=(5,10)) -fig.subplots_adjust(top=0.99, bottom=0.01, left=0.2, right=0.99) -for i,m in enumerate(maps): - ax = plt.subplot(nmaps, 1, i+1) - plt.axis("off") - plt.imshow(a, aspect='auto', cmap=plt.get_cmap(m), origin='lower') - pos = list(ax.get_position().bounds) - fig.text(pos[0] - 0.01, pos[1], m, fontsize=10, horizontalalignment='right') - -plt.show() diff --git a/examples/pylab_examples/spine_placement_demo.py b/examples/pylab_examples/spine_placement_demo.py index 2e80f68f7601..42f925371c43 100644 --- a/examples/pylab_examples/spine_placement_demo.py +++ b/examples/pylab_examples/spine_placement_demo.py @@ -1,31 +1,6 @@ -import sys -import matplotlib.pyplot as plt import numpy as np -from matplotlib.pyplot import show - -fig = plt.figure() -x = np.linspace(0,2*np.pi,100) -y = 2*np.sin(x) -ax = fig.add_subplot(1,2,1) -ax.set_title('dropped spines') -ax.plot(x,y) -for loc, spine in ax.spines.items(): - if loc in ['left','bottom']: - spine.set_position(('outward',10)) # outward by 10 points - elif loc in ['right','top']: - spine.set_color('none') # don't draw spine - else: - raise ValueError('unknown spine location: %s'%loc) - -# turn off ticks where there is no spine -ax.xaxis.set_ticks_position('bottom') -ax.yaxis.set_ticks_position('left') - -ax = fig.add_subplot(1,2,2,sharex=ax) -ax.plot(x,y) -ax.set_title('normal spines') +import matplotlib.pyplot as plt -# ---------------------------------------------------- fig = plt.figure() x = np.linspace(-np.pi,np.pi,100) @@ -122,40 +97,4 @@ def adjust_spines(ax,spines): ax.plot(x,y) adjust_spines(ax,['bottom']) -# ---------------------------------------------------- - -fig = plt.figure() - -x = np.linspace(0,2*np.pi,50) -y = np.sin(x) -y2 = y + 0.1*np.random.normal( size=x.shape ) - -# plot data -ax = fig.add_subplot(1,1,1) -line1,=ax.plot(x,y,'--') -line2,=ax.plot(x,y2,'bo') - -# adjust the spines -adjust_spines(ax,['left','bottom']) - -# set ticks and tick labels -# x -ax.set_xlim((0,2*np.pi)) -ax.set_xticks([0,np.pi,2*np.pi]) -if sys.version_info[0] < 3: - pichr = unichr(0x03C0) -else: - pichr = chr(0x03C0) -ax.set_xticklabels(['0',pichr,'2 '+pichr]) - -# y -ax.set_yticks([-1,0,1]) - -# disable clipping of data points by axes range -for artist in (line1,line2): - artist.set_clip_on(False) - -# adjust spine to be within ticks -ax.spines['left'].set_bounds( -1, 1 ) - -show() +plt.show() diff --git a/examples/pylab_examples/subplot_demo.py b/examples/pylab_examples/subplot_demo.py index 509b7f1db2b8..6e9598eab725 100644 --- a/examples/pylab_examples/subplot_demo.py +++ b/examples/pylab_examples/subplot_demo.py @@ -1,25 +1,24 @@ -#!/usr/bin/env python -from pylab import * +""" +Simple demo with multiple subplots. +""" +import numpy as np +import matplotlib.pyplot as plt -def f(t): - s1 = cos(2*pi*t) - e1 = exp(-t) - return multiply(s1,e1) -t1 = arange(0.0, 5.0, 0.1) -t2 = arange(0.0, 5.0, 0.02) -t3 = arange(0.0, 2.0, 0.01) +x1 = np.linspace(0.0, 5.0) +x2 = np.linspace(0.0, 2.0) -subplot(211) -l = plot(t1, f(t1), 'bo', t2, f(t2), 'k--', markerfacecolor='green') -grid(True) -title('A tale of 2 subplots') -ylabel('Damped oscillation') +y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) +y2 = np.cos(2 * np.pi * x2) -subplot(212) -plot(t3, cos(2*pi*t3), 'r.') -grid(True) -xlabel('time (s)') -ylabel('Undamped') -show() +plt.subplot(2, 1, 1) +plt.plot(x1, y1, 'ko-') +plt.title('A tale of 2 subplots') +plt.ylabel('Damped oscillation') +plt.subplot(2, 1, 2) +plt.plot(x2, y2, 'r.-') +plt.xlabel('time (s)') +plt.ylabel('Undamped') + +plt.show() diff --git a/examples/pylab_examples/text_themes.py b/examples/pylab_examples/text_themes.py deleted file mode 100644 index 43dfc39064f8..000000000000 --- a/examples/pylab_examples/text_themes.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python -from pylab import * - -font = {'family' : 'serif', - 'color' : 'r', - 'weight' : 'normal', - 'size' : 12, - } - -def f(t): - s1 = cos(2*pi*t) - e1 = exp(-t) - return multiply(s1,e1) - -t1 = arange(0.0, 5.0, 0.1) -t2 = arange(0.0, 5.0, 0.02) - -plot(t1, f(t1), 'bo', t2, f(t2), 'k') -title('Damped exponential decay', font, size='large', color='r') -text(2, 0.65, r'$\cos(2 \pi t) \exp(-t)$', color='k') -xlabel('time (s)', font, style='italic') -ylabel('voltage (mV)', font) - -show() diff --git a/examples/pylab_examples/unicode_demo.py b/examples/pylab_examples/unicode_demo.py deleted file mode 100755 index bba623482a26..000000000000 --- a/examples/pylab_examples/unicode_demo.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -from __future__ import unicode_literals - -import pylab - -pylab.plot([1, 2, 4]) -pylab.title('Développés et fabriqués') -pylab.xlabel("réactivité nous permettent d'être sélectionnés et adoptés") -pylab.ylabel('André was here!') -pylab.text( 0.5, 2.5, 'Institut für Festkörperphysik', rotation=45) -pylab.text( 1, 1.5, 'AVA (check kerning)') - -pylab.show() diff --git a/examples/pylab_examples/vertical_ticklabels.py b/examples/pylab_examples/vertical_ticklabels.py deleted file mode 100644 index 2416a785bfc1..000000000000 --- a/examples/pylab_examples/vertical_ticklabels.py +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env python -from pylab import * - -plot([1,2,3,4], [1,4,9,16]) -locs, labels = xticks([1,2,3,4], ['Frogs', 'Hogs', 'Bogs', 'Slogs']) -setp(labels, 'rotation', 'vertical') -show() diff --git a/examples/shapes_and_collections/artist_reference.py b/examples/shapes_and_collections/artist_reference.py new file mode 100644 index 000000000000..a9016de58949 --- /dev/null +++ b/examples/shapes_and_collections/artist_reference.py @@ -0,0 +1,104 @@ +""" +Reference for matplotlib artists + +This example displays several of matplotlib's graphics primitives (artists) +drawn using matplotlib API. A full list of artists and the documentation is +available at http://matplotlib.org/api/artist_api.html. + +Copyright (c) 2010, Bartosz Telenczuk +BSD License +""" +import matplotlib.pyplot as plt; plt.rcdefaults() +from mpltools import style; style.use('gallery') + +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.path as mpath +import matplotlib.lines as mlines +import matplotlib.patches as mpatches +from matplotlib.collections import PatchCollection + + +def label(xy, text): + y = xy[1] - 0.15 # shift y-value for label so that it's below the artist + plt.text(xy[0], y, text, ha="center", family='sans-serif', size=14) + + +fig, ax = plt.subplots() +# create 3x3 grid to plot the artists +grid = np.mgrid[0.2:0.8:3j, 0.2:0.8:3j].reshape(2, -1).T + +patches = [] + +# add a circle +circle = mpatches.Circle(grid[0], 0.1,ec="none") +patches.append(circle) +label(grid[0], "Circle") + +# add a rectangle +rect = mpatches.Rectangle(grid[1] - [0.025, 0.05], 0.05, 0.1, ec="none") +patches.append(rect) +label(grid[1], "Rectangle") + +# add a wedge +wedge = mpatches.Wedge(grid[2], 0.1, 30, 270, ec="none") +patches.append(wedge) +label(grid[2], "Wedge") + +# add a Polygon +polygon = mpatches.RegularPolygon(grid[3], 5, 0.1) +patches.append(polygon) +label(grid[3], "Polygon") + +#add an ellipse +ellipse = mpatches.Ellipse(grid[4], 0.2, 0.1) +patches.append(ellipse) +label(grid[4], "Ellipse") + +#add an arrow +arrow = mpatches.Arrow(grid[5, 0]-0.05, grid[5, 1]-0.05, 0.1, 0.1, width=0.1) +patches.append(arrow) +label(grid[5], "Arrow") + +# add a path patch +Path = mpath.Path +path_data = [ + (Path.MOVETO, [ 0.018, -0.11 ]), + (Path.CURVE4, [-0.031, -0.051]), + (Path.CURVE4, [-0.115, 0.073]), + (Path.CURVE4, [-0.03 , 0.073]), + (Path.LINETO, [-0.011, 0.039]), + (Path.CURVE4, [ 0.043, 0.121]), + (Path.CURVE4, [ 0.075, -0.005]), + (Path.CURVE4, [ 0.035, -0.027]), + (Path.CLOSEPOLY, [0.018, -0.11]) + ] +codes, verts = zip(*path_data) +path = mpath.Path(verts + grid[6], codes) +patch = mpatches.PathPatch(path) +patches.append(patch) +label(grid[6], "PathPatch") + +# add a fancy box +fancybox = mpatches.FancyBboxPatch( + grid[7] - [0.025, 0.05], 0.05, 0.1, + boxstyle=mpatches.BoxStyle("Round", pad=0.02)) +patches.append(fancybox) +label(grid[7], "FancyBoxPatch") + +# add a line +x,y = np.array([[-0.06, 0.0, 0.1], [0.05, -0.05, 0.05]]) +line = mlines.Line2D(x + grid[8, 0], y + grid[8, 1], lw=5., alpha=0.3) +label(grid[8], "Line2D") + +colors = np.linspace(0, 1, len(patches)) +collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3) +collection.set_array(np.array(colors)) +ax.add_collection(collection) +ax.add_line(line) + +plt.subplots_adjust(left=0, right=1, bottom=0, top=1) +plt.axis('equal') +plt.axis('off') + +plt.show() diff --git a/examples/api/path_patch_demo.py b/examples/shapes_and_collections/path_patch_demo.py similarity index 68% rename from examples/api/path_patch_demo.py rename to examples/shapes_and_collections/path_patch_demo.py index d28fa2c37015..fb0c8aa47592 100644 --- a/examples/api/path_patch_demo.py +++ b/examples/shapes_and_collections/path_patch_demo.py @@ -1,14 +1,15 @@ -import numpy as np +""" +Demo of a PathPatch object. +""" import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt -Path = mpath.Path -fig = plt.figure() -ax = fig.add_subplot(111) +fig, ax = plt.subplots() -pathdata = [ +Path = mpath.Path +path_data = [ (Path.MOVETO, (1.58, -2.57)), (Path.CURVE4, (0.35, -1.1)), (Path.CURVE4, (-1.75, 2.0)), @@ -19,18 +20,15 @@ (Path.CURVE4, (2.0, -0.5)), (Path.CLOSEPOLY, (1.58, -2.57)), ] - -codes, verts = zip(*pathdata) +codes, verts = zip(*path_data) path = mpath.Path(verts, codes) -patch = mpatches.PathPatch(path, facecolor='red', edgecolor='yellow', alpha=0.5) +patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5) ax.add_patch(patch) +# plot control points and connecting lines x, y = zip(*path.vertices) line, = ax.plot(x, y, 'go-') + ax.grid() -ax.set_xlim(-3,4) -ax.set_ylim(-3,4) -ax.set_title('spline paths') +ax.axis('equal') plt.show() - - diff --git a/examples/shapes_and_collections/scatter_demo.py b/examples/shapes_and_collections/scatter_demo.py new file mode 100644 index 000000000000..317b647ce94c --- /dev/null +++ b/examples/shapes_and_collections/scatter_demo.py @@ -0,0 +1,14 @@ +""" +Simple demo of a scatter plot. +""" +import numpy as np +import matplotlib.pyplot as plt + + +N = 50 +x = np.random.rand(N) +y = np.random.rand(N) +area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses + +plt.scatter(x, y, s=area, alpha=0.5) +plt.show() diff --git a/examples/showcase/integral_demo.py b/examples/showcase/integral_demo.py new file mode 100644 index 000000000000..d55f551fab80 --- /dev/null +++ b/examples/showcase/integral_demo.py @@ -0,0 +1,51 @@ +""" +Plot demonstrating the integral as the area under a curve. + +Although this is a simple example, it demonstrates some important tweaks: + + * A simple line plot with custom color and line width. + * A shaded region created using a Polygon patch. + * A text label with mathtext rendering. + * figtext calls to label the x- and y-axes. + * Use of axis spines to hide the top and right spines. + * Custom tick placement and labels. +""" +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Polygon + + +def func(x): + return (x - 3) * (x - 5) * (x - 7) + 85 + + +a, b = 2, 9 # integral limits +x = np.linspace(0, 10) +y = func(x) + +fig, ax = plt.subplots() +plt.plot(x, y, 'r', linewidth=2) +plt.ylim(ymin=0) + +# Make the shaded region +ix = np.linspace(a, b) +iy = func(ix) +verts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)] +poly = Polygon(verts, facecolor='0.9', edgecolor='0.5') +ax.add_patch(poly) + +plt.text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$", + horizontalalignment='center', fontsize=20) + +plt.figtext(0.9, 0.05, '$x$') +plt.figtext(0.1, 0.9, '$y$') + +ax.spines['right'].set_visible(False) +ax.spines['top'].set_visible(False) +ax.xaxis.set_ticks_position('bottom') + +ax.set_xticks((a, b)) +ax.set_xticklabels(('$a$', '$b$')) +ax.set_yticks([]) + +plt.show() diff --git a/examples/specialty_plots/hinton_demo.py b/examples/specialty_plots/hinton_demo.py new file mode 100644 index 000000000000..201b321283c1 --- /dev/null +++ b/examples/specialty_plots/hinton_demo.py @@ -0,0 +1,41 @@ +""" +Demo of a function to create Hinton diagrams. + +Hinton diagrams are useful for visualizing the values of a 2D array (e.g. +a weight matrix): Positive and negative values are represented by white and +black squares, respectively, and the size of each square represents the +magnitude of each value. + +Initial idea from David Warde-Farley on the SciPy Cookbook +""" +import numpy as np +import matplotlib.pyplot as plt + + +def hinton(matrix, max_weight=None, ax=None): + """Draw Hinton diagram for visualizing a weight matrix.""" + ax = ax if ax is not None else plt.gca() + + if not max_weight: + max_weight = 2**np.ceil(np.log(np.abs(matrix).max())/np.log(2)) + + ax.patch.set_facecolor('gray') + ax.set_aspect('equal', 'box') + ax.xaxis.set_major_locator(plt.NullLocator()) + ax.yaxis.set_major_locator(plt.NullLocator()) + + for (x,y),w in np.ndenumerate(matrix): + color = 'white' if w > 0 else 'black' + size = np.sqrt(np.abs(w)) + rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, + facecolor=color, edgecolor=color) + ax.add_patch(rect) + + ax.autoscale_view() + ax.invert_yaxis() + + +if __name__ == '__main__': + hinton(np.random.rand(20, 20) - 0.5) + plt.show() + diff --git a/examples/statistics/errorbar_demo.py b/examples/statistics/errorbar_demo.py new file mode 100644 index 000000000000..4801f46a8218 --- /dev/null +++ b/examples/statistics/errorbar_demo.py @@ -0,0 +1,13 @@ +""" +Demo of the errorbar function. +""" +import numpy as np +import matplotlib.pyplot as plt + +# example data +x = np.arange(0.1, 4, 0.5) +y = np.exp(-x) + +plt.errorbar(x, y, xerr=0.2, yerr=0.4) +plt.show() + diff --git a/examples/statistics/errorbar_demo_features.py b/examples/statistics/errorbar_demo_features.py new file mode 100644 index 000000000000..2252d1fb4a8c --- /dev/null +++ b/examples/statistics/errorbar_demo_features.py @@ -0,0 +1,39 @@ +""" +Demo of errorbar function with different ways of specifying error bars. + +Errors can be specified as a constant value (as shown in `errorbar_demo.py`), +or as demonstrated in this example, they can be specified by an N x 1 or 2 x N, +where N is the number of data points. + +N x 1: + Error varies for each point, but the error values are symmetric (i.e. the + lower and upper values are equal). + +2 x N: + Error varies for each point, and the lower and upper limits (in that order) + are different (asymmetric case) + +In addition, this example demonstrates how to use log scale with errorbar. +""" +import numpy as np +import matplotlib.pyplot as plt + +# example data +x = np.arange(0.1, 4, 0.5) +y = np.exp(-x) +# example error bar values that vary with x-position +error = 0.1 + 0.2 * x +# error bar values w/ different -/+ errors +lower_error = 0.4 * error +upper_error = error +asymmetric_error = [lower_error, upper_error] + +fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True) +ax0.errorbar(x, y, yerr=error, fmt='-o') +ax0.set_title('variable, symmetric error') + +ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o') +ax1.set_title('variable, asymmetric error') +ax1.set_yscale('log') +plt.show() + diff --git a/examples/statistics/histogram_demo_features.py b/examples/statistics/histogram_demo_features.py new file mode 100644 index 000000000000..299f9bfeb70c --- /dev/null +++ b/examples/statistics/histogram_demo_features.py @@ -0,0 +1,35 @@ +""" +Demo of the histogram (hist) function with a few features. + +In addition to the basic histogram, this demo shows a few optional features: + + * Setting the number of data bins + * The ``normed`` flag, which normalizes bin heights so that the integral of + the histogram is 1. The resulting histogram is a probability density. + * Setting the face color of the bars + * Setting the opacity (alpha value). + +""" +import numpy as np +import matplotlib.mlab as mlab +import matplotlib.pyplot as plt + + +# example data +mu = 100 # mean of distribution +sigma = 15 # standard deviation of distribution +x = mu + sigma * np.random.randn(10000) + +num_bins = 50 +# the histogram of the data +n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5) +# add a 'best fit' line +y = mlab.normpdf(bins, mu, sigma) +plt.plot(bins, y, 'r--') +plt.xlabel('Smarts') +plt.ylabel('Probability') +plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$') + +# Tweak spacing to prevent clipping of ylabel +plt.subplots_adjust(left=0.15) +plt.show() diff --git a/examples/subplots_axes_and_figures/subplot_demo.py b/examples/subplots_axes_and_figures/subplot_demo.py new file mode 100644 index 000000000000..b90b53d899e9 --- /dev/null +++ b/examples/subplots_axes_and_figures/subplot_demo.py @@ -0,0 +1,24 @@ +""" +Simple demo with multiple subplots. +""" +import numpy as np +import matplotlib.pyplot as plt + + +x1 = np.linspace(0.0, 5.0) +x2 = np.linspace(0.0, 2.0) + +y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) +y2 = np.cos(2 * np.pi * x2) + +plt.subplot(2, 1, 1) +plt.plot(x1, y1, 'yo-') +plt.title('A tale of 2 subplots') +plt.ylabel('Damped oscillation') + +plt.subplot(2, 1, 2) +plt.plot(x2, y2, 'r.-') +plt.xlabel('time (s)') +plt.ylabel('Undamped') + +plt.show() diff --git a/examples/tests/backend_driver.py b/examples/tests/backend_driver.py index 9f1c28bb7606..8b18d73f461a 100755 --- a/examples/tests/backend_driver.py +++ b/examples/tests/backend_driver.py @@ -20,21 +20,84 @@ switches with a --. """ -import os, time, sys, glob, string +import os +import time +import sys +import glob from optparse import OptionParser + import matplotlib.rcsetup as rcsetup from matplotlib.cbook import Bunch, dedent + all_backends = list(rcsetup.all_backends) # to leave the original list alone # actual physical directory for each dir -dirs = dict(pylab = os.path.join('..', 'pylab_examples'), +dirs = dict(files=os.path.join('..', 'lines_bars_and_markers'), + shapes=os.path.join('..', 'shapes_and_collections'), + images=os.path.join('..', 'images_contours_and_fields'), + pie=os.path.join('..', 'pie_and_polar_charts'), + text=os.path.join('..', 'text_labels_and_annotations'), + ticks=os.path.join('..', 'ticks_and_spines'), + subplots=os.path.join('..', 'subplots_axes_and_figures'), + specialty=os.path.join('..', 'specialty_plots'), + showcase=os.path.join('..', 'showcase'), + pylab = os.path.join('..', 'pylab_examples'), api = os.path.join('..', 'api'), units = os.path.join('..', 'units'), mplot3d = os.path.join('..', 'mplot3d')) + # files in each dir files = dict() + +files['lines'] = [ + 'barh_demo.py', + 'fill_demo.py', + 'fill_demo_features.py', + 'line_demo_dash_control.py', + ] + +files['shapes'] = [ + 'path_patch_demo.py', + 'scatter_demo.py', + ] + +files['images'] = [ + 'imshow_demo.py', + ] + + +files['statistics'] = [ + 'errorbar_demo.py', + 'errorbar_demo_features.py', + 'histogram_demo_features.py', + ] + +files['pie'] = [ + 'pie_demo.py', + 'polar_bar_demo.py', + 'polar_scatter_demo.py', + ] + +files['text_labels_and_annotations'] = [ + 'text_demo_fontdict.py', + 'unicode_demo.py', + ] + +files['ticks_and_spines'] = [ + 'spines_demo_bounds.py', + 'ticklabels_demo_rotation.py', + ] + +files['subplots_axes_and_figures'] = [ + 'subplot_demo.py', + ] + +files['showcase'] = [ + 'integral_demo.py', + ] + files['pylab'] = [ 'accented_text.py', 'alignment_test.py', @@ -53,7 +116,6 @@ 'barb_demo.py', 'barchart_demo.py', 'barcode_demo.py', - 'barh_demo.py', 'boxplot_demo.py', 'broken_barh.py', 'clippedline.py', @@ -74,7 +136,6 @@ 'custom_figure_class.py', 'custom_ticker1.py', 'customize_rc.py', - 'dash_control.py', 'dashpointlabel.py', 'date_demo1.py', 'date_demo2.py', @@ -86,7 +147,6 @@ 'ellipse_demo.py', 'ellipse_rotated.py', 'equal_aspect_ratio.py', - 'errorbar_demo.py', 'errorbar_limits.py', 'fancyarrow_demo.py', 'fancybox_demo.py', @@ -96,8 +156,6 @@ 'figlegend_demo.py', 'figure_title.py', 'fill_between_demo.py', - 'fill_demo.py', - 'fill_demo2.py', 'fill_spiral.py', 'finance_demo.py', 'findobj_demo.py', @@ -111,20 +169,17 @@ 'hexbin_demo.py', 'hexbin_demo2.py', 'hist_colormapped.py', - 'histogram_demo.py', 'histogram_demo_extended.py', 'hline_demo.py', 'image_clip_path.py', 'image_demo.py', 'image_demo2.py', - 'image_demo3.py', 'image_interp.py', 'image_masked.py', 'image_nonuniform.py', 'image_origin.py', 'image_slices_viewer.py', - 'integral_demo.py', 'interp_demo.py', 'invert_axes.py', 'layer_images.py', @@ -158,13 +213,10 @@ 'pcolor_demo2.py', 'pcolor_log.py', 'pcolor_small.py', - 'pie_demo.py', 'pie_demo2.py', 'plotfile_demo.py', - 'polar_bar.py', 'polar_demo.py', 'polar_legend.py', - 'polar_scatter.py', 'poormans_contour.py', 'psd_demo.py', 'psd_demo2.py', @@ -172,7 +224,6 @@ 'quadmesh_demo.py', 'quiver_demo.py', 'scatter_custom_symbol.py', - 'scatter_demo.py', 'scatter_demo2.py', 'scatter_masked.py', 'scatter_profile.py', @@ -188,17 +239,13 @@ 'step_demo.py', 'stix_fonts_demo.py', 'stock_demo.py', - 'subplot_demo.py', 'subplots_adjust.py', 'symlog_demo.py', 'table_demo.py', 'text_handles.py', 'text_rotation.py', 'text_rotation_relative_to_line.py', - 'text_themes.py', 'transoffset.py', - 'unicode_demo.py', - 'vertical_ticklabels.py', 'vline_demo.py', 'xcorr_demo.py', 'zorder_demo.py', @@ -218,7 +265,6 @@ 'date_index_formatter.py', 'donut_demo.py', 'font_family_rc.py', - 'histogram_demo.py', 'image_zcoord.py', 'joinstyle.py', 'legend_demo.py', @@ -226,7 +272,6 @@ 'logo2.py', 'mathtext_asarray.py', 'patch_collection.py', - 'path_patch_demo.py', 'quad_bezier.py', 'scatter_piecharts.py', 'span_regions.py', diff --git a/examples/text_labels_and_annotations/text_demo_fontdict.py b/examples/text_labels_and_annotations/text_demo_fontdict.py new file mode 100644 index 000000000000..a0dcf3f48d3a --- /dev/null +++ b/examples/text_labels_and_annotations/text_demo_fontdict.py @@ -0,0 +1,25 @@ +""" +Demo using fontdict to control style of text and labels. +""" +import numpy as np +import matplotlib.pyplot as plt + + +font = {'family' : 'serif', + 'color' : 'darkred', + 'weight' : 'normal', + 'size' : 16, + } + +x = np.linspace(0.0, 5.0, 100) +y = np.cos(2 * np.pi * x) * np.exp(-x) + +plt.plot(x, y, 'k') +plt.title('Damped exponential decay', fontdict=font) +plt.text(2, 0.65, r'$\cos(2 \pi t) \exp(-t)$', fontdict=font) +plt.xlabel('time (s)', fontdict=font) +plt.ylabel('voltage (mV)', fontdict=font) + +# Tweak spacing to prevent clipping of ylabel +plt.subplots_adjust(left=0.15) +plt.show() diff --git a/examples/text_labels_and_annotations/unicode_demo.py b/examples/text_labels_and_annotations/unicode_demo.py new file mode 100644 index 000000000000..295b3c4aa5fd --- /dev/null +++ b/examples/text_labels_and_annotations/unicode_demo.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +""" +Demo of unicode support in text and labels. +""" +from __future__ import unicode_literals + +import matplotlib.pyplot as plt + + +plt.title('Développés et fabriqués') +plt.xlabel("réactivité nous permettent d'être sélectionnés et adoptés") +plt.ylabel('André was here!') +plt.text( 0.2, 0.8, 'Institut für Festkörperphysik', rotation=45) +plt.text( 0.4, 0.2, 'AVA (check kerning)') + +plt.show() diff --git a/examples/ticks_and_spines/spines_demo.py b/examples/ticks_and_spines/spines_demo.py new file mode 100644 index 000000000000..a720131e845c --- /dev/null +++ b/examples/ticks_and_spines/spines_demo.py @@ -0,0 +1,31 @@ +""" +Basic demo of axis spines. + +This demo compares a normal axes, with spines on all four sides, and an axes +with spines only on the left and bottom. +""" +import numpy as np +import matplotlib.pyplot as plt + + +x = np.linspace(0, 2 * np.pi, 100) +y = 2 * np.sin(x) + +fig, (ax0, ax1) = plt.subplots(nrows=2) + +ax0.plot(x, y) +ax0.set_title('normal spines') + +ax1.plot(x, y) +ax1.set_title('bottom-left spines') + +# Hide the right and top spines +ax1.spines['right'].set_visible(False) +ax1.spines['top'].set_visible(False) +# Only show ticks on the left and bottom spines +ax1.yaxis.set_ticks_position('left') +ax1.xaxis.set_ticks_position('bottom') + +# Tweak spacing between subplots to prevent labels from overlapping +plt.subplots_adjust(hspace=0.5) +plt.show() diff --git a/examples/ticks_and_spines/spines_demo_bounds.py b/examples/ticks_and_spines/spines_demo_bounds.py new file mode 100644 index 000000000000..9db2591abcae --- /dev/null +++ b/examples/ticks_and_spines/spines_demo_bounds.py @@ -0,0 +1,32 @@ +""" +Demo of spines using custom bounds to limit the extent of the spine. +""" +import numpy as np +import matplotlib.pyplot as plt + + +x = np.linspace(0, 2*np.pi, 50) +y = np.sin(x) +y2 = y + 0.1 * np.random.normal(size=x.shape) + +fig, ax = plt.subplots() +ax.plot(x, y, 'k--') +ax.plot(x, y2, 'ro') + +# set ticks and tick labels +ax.set_xlim((0, 2*np.pi)) +ax.set_xticks([0, np.pi, 2*np.pi]) +ax.set_xticklabels(['0', '$\pi$','2$\pi$']) +ax.set_ylim((-1.5, 1.5)) +ax.set_yticks([-1, 0, 1]) + +# Only draw spine between the y-ticks +ax.spines['left'].set_bounds(-1, 1) +# Hide the right and top spines +ax.spines['right'].set_visible(False) +ax.spines['top'].set_visible(False) +# Only show ticks on the left and bottom spines +ax.yaxis.set_ticks_position('left') +ax.xaxis.set_ticks_position('bottom') + +plt.show() diff --git a/examples/ticks_and_spines/spines_demo_dropped.py b/examples/ticks_and_spines/spines_demo_dropped.py new file mode 100644 index 000000000000..1a11e8f58f59 --- /dev/null +++ b/examples/ticks_and_spines/spines_demo_dropped.py @@ -0,0 +1,24 @@ +""" +Demo of spines offset from the axes (a.k.a. "dropped spines"). +""" +import numpy as np +import matplotlib.pyplot as plt + + +fig, ax = plt.subplots() + +image = np.random.uniform(size=(10, 10)) +ax.imshow(image, cmap=plt.cm.gray, interpolation='nearest') +ax.set_title('dropped spines') + +# Move left and bottom spines outward by 10 points +ax.spines['left'].set_position(('outward', 10)) +ax.spines['bottom'].set_position(('outward', 10)) +# Hide the right and top spines +ax.spines['right'].set_visible(False) +ax.spines['top'].set_visible(False) +# Only show ticks on the left and bottom spines +ax.yaxis.set_ticks_position('left') +ax.xaxis.set_ticks_position('bottom') + +plt.show() diff --git a/examples/ticks_and_spines/ticklabels_demo_rotation.py b/examples/ticks_and_spines/ticklabels_demo_rotation.py new file mode 100644 index 000000000000..9c1c49b2e4d6 --- /dev/null +++ b/examples/ticks_and_spines/ticklabels_demo_rotation.py @@ -0,0 +1,18 @@ +""" +Demo of custom tick-labels with user-defined rotation. +""" +import matplotlib.pyplot as plt + + +x = [1, 2, 3, 4] +y = [1, 4, 9, 6] +labels = ['Frogs', 'Hogs', 'Bogs', 'Slogs'] + +plt.plot(x, y, 'ro') +# You can specify a rotation for the tick labels in degrees or with keywords. +plt.xticks(x, labels, rotation='vertical') +# Pad margins so that markers don't get clipped by the axes +plt.margins(0.2) +# Tweak spacing to prevent clipping of tick-labels +plt.subplots_adjust(bottom=0.15) +plt.show() diff --git a/lib/matplotlib/axes.py b/lib/matplotlib/axes.py index c2f294ce9d73..1f3342921d4a 100644 --- a/lib/matplotlib/axes.py +++ b/lib/matplotlib/axes.py @@ -5367,7 +5367,7 @@ def errorbar(self, x, y, yerr=None, xerr=None, **Example:** - .. plot:: mpl_examples/pylab_examples/errorbar_demo.py + .. plot:: mpl_examples/statistics/errorbar_demo.py """ @@ -6697,7 +6697,7 @@ def fill(self, *args, **kwargs): **Example:** - .. plot:: mpl_examples/pylab_examples/fill_demo.py + .. plot:: mpl_examples/lines_bars_and_markers/fill_demo.py """ if not self._hold: @@ -7976,7 +7976,7 @@ def hist(self, x, bins=10, range=None, normed=False, weights=None, **Example:** - .. plot:: mpl_examples/pylab_examples/histogram_demo.py + .. plot:: mpl_examples/statistics/histogram_demo_features.py """ if not self._hold: diff --git a/lib/matplotlib/mpl-data/sample_data/lena.npy b/lib/matplotlib/mpl-data/sample_data/lena.npy new file mode 100644 index 000000000000..39f4fb1f07f8 Binary files /dev/null and b/lib/matplotlib/mpl-data/sample_data/lena.npy differ diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 493d95b9d4df..20e6d2eb2d60 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -763,12 +763,12 @@ def subplot(*args, **kwargs): For additional information on :func:`axes` and :func:`subplot` keyword arguments. - :file:`examples/pylab_examples/polar_scatter.py` + :file:`examples/pie_and_polar_charts/polar_scatter_demo.py` For an example **Example:** - .. plot:: mpl_examples/pylab_examples/subplot_demo.py + .. plot:: mpl_examples/subplots_axes_and_figures/subplot_demo.py """ # if subplot called without arguments, create subplot(1,1,1)