diff --git a/doc/users/prev_whats_new/whats_new_0.98.4.rst b/doc/users/prev_whats_new/whats_new_0.98.4.rst index 3cb48c72e4ed..671ec74c0a4f 100644 --- a/doc/users/prev_whats_new/whats_new_0.98.4.rst +++ b/doc/users/prev_whats_new/whats_new_0.98.4.rst @@ -79,7 +79,7 @@ psd amplitude scaling Ryan May did a lot of work to rationalize the amplitude scaling of :func:`~matplotlib.pyplot.psd` and friends. See -:ref:`sphx_glr_gallery_pylab_examples_psd_demo2.py`. and :ref:`sphx_glr_gallery_pylab_examples_psd_demo3.py`. +:ref:`sphx_glr_gallery_pylab_examples_psd_demo.py`. The changes should increase MATLAB compatibility and increase scaling options. diff --git a/doc/users/prev_whats_new/whats_new_1.1.rst b/doc/users/prev_whats_new/whats_new_1.1.rst index 33477ad2ce6a..487c49e28cdd 100644 --- a/doc/users/prev_whats_new/whats_new_1.1.rst +++ b/doc/users/prev_whats_new/whats_new_1.1.rst @@ -119,8 +119,8 @@ been improved in the presence of NANs. See the :ref:`sphx_glr_tutorials_02_intermediate_legend_guide.py` for more detailed explanation and examples. -.. figure:: ../../gallery/pylab_examples/images/sphx_glr_legend_demo4_001.png - :target: ../../gallery/pylab_examples/legend_demo4.html +.. figure:: ../../gallery/text_labels_and_annotations/images/sphx_glr_legend_demo_004.png + :target: ../../gallery/text_labels_and_annotations/legend_demo.html :align: center :scale: 50 diff --git a/doc/users/prev_whats_new/whats_new_1.2.rst b/doc/users/prev_whats_new/whats_new_1.2.rst index 48c19f090fa5..adb23cca4215 100644 --- a/doc/users/prev_whats_new/whats_new_1.2.rst +++ b/doc/users/prev_whats_new/whats_new_1.2.rst @@ -128,8 +128,8 @@ confidence intervals into the :meth:`~matplotlib.axes.boxplot` method. For every column of data passed to boxplot, the user can specify an accompanying median and confidence interval. -.. figure:: ../../gallery/pylab_examples/images/sphx_glr_boxplot_demo3_001.png - :target: ../../gallery/pylab_examples/boxplot_demo3.html +.. figure:: ../../gallery/statistics/images/sphx_glr_boxplot_demo_003.png + :target: ../../gallery/statistics/boxplot_demo.html :align: center :scale: 50 diff --git a/doc/users/prev_whats_new/whats_new_1.3.rst b/doc/users/prev_whats_new/whats_new_1.3.rst index d17a2ce8ed81..2bbad25ac467 100644 --- a/doc/users/prev_whats_new/whats_new_1.3.rst +++ b/doc/users/prev_whats_new/whats_new_1.3.rst @@ -154,8 +154,8 @@ Till Stensitzki added non-zero baselines to :func:`~matplotlib.pyplot.stackplot`. They may be symmetric or weighted. -.. figure:: ../../gallery/pylab_examples/images/sphx_glr_stackplot_demo2_001.png - :target: ../../gallery/pylab_examples/stackplot_demo2.html +.. figure:: ../../gallery/pylab_examples/images/sphx_glr_stackplot_demo_001.png + :target: ../../gallery/pylab_examples/stackplot_demo.html :align: center :scale: 50 diff --git a/examples/pylab_examples/image_slices_viewer.py b/examples/animation/image_slices_viewer.py similarity index 100% rename from examples/pylab_examples/image_slices_viewer.py rename to examples/animation/image_slices_viewer.py diff --git a/examples/images_contours_and_fields/image_demo.py b/examples/images_contours_and_fields/image_demo.py index 65bba8c6412e..40cc412bd38f 100644 --- a/examples/images_contours_and_fields/image_demo.py +++ b/examples/images_contours_and_fields/image_demo.py @@ -1,17 +1,176 @@ """ -=================== -Displaying an image -=================== +========== +Image Demo +========== + +Many ways to plot images in Matplotlib. + +The most common way to plot images in Matplotlib is with +imshow. The following examples demonstrate much of the +functionality of imshow and the many images you can create. -Simple demo of the imshow function. """ +from __future__ import print_function + +import numpy as np +import matplotlib.cm as cm +import matplotlib.mlab as mlab import matplotlib.pyplot as plt import matplotlib.cbook as cbook +from matplotlib.path import Path +from matplotlib.patches import PathPatch + +############################################################################### +# First we'll generate a simple bivariate normal distribution. + +delta = 0.025 +x = y = np.arange(-3.0, 3.0, delta) +X, Y = np.meshgrid(x, y) +Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) +Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) +Z = Z2 - Z1 # difference of Gaussians + +im = plt.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn, + origin='lower', extent=[-3, 3, -3, 3], + vmax=abs(Z).max(), vmin=-abs(Z).max()) + +plt.show() + + +############################################################################### +# It is also possible to show images of pictures. +# A sample image image_file = cbook.get_sample_data('ada.png') image = plt.imread(image_file) fig, ax = plt.subplots() ax.imshow(image) ax.axis('off') # clear x- and y-axes + + +# And another image + +w, h = 512, 512 + +datafile = cbook.get_sample_data('ct.raw.gz', asfileobj=True) +s = datafile.read() +A = np.fromstring(s, np.uint16).astype(float).reshape((w, h)) +A /= A.max() + +extent = (0, 25, 0, 25) +im = plt.imshow(A, cmap=plt.cm.hot, origin='upper', extent=extent) + +markers = [(15.9, 14.5), (16.8, 15)] +x, y = zip(*markers) +plt.plot(x, y, 'o') + +plt.title('CT density') + +plt.show() + + +############################################################################### +# Interpolating images +# -------------------- +# +# It is also possible to interpolate images before displaying them. Be careful, +# as this may manipulate the way your data looks, but it can be helpful for +# achieving the look you want. Below we'll display the same (small) array, +# interpolated with three different interpolation methods. +# +# The center of the pixel at A[i,j] is plotted at i+0.5, i+0.5. If you +# are using interpolation='nearest', the region bounded by (i,j) and +# (i+1,j+1) will have the same color. If you are using interpolation, +# the pixel center will have the same color as it does with nearest, but +# other pixels will be interpolated between the neighboring pixels. +# +# Earlier versions of matplotlib (<0.63) tried to hide the edge effects +# from you by setting the view limits so that they would not be visible. +# A recent bugfix in antigrain, and a new implementation in the +# matplotlib._image module which takes advantage of this fix, no longer +# makes this necessary. To prevent edge effects, when doing +# interpolation, the matplotlib._image module now pads the input array +# with identical pixels around the edge. e.g., if you have a 5x5 array +# with colors a-y as below:: +# +# a b c d e +# f g h i j +# k l m n o +# p q r s t +# u v w x y +# +# the _image module creates the padded array,:: +# +# a a b c d e e +# a a b c d e e +# f f g h i j j +# k k l m n o o +# p p q r s t t +# o u v w x y y +# o u v w x y y +# +# does the interpolation/resizing, and then extracts the central region. +# This allows you to plot the full range of your array w/o edge effects, +# and for example to layer multiple images of different sizes over one +# another with different interpolation methods - see +# examples/layer_images.py. It also implies a performance hit, as this +# new temporary, padded array must be created. Sophisticated +# interpolation also implies a performance hit, so if you need maximal +# performance or have very large images, interpolation='nearest' is +# suggested. + +A = np.random.rand(5, 5) +plt.figure(1) +plt.imshow(A, interpolation='nearest') +plt.grid(True) + +plt.figure(2) +plt.imshow(A, interpolation='bilinear') +plt.grid(True) + +plt.figure(3) +plt.imshow(A, interpolation='bicubic') +plt.grid(True) + +plt.show() + + +############################################################################### +# You can specify whether images should be plotted with the array origin +# x[0,0] in the upper left or upper right by using the origin parameter. +# You can also control the default be setting image.origin in your +# matplotlibrc file; see http://matplotlib.org/matplotlibrc + +x = np.arange(120).reshape((10, 12)) + +interp = 'bilinear' +fig, axs = plt.subplots(nrows=2, sharex=True, figsize=(3, 5)) +axs[0].set_title('blue should be up') +axs[0].imshow(x, origin='upper', interpolation=interp) + +axs[1].set_title('blue should be down') +axs[1].imshow(x, origin='lower', interpolation=interp) +plt.show() + + +############################################################################### +# Finally, we'll show an image using a clip path. + +delta = 0.025 +x = y = np.arange(-3.0, 3.0, delta) +X, Y = np.meshgrid(x, y) +Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) +Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) +Z = Z2 - Z1 # difference of Gaussians + +path = Path([[0, 1], [1, 0], [0, -1], [-1, 0], [0, 1]]) +patch = PathPatch(path, facecolor='none') +plt.gca().add_patch(patch) + +im = plt.imshow(Z, interpolation='bilinear', cmap=cm.gray, + origin='lower', extent=[-3, 3, -3, 3], + clip_path=patch, clip_on=True) +im.set_clip_path(patch) + plt.show() diff --git a/examples/pylab_examples/image_masked.py b/examples/images_contours_and_fields/image_masked.py similarity index 100% rename from examples/pylab_examples/image_masked.py rename to examples/images_contours_and_fields/image_masked.py diff --git a/examples/pylab_examples/image_nonuniform.py b/examples/images_contours_and_fields/image_nonuniform.py similarity index 100% rename from examples/pylab_examples/image_nonuniform.py rename to examples/images_contours_and_fields/image_nonuniform.py diff --git a/examples/pylab_examples/annotation_demo.py b/examples/pylab_examples/annotation_demo.py deleted file mode 100644 index b514626c64e0..000000000000 --- a/examples/pylab_examples/annotation_demo.py +++ /dev/null @@ -1,135 +0,0 @@ -""" -=============== -Annotation Demo -=============== - -Some examples of how to annotate points in figures. You specify an -annotation point xy=(x,y) and a text point xytext=(x,y) for the -annotated points and text location, respectively. Optionally, you can -specify the coordinate system of xy and xytext with one of the -following strings for xycoords and textcoords (default is 'data') - - - 'figure points' : points from the lower left corner of the figure - 'figure pixels' : pixels from the lower left corner of the figure - 'figure fraction' : 0,0 is lower left of figure and 1,1 is upper, right - 'axes points' : points from lower left corner of axes - 'axes pixels' : pixels from lower left corner of axes - 'axes fraction' : 0,0 is lower left of axes and 1,1 is upper right - 'offset points' : Specify an offset (in points) from the xy value - 'offset pixels' : Specify an offset (in pixels) from the xy value - 'data' : use the axes data coordinate system - -Optionally, you can specify arrow properties which draws and arrow -from the text to the annotated point by giving a dictionary of arrow -properties - -Valid keys are - - width : the width of the arrow in points - frac : the fraction of the arrow length occupied by the head - headwidth : the width of the base of the arrow head in points - shrink : move the tip/base some % away from the annotated point and text - any key for matplotlib.patches.polygon (e.g., facecolor) - -For physical coordinate systems (points or pixels) the origin is the -(bottom, left) of the figure or axes. -""" - - -import matplotlib.pyplot as plt -from matplotlib.patches import Ellipse -import numpy as np - - -# If only one location is given, the text and xypoint being -# annotated are assumed to be the same -fig = plt.figure() -ax = fig.add_subplot(111, autoscale_on=False, xlim=(-1, 5), ylim=(-3, 5)) - -t = np.arange(0.0, 5.0, 0.01) -s = np.cos(2*np.pi*t) -line, = ax.plot(t, s) - -ax.annotate('figure pixels', - xy=(10, 10), xycoords='figure pixels') - -ax.annotate('figure points', - xy=(80, 80), xycoords='figure points') - -ax.annotate('point offset from data', - xy=(2, 1), xycoords='data', - xytext=(-15, 25), textcoords='offset points', - arrowprops=dict(facecolor='black', shrink=0.05), - horizontalalignment='right', verticalalignment='bottom') - -ax.annotate('axes fraction', - xy=(3, 1), xycoords='data', - xytext=(0.8, 0.95), textcoords='axes fraction', - arrowprops=dict(facecolor='black', shrink=0.05), - horizontalalignment='right', verticalalignment='top') - -ax.annotate('figure fraction', - xy=(.025, .975), xycoords='figure fraction', - horizontalalignment='left', verticalalignment='top', - fontsize=20) - -# use negative points or pixels to specify from right, top -10, 10 -# is 10 points to the left of the right side of the axes and 10 -# points above the bottom -ax.annotate('pixel offset from axes fraction', - xy=(1, 0), xycoords='axes fraction', - xytext=(-20, 20), textcoords='offset pixels', - horizontalalignment='right', - verticalalignment='bottom') - - -# You can specify the xypoint and the xytext in different positions and -# coordinate systems, and optionally turn on a connecting line and mark -# the point with a marker. Annotations work on polar axes too. -# In the example below, the xy point is in native coordinates (xycoords -# defaults to 'data'). For a polar axes, this is in (theta, radius) space. -# The text in the example is placed in the fractional figure coordinate system. -# Text keyword args like horizontal and vertical alignment are respected. -fig = plt.figure() -ax = fig.add_subplot(111, projection='polar') -r = np.arange(0, 1, 0.001) -theta = 2*2*np.pi*r -line, = ax.plot(theta, r) - -ind = 800 -thisr, thistheta = r[ind], theta[ind] -ax.plot([thistheta], [thisr], 'o') -ax.annotate('a polar annotation', - xy=(thistheta, thisr), # theta, radius - xytext=(0.05, 0.05), # fraction, fraction - textcoords='figure fraction', - arrowprops=dict(facecolor='black', shrink=0.05), - horizontalalignment='left', - verticalalignment='bottom') - - -# You can also use polar notation on a cartesian axes. Here the native -# coordinate system ('data') is cartesian, so you need to specify the -# xycoords and textcoords as 'polar' if you want to use (theta, radius). - -el = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5) - -fig = plt.figure() -ax = fig.add_subplot(111, aspect='equal') -ax.add_artist(el) -el.set_clip_box(ax.bbox) -ax.annotate('the top', - xy=(np.pi/2., 10.), # theta, radius - xytext=(np.pi/3, 20.), # theta, radius - xycoords='polar', - textcoords='polar', - arrowprops=dict(facecolor='black', shrink=0.05), - horizontalalignment='left', - verticalalignment='bottom', - clip_on=True) # clip to the axes bounding box - -ax.set_xlim([-20, 20]) -ax.set_ylim([-20, 20]) - -plt.show() diff --git a/examples/pylab_examples/annotation_demo2.py b/examples/pylab_examples/annotation_demo2.py deleted file mode 100644 index 86a707621de3..000000000000 --- a/examples/pylab_examples/annotation_demo2.py +++ /dev/null @@ -1,156 +0,0 @@ -""" -================ -Annotation Demo2 -================ - -""" -import matplotlib.pyplot as plt -from matplotlib.patches import Ellipse -import numpy as np - - -fig = plt.figure(1, figsize=(8, 5)) -ax = fig.add_subplot(111, autoscale_on=False, xlim=(-1, 5), ylim=(-4, 3)) - -t = np.arange(0.0, 5.0, 0.01) -s = np.cos(2*np.pi*t) -line, = ax.plot(t, s, lw=3) - -ax.annotate('straight', - xy=(0, 1), xycoords='data', - xytext=(-50, 30), textcoords='offset points', - arrowprops=dict(arrowstyle="->")) - -ax.annotate('arc3,\nrad 0.2', - xy=(0.5, -1), xycoords='data', - xytext=(-80, -60), textcoords='offset points', - arrowprops=dict(arrowstyle="->", - connectionstyle="arc3,rad=.2")) - -ax.annotate('arc,\nangle 50', - xy=(1., 1), xycoords='data', - xytext=(-90, 50), textcoords='offset points', - arrowprops=dict(arrowstyle="->", - connectionstyle="arc,angleA=0,armA=50,rad=10")) - -ax.annotate('arc,\narms', - xy=(1.5, -1), xycoords='data', - xytext=(-80, -60), textcoords='offset points', - arrowprops=dict(arrowstyle="->", - connectionstyle="arc,angleA=0,armA=40,angleB=-90,armB=30,rad=7")) - -ax.annotate('angle,\nangle 90', - xy=(2., 1), xycoords='data', - xytext=(-70, 30), textcoords='offset points', - arrowprops=dict(arrowstyle="->", - connectionstyle="angle,angleA=0,angleB=90,rad=10")) - -ax.annotate('angle3,\nangle -90', - xy=(2.5, -1), xycoords='data', - xytext=(-80, -60), textcoords='offset points', - arrowprops=dict(arrowstyle="->", - connectionstyle="angle3,angleA=0,angleB=-90")) - -ax.annotate('angle,\nround', - xy=(3., 1), xycoords='data', - xytext=(-60, 30), textcoords='offset points', - bbox=dict(boxstyle="round", fc="0.8"), - arrowprops=dict(arrowstyle="->", - connectionstyle="angle,angleA=0,angleB=90,rad=10")) - -ax.annotate('angle,\nround4', - xy=(3.5, -1), xycoords='data', - xytext=(-70, -80), textcoords='offset points', - size=20, - bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), - arrowprops=dict(arrowstyle="->", - connectionstyle="angle,angleA=0,angleB=-90,rad=10")) - -ax.annotate('angle,\nshrink', - xy=(4., 1), xycoords='data', - xytext=(-60, 30), textcoords='offset points', - bbox=dict(boxstyle="round", fc="0.8"), - arrowprops=dict(arrowstyle="->", - shrinkA=0, shrinkB=10, - connectionstyle="angle,angleA=0,angleB=90,rad=10")) - -# You can pass an empty string to get only annotation arrows rendered -ann = ax.annotate('', xy=(4., 1.), xycoords='data', - xytext=(4.5, -1), textcoords='data', - arrowprops=dict(arrowstyle="<->", - connectionstyle="bar", - ec="k", - shrinkA=5, shrinkB=5)) - - -fig = plt.figure(2) -fig.clf() -ax = fig.add_subplot(111, autoscale_on=False, xlim=(-1, 5), ylim=(-5, 3)) - -el = Ellipse((2, -1), 0.5, 0.5) -ax.add_patch(el) - -ax.annotate('$->$', - xy=(2., -1), xycoords='data', - xytext=(-150, -140), textcoords='offset points', - bbox=dict(boxstyle="round", fc="0.8"), - arrowprops=dict(arrowstyle="->", - patchB=el, - connectionstyle="angle,angleA=90,angleB=0,rad=10")) - -ax.annotate('arrow\nfancy', - xy=(2., -1), xycoords='data', - xytext=(-100, 60), textcoords='offset points', - size=20, - # bbox=dict(boxstyle="round", fc="0.8"), - arrowprops=dict(arrowstyle="fancy", - fc="0.6", ec="none", - patchB=el, - connectionstyle="angle3,angleA=0,angleB=-90")) - -ax.annotate('arrow\nsimple', - xy=(2., -1), xycoords='data', - xytext=(100, 60), textcoords='offset points', - size=20, - # bbox=dict(boxstyle="round", fc="0.8"), - arrowprops=dict(arrowstyle="simple", - fc="0.6", ec="none", - patchB=el, - connectionstyle="arc3,rad=0.3")) - -ax.annotate('wedge', - xy=(2., -1), xycoords='data', - xytext=(-100, -100), textcoords='offset points', - size=20, - # bbox=dict(boxstyle="round", fc="0.8"), - arrowprops=dict(arrowstyle="wedge,tail_width=0.7", - fc="0.6", ec="none", - patchB=el, - connectionstyle="arc3,rad=-0.3")) - -ann = ax.annotate('bubble,\ncontours', - xy=(2., -1), xycoords='data', - xytext=(0, -70), textcoords='offset points', - size=20, - bbox=dict(boxstyle="round", - fc=(1.0, 0.7, 0.7), - ec=(1., .5, .5)), - arrowprops=dict(arrowstyle="wedge,tail_width=1.", - fc=(1.0, 0.7, 0.7), ec=(1., .5, .5), - patchA=None, - patchB=el, - relpos=(0.2, 0.8), - connectionstyle="arc3,rad=-0.1")) - -ann = ax.annotate('bubble', - xy=(2., -1), xycoords='data', - xytext=(55, 0), textcoords='offset points', - size=20, va="center", - bbox=dict(boxstyle="round", fc=(1.0, 0.7, 0.7), ec="none"), - arrowprops=dict(arrowstyle="wedge,tail_width=1.", - fc=(1.0, 0.7, 0.7), ec="none", - patchA=None, - patchB=el, - relpos=(0.2, 0.5))) - -plt.show() diff --git a/examples/pylab_examples/annotation_demo3.py b/examples/pylab_examples/annotation_demo3.py deleted file mode 100644 index 6baa8e7f8609..000000000000 --- a/examples/pylab_examples/annotation_demo3.py +++ /dev/null @@ -1,94 +0,0 @@ -""" -================ -Annotation Demo3 -================ - -""" -import matplotlib.pyplot as plt -from matplotlib.text import OffsetFrom - - -fig, (ax1, ax2) = plt.subplots(1, 2) - -bbox_args = dict(boxstyle="round", fc="0.8") -arrow_args = dict(arrowstyle="->") - -ax1.annotate('figure fraction : 0, 0', xy=(0, 0), xycoords='figure fraction', - xytext=(20, 20), textcoords='offset points', - ha="left", va="bottom", - bbox=bbox_args, - arrowprops=arrow_args) - -ax1.annotate('figure fraction : 1, 1', xy=(1, 1), xycoords='figure fraction', - xytext=(-20, -20), textcoords='offset points', - ha="right", va="top", - bbox=bbox_args, - arrowprops=arrow_args) - -ax1.annotate('axes fraction : 0, 0', xy=(0, 0), xycoords='axes fraction', - xytext=(20, 20), textcoords='offset points', - ha="left", va="bottom", - bbox=bbox_args, - arrowprops=arrow_args) - -ax1.annotate('axes fraction : 1, 1', xy=(1, 1), xycoords='axes fraction', - xytext=(-20, -20), textcoords='offset points', - ha="right", va="top", - bbox=bbox_args, - arrowprops=arrow_args) - - -an1 = ax1.annotate('Drag me 1', xy=(.5, .7), xycoords='data', - #xytext=(.5, .7), textcoords='data', - ha="center", va="center", - bbox=bbox_args, - #arrowprops=arrow_args - ) - -an2 = ax1.annotate('Drag me 2', xy=(.5, .5), xycoords=an1, - xytext=(.5, .3), textcoords='axes fraction', - ha="center", va="center", - bbox=bbox_args, - arrowprops=dict(patchB=an1.get_bbox_patch(), - connectionstyle="arc3,rad=0.2", - **arrow_args)) - -an3 = ax1.annotate('', xy=(.5, .5), xycoords=an2, - xytext=(.5, .5), textcoords=an1, - ha="center", va="center", - bbox=bbox_args, - arrowprops=dict(patchA=an1.get_bbox_patch(), - patchB=an2.get_bbox_patch(), - connectionstyle="arc3,rad=0.2", - **arrow_args)) - - -t = ax2.annotate('xy=(0, 1)\nxycoords=("data", "axes fraction")', - xy=(0, 1), xycoords=("data", 'axes fraction'), - xytext=(0, -20), textcoords='offset points', - ha="center", va="top", - bbox=bbox_args, - arrowprops=arrow_args) - -ax2.annotate('xy=(0.5, 0)\nxycoords=artist', - xy=(0.5, 0.), xycoords=t, - xytext=(0, -20), textcoords='offset points', - ha="center", va="top", - bbox=bbox_args, - arrowprops=arrow_args) - -ax2.annotate('xy=(0.8, 0.5)\nxycoords=ax1.transData', - xy=(0.8, 0.5), xycoords=ax1.transData, - xytext=(10, 10), - textcoords=OffsetFrom(ax2.bbox, (0, 0), "points"), - ha="left", va="bottom", - bbox=bbox_args, - arrowprops=arrow_args) - -ax2.set_xlim([-2, 2]) -ax2.set_ylim([-2, 2]) - -an1.draggable() -an2.draggable() - -plt.show() diff --git a/examples/pylab_examples/barchart_demo.py b/examples/pylab_examples/barchart_demo.py deleted file mode 100644 index a1f23bf1214f..000000000000 --- a/examples/pylab_examples/barchart_demo.py +++ /dev/null @@ -1,49 +0,0 @@ -""" -============= -Barchart Demo -============= - -Bar chart demo with pairs of bars grouped for easy comparison. -""" -import numpy as np -import matplotlib.pyplot as plt - - -n_groups = 5 - -means_men = (20, 35, 30, 35, 27) -std_men = (2, 3, 4, 1, 2) - -means_women = (25, 32, 34, 20, 25) -std_women = (3, 5, 2, 3, 3) - -fig, ax = plt.subplots() - -index = np.arange(n_groups) -bar_width = 0.35 - -opacity = 0.4 -error_config = {'ecolor': '0.3'} - -rects1 = plt.bar(index, means_men, bar_width, - alpha=opacity, - color='b', - yerr=std_men, - error_kw=error_config, - label='Men') - -rects2 = plt.bar(index + bar_width, means_women, bar_width, - alpha=opacity, - color='r', - yerr=std_women, - error_kw=error_config, - label='Women') - -plt.xlabel('Group') -plt.ylabel('Scores') -plt.title('Scores by group and gender') -plt.xticks(index + bar_width / 2, ('A', 'B', 'C', 'D', 'E')) -plt.legend() - -plt.tight_layout() -plt.show() diff --git a/examples/pylab_examples/boxplot_demo.py b/examples/pylab_examples/boxplot_demo.py deleted file mode 100644 index c285193ecf4c..000000000000 --- a/examples/pylab_examples/boxplot_demo.py +++ /dev/null @@ -1,61 +0,0 @@ -""" -============ -Boxplot Demo -============ - -""" -import matplotlib.pyplot as plt -import numpy as np - -# Fixing random state for reproducibility -np.random.seed(19680801) - -# fake up some data -spread = np.random.rand(50) * 100 -center = np.ones(25) * 50 -flier_high = np.random.rand(10) * 100 + 100 -flier_low = np.random.rand(10) * -100 -data = np.concatenate((spread, center, flier_high, flier_low), 0) - -# basic plot -plt.boxplot(data) - -# notched plot -plt.figure() -plt.boxplot(data, 1) - -# change outlier point symbols -plt.figure() -plt.boxplot(data, 0, 'gD') - -# don't show outlier points -plt.figure() -plt.boxplot(data, 0, '') - -# horizontal boxes -plt.figure() -plt.boxplot(data, 0, 'rs', 0) - -# change whisker length -plt.figure() -plt.boxplot(data, 0, 'rs', 0, 0.75) - -# fake up some more data -spread = np.random.rand(50) * 100 -center = np.ones(25) * 40 -flier_high = np.random.rand(10) * 100 + 100 -flier_low = np.random.rand(10) * -100 -d2 = np.concatenate((spread, center, flier_high, flier_low), 0) -data.shape = (-1, 1) -d2.shape = (-1, 1) -# data = concatenate( (data, d2), 1 ) -# Making a 2-D array only works if all the columns are the -# same length. If they are not, then use a list instead. -# This is actually more efficient because boxplot converts -# a 2-D array into a list of vectors internally anyway. -data = [data, d2, d2[::2, 0]] -# multiple box plots on one figure -plt.figure() -plt.boxplot(data) - -plt.show() diff --git a/examples/pylab_examples/boxplot_demo3.py b/examples/pylab_examples/boxplot_demo3.py deleted file mode 100644 index e4b40a980506..000000000000 --- a/examples/pylab_examples/boxplot_demo3.py +++ /dev/null @@ -1,54 +0,0 @@ -""" -============= -Boxplot Demo3 -============= - -""" -import matplotlib.pyplot as plt -import numpy as np - - -def fakeBootStrapper(n): - ''' - This is just a placeholder for the user's method of - bootstrapping the median and its confidence intervals. - - Returns an arbitrary median and confidence intervals - packed into a tuple - ''' - if n == 1: - med = 0.1 - CI = (-0.25, 0.25) - else: - med = 0.2 - CI = (-0.35, 0.50) - - return med, CI - -# Fixing random state for reproducibility -np.random.seed(19680801) - -inc = 0.1 -e1 = np.random.normal(0, 1, size=(500,)) -e2 = np.random.normal(0, 1, size=(500,)) -e3 = np.random.normal(0, 1 + inc, size=(500,)) -e4 = np.random.normal(0, 1 + 2*inc, size=(500,)) - -treatments = [e1, e2, e3, e4] -med1, CI1 = fakeBootStrapper(1) -med2, CI2 = fakeBootStrapper(2) -medians = [None, None, med1, med2] -conf_intervals = [None, None, CI1, CI2] - -fig, ax = plt.subplots() -pos = np.array(range(len(treatments))) + 1 -bp = ax.boxplot(treatments, sym='k+', positions=pos, - notch=1, bootstrap=5000, - usermedians=medians, - conf_intervals=conf_intervals) - -ax.set_xlabel('treatment') -ax.set_ylabel('response') -plt.setp(bp['whiskers'], color='k', linestyle='-') -plt.setp(bp['fliers'], markersize=3.0) -plt.show() diff --git a/examples/pylab_examples/fancybox_demo.py b/examples/pylab_examples/fancybox_demo.py index c6240136a1ef..9b3b02314c2f 100644 --- a/examples/pylab_examples/fancybox_demo.py +++ b/examples/pylab_examples/fancybox_demo.py @@ -3,11 +3,37 @@ Fancybox Demo ============= +Plotting fancy boxes with Matplotlib. + +The following examples show how to plot boxes with different +visual properties. """ import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms +import matplotlib.patches as mpatch from matplotlib.patches import FancyBboxPatch +############################################################################### +# First we'll show some sample boxes with fancybox. + +styles = mpatch.BoxStyle.get_styles() +spacing = 1.2 + +figheight = (spacing * len(styles) + .5) +fig1 = plt.figure(1, (4/1.5, figheight/1.5)) +fontsize = 0.3 * 72 + +for i, stylename in enumerate(sorted(styles)): + fig1.text(0.5, (spacing * (len(styles) - i) - 0.5) / figheight, stylename, + ha="center", + size=fontsize, + transform=fig1.transFigure, + bbox=dict(boxstyle=stylename, fc="w", ec="k")) + +plt.show() + +############################################################################### +# Next we'll show off multiple fancy boxes at once. # Bbox object around which the fancy box will be drawn. bb = mtransforms.Bbox([[0.3, 0.4], [0.7, 0.6]]) diff --git a/examples/pylab_examples/fancybox_demo2.py b/examples/pylab_examples/fancybox_demo2.py deleted file mode 100644 index bedde709385a..000000000000 --- a/examples/pylab_examples/fancybox_demo2.py +++ /dev/null @@ -1,24 +0,0 @@ -""" -============== -Fancybox Demo2 -============== - -""" -import matplotlib.patches as mpatch -import matplotlib.pyplot as plt - -styles = mpatch.BoxStyle.get_styles() -spacing = 1.2 - -figheight = (spacing * len(styles) + .5) -fig1 = plt.figure(1, (4/1.5, figheight/1.5)) -fontsize = 0.3 * 72 - -for i, stylename in enumerate(sorted(styles)): - fig1.text(0.5, (spacing * (len(styles) - i) - 0.5) / figheight, stylename, - ha="center", - size=fontsize, - transform=fig1.transFigure, - bbox=dict(boxstyle=stylename, fc="w", ec="k")) - -plt.show() diff --git a/examples/pylab_examples/hexbin_demo.py b/examples/pylab_examples/hexbin_demo.py deleted file mode 100644 index 7809e7a0b682..000000000000 --- a/examples/pylab_examples/hexbin_demo.py +++ /dev/null @@ -1,42 +0,0 @@ -""" -=========== -Hexbin Demo -=========== - -hexbin is an axes method or pyplot function that is essentially -a pcolor of a 2-D histogram with hexagonal cells. It can be -much more informative than a scatter plot; in the first subplot -below, try substituting 'scatter' for 'hexbin'. -""" - -import numpy as np -import matplotlib.pyplot as plt - -# Fixing random state for reproducibility -np.random.seed(19680801) - -n = 100000 -x = np.random.standard_normal(n) -y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n) -xmin = x.min() -xmax = x.max() -ymin = y.min() -ymax = y.max() - -fig, axs = plt.subplots(ncols=2, sharey=True, figsize=(7, 4)) -fig.subplots_adjust(hspace=0.5, left=0.07, right=0.93) -ax = axs[0] -hb = ax.hexbin(x, y, gridsize=50, cmap='inferno') -ax.axis([xmin, xmax, ymin, ymax]) -ax.set_title("Hexagon binning") -cb = fig.colorbar(hb, ax=ax) -cb.set_label('counts') - -ax = axs[1] -hb = ax.hexbin(x, y, gridsize=50, bins='log', cmap='inferno') -ax.axis([xmin, xmax, ymin, ymax]) -ax.set_title("With a log color scale") -cb = fig.colorbar(hb, ax=ax) -cb.set_label('log10(N)') - -plt.show() diff --git a/examples/pylab_examples/hexbin_demo2.py b/examples/pylab_examples/hexbin_demo2.py deleted file mode 100644 index 3fd3f783595b..000000000000 --- a/examples/pylab_examples/hexbin_demo2.py +++ /dev/null @@ -1,59 +0,0 @@ -""" -============ -Hexbin Demo2 -============ - -hexbin is an axes method or pyplot function that is essentially a -pcolor of a 2-D histogram with hexagonal cells. -""" - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib.mlab as mlab - -delta = 0.025 -x = y = np.arange(-3.0, 3.0, delta) -X, Y = np.meshgrid(x, y) -Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -Z = Z2 - Z1 # difference of Gaussians - -x = X.ravel() -y = Y.ravel() -z = Z.ravel() - -if 1: - # make some points 20 times more common than others, but same mean - xcond = (-1 < x) & (x < 1) - ycond = (-2 < y) & (y < 0) - cond = xcond & ycond - xnew = x[cond] - ynew = y[cond] - znew = z[cond] - for i in range(20): - x = np.hstack((x, xnew)) - y = np.hstack((y, ynew)) - z = np.hstack((z, znew)) - -xmin = x.min() -xmax = x.max() -ymin = y.min() -ymax = y.max() - -gridsize = 30 - -plt.subplot(211) -plt.hexbin(x, y, C=z, gridsize=gridsize, marginals=True, cmap=plt.cm.RdBu, - vmax=abs(z).max(), vmin=-abs(z).max()) -plt.axis([xmin, xmax, ymin, ymax]) -cb = plt.colorbar() -cb.set_label('mean value') - - -plt.subplot(212) -plt.hexbin(x, y, gridsize=gridsize, cmap=plt.cm.Blues_r) -plt.axis([xmin, xmax, ymin, ymax]) -cb = plt.colorbar() -cb.set_label('N observations') - -plt.show() diff --git a/examples/pylab_examples/image_clip_path.py b/examples/pylab_examples/image_clip_path.py deleted file mode 100644 index 005ce17cea23..000000000000 --- a/examples/pylab_examples/image_clip_path.py +++ /dev/null @@ -1,30 +0,0 @@ -""" -=============== -Image Clip Path -=============== - -""" -import numpy as np -import matplotlib.cm as cm -import matplotlib.mlab as mlab -import matplotlib.pyplot as plt -from matplotlib.path import Path -from matplotlib.patches import PathPatch - -delta = 0.025 -x = y = np.arange(-3.0, 3.0, delta) -X, Y = np.meshgrid(x, y) -Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -Z = Z2 - Z1 # difference of Gaussians - -path = Path([[0, 1], [1, 0], [0, -1], [-1, 0], [0, 1]]) -patch = PathPatch(path, facecolor='none') -plt.gca().add_patch(patch) - -im = plt.imshow(Z, interpolation='bilinear', cmap=cm.gray, - origin='lower', extent=[-3, 3, -3, 3], - clip_path=patch, clip_on=True) -im.set_clip_path(patch) - -plt.show() diff --git a/examples/pylab_examples/image_demo.py b/examples/pylab_examples/image_demo.py deleted file mode 100644 index 477e81d377b4..000000000000 --- a/examples/pylab_examples/image_demo.py +++ /dev/null @@ -1,23 +0,0 @@ -""" -========== -Image Demo -========== - -""" -import numpy as np -import matplotlib.cm as cm -import matplotlib.mlab as mlab -import matplotlib.pyplot as plt - -delta = 0.025 -x = y = np.arange(-3.0, 3.0, delta) -X, Y = np.meshgrid(x, y) -Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -Z = Z2 - Z1 # difference of Gaussians - -im = plt.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn, - origin='lower', extent=[-3, 3, -3, 3], - vmax=abs(Z).max(), vmin=-abs(Z).max()) - -plt.show() diff --git a/examples/pylab_examples/image_demo2.py b/examples/pylab_examples/image_demo2.py deleted file mode 100644 index e5493e9548bf..000000000000 --- a/examples/pylab_examples/image_demo2.py +++ /dev/null @@ -1,28 +0,0 @@ -""" -=========== -Image Demo2 -=========== - -""" -from __future__ import print_function -import matplotlib.pyplot as plt -import numpy as np -import matplotlib.cbook as cbook - -w, h = 512, 512 - -datafile = cbook.get_sample_data('ct.raw.gz', asfileobj=True) -s = datafile.read() -A = np.fromstring(s, np.uint16).astype(float).reshape((w, h)) -A /= A.max() - -extent = (0, 25, 0, 25) -im = plt.imshow(A, cmap=plt.cm.hot, origin='upper', extent=extent) - -markers = [(15.9, 14.5), (16.8, 15)] -x, y = zip(*markers) -plt.plot(x, y, 'o') - -plt.title('CT density') - -plt.show() diff --git a/examples/pylab_examples/image_interp.py b/examples/pylab_examples/image_interp.py deleted file mode 100644 index fd9d0f2877d4..000000000000 --- a/examples/pylab_examples/image_interp.py +++ /dev/null @@ -1,71 +0,0 @@ -""" -============ -Image Interp -============ - -The same (small) array, interpolated with three different -interpolation methods. - -The center of the pixel at A[i,j] is plotted at i+0.5, i+0.5. If you -are using interpolation='nearest', the region bounded by (i,j) and -(i+1,j+1) will have the same color. If you are using interpolation, -the pixel center will have the same color as it does with nearest, but -other pixels will be interpolated between the neighboring pixels. - -Earlier versions of matplotlib (<0.63) tried to hide the edge effects -from you by setting the view limits so that they would not be visible. -A recent bugfix in antigrain, and a new implementation in the -matplotlib._image module which takes advantage of this fix, no longer -makes this necessary. To prevent edge effects, when doing -interpolation, the matplotlib._image module now pads the input array -with identical pixels around the edge. e.g., if you have a 5x5 array -with colors a-y as below:: - - a b c d e - f g h i j - k l m n o - p q r s t - u v w x y - -the _image module creates the padded array,:: - - a a b c d e e - a a b c d e e - f f g h i j j - k k l m n o o - p p q r s t t - o u v w x y y - o u v w x y y - -does the interpolation/resizing, and then extracts the central region. -This allows you to plot the full range of your array w/o edge effects, -and for example to layer multiple images of different sizes over one -another with different interpolation methods - see -examples/layer_images.py. It also implies a performance hit, as this -new temporary, padded array must be created. Sophisticated -interpolation also implies a performance hit, so if you need maximal -performance or have very large images, interpolation='nearest' is -suggested. - -""" -import matplotlib.pyplot as plt -import numpy as np - -# Fixing random state for reproducibility -np.random.seed(19680801) - - -A = np.random.rand(5, 5) -plt.figure(1) -plt.imshow(A, interpolation='nearest') -plt.grid(True) - -plt.figure(2) -plt.imshow(A, interpolation='bilinear') -plt.grid(True) - -plt.figure(3) -plt.imshow(A, interpolation='bicubic') -plt.grid(True) - -plt.show() diff --git a/examples/pylab_examples/image_origin.py b/examples/pylab_examples/image_origin.py deleted file mode 100644 index a8bb92e12dce..000000000000 --- a/examples/pylab_examples/image_origin.py +++ /dev/null @@ -1,23 +0,0 @@ -""" -============ -Image Origin -============ - -You can specify whether images should be plotted with the array origin -x[0,0] in the upper left or upper right by using the origin parameter. -You can also control the default be setting image.origin in your -matplotlibrc file; see http://matplotlib.org/matplotlibrc -""" -import matplotlib.pyplot as plt -import numpy as np - -x = np.arange(120).reshape((10, 12)) - -interp = 'bilinear' -fig, axs = plt.subplots(nrows=2, sharex=True, figsize=(3, 5)) -axs[0].set_title('blue should be up') -axs[0].imshow(x, origin='upper', interpolation=interp) - -axs[1].set_title('blue should be down') -axs[1].imshow(x, origin='lower', interpolation=interp) -plt.show() diff --git a/examples/pylab_examples/legend_demo2.py b/examples/pylab_examples/legend_demo2.py deleted file mode 100644 index 7368e5967b64..000000000000 --- a/examples/pylab_examples/legend_demo2.py +++ /dev/null @@ -1,26 +0,0 @@ -""" -============ -Legend Demo2 -============ - -Make a legend for specific lines. -""" -import matplotlib.pyplot as plt -import numpy as np - - -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 into l1 using tuple -# unpacking. So l1 is a Line2D instance, not a sequence of lines -l1, = plt.plot(t2, np.exp(-t2)) -l2, l3 = plt.plot(t2, np.sin(2 * np.pi * t2), '--o', t1, np.log(1 + t1), '.') -l4, = plt.plot(t2, np.exp(-t2) * np.sin(2 * np.pi * t2), 's-.') - -plt.legend((l2, l4), ('oscillatory', 'damped'), loc='upper right', shadow=True) -plt.xlabel('time') -plt.ylabel('volts') -plt.title('Damped oscillation') -plt.show() diff --git a/examples/pylab_examples/legend_demo3.py b/examples/pylab_examples/legend_demo3.py deleted file mode 100644 index 5efad0ae7780..000000000000 --- a/examples/pylab_examples/legend_demo3.py +++ /dev/null @@ -1,28 +0,0 @@ -""" -============ -Legend Demo3 -============ - -""" -import matplotlib.pyplot as plt -import numpy as np - -x = np.linspace(0, 1) - -# Plot the lines y=x**n for n=1..4. -ax = plt.subplot(2, 1, 1) -for n in range(1, 5): - plt.plot(x, x**n, label="n={0}".format(n)) -plt.legend(loc="upper left", bbox_to_anchor=[0, 1], - ncol=2, shadow=True, title="Legend", fancybox=True) -ax.get_legend().get_title().set_color("red") - -# Demonstrate some more complex labels. -ax = plt.subplot(2, 1, 2) -plt.plot(x, x**2, label="multi\nline") -half_pi = np.linspace(0, np.pi / 2) -plt.plot(np.sin(half_pi), np.cos(half_pi), label=r"$\frac{1}{2}\pi$") -plt.plot(x, 2**(x**2), label="$2^{x^2}$") -plt.legend(shadow=True, fancybox=True) - -plt.show() diff --git a/examples/pylab_examples/legend_demo4.py b/examples/pylab_examples/legend_demo4.py deleted file mode 100644 index f767399601c7..000000000000 --- a/examples/pylab_examples/legend_demo4.py +++ /dev/null @@ -1,28 +0,0 @@ -""" -============ -Legend Demo4 -============ - -""" -import matplotlib.pyplot as plt - -fig, axes = plt.subplots(3, 1) -top_ax, middle_ax, bottom_ax = axes - -top_ax.bar([0, 1, 2], [0.2, 0.3, 0.1], width=0.4, label="Bar 1", - align="center") -top_ax.bar([0.5, 1.5, 2.5], [0.3, 0.2, 0.2], color="red", width=0.4, - label="Bar 2", align="center") -top_ax.legend() - -middle_ax.errorbar([0, 1, 2], [2, 3, 1], xerr=0.4, fmt="s", label="test 1") -middle_ax.errorbar([0, 1, 2], [3, 2, 4], yerr=0.3, fmt="o", label="test 2") -middle_ax.errorbar([0, 1, 2], [1, 1, 3], xerr=0.4, yerr=0.3, fmt="^", - label="test 3") -middle_ax.legend() - -bottom_ax.stem([0.3, 1.5, 2.7], [1, 3.6, 2.7], label="stem test") -bottom_ax.legend() - -plt.subplots_adjust(hspace=0.7) -plt.show() diff --git a/examples/pylab_examples/legend_demo5.py b/examples/pylab_examples/legend_demo5.py deleted file mode 100644 index 5d9db97af2a2..000000000000 --- a/examples/pylab_examples/legend_demo5.py +++ /dev/null @@ -1,77 +0,0 @@ -""" -============ -Legend Demo5 -============ - -""" -from __future__ import (absolute_import, division, - print_function, unicode_literals) -import six -from matplotlib import pyplot as plt -import numpy as np -from matplotlib.legend_handler import HandlerLineCollection -import matplotlib.collections as mcol -from matplotlib.lines import Line2D - - -class HandlerDashedLines(HandlerLineCollection): - """ - Custom Handler for LineCollection instances. - """ - def create_artists(self, legend, orig_handle, - xdescent, ydescent, width, height, fontsize, trans): - # figure out how many lines there are - numlines = len(orig_handle.get_segments()) - xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, - width, height, fontsize) - leglines = [] - # divide the vertical space where the lines will go - # into equal parts based on the number of lines - ydata = ((height) / (numlines + 1)) * np.ones(xdata.shape, float) - # for each line, create the line at the proper location - # and set the dash pattern - for i in range(numlines): - legline = Line2D(xdata, ydata * (numlines - i) - ydescent) - self.update_prop(legline, orig_handle, legend) - # set color, dash pattern, and linewidth to that - # of the lines in linecollection - try: - color = orig_handle.get_colors()[i] - except IndexError: - color = orig_handle.get_colors()[0] - try: - dashes = orig_handle.get_dashes()[i] - except IndexError: - dashes = orig_handle.get_dashes()[0] - try: - lw = orig_handle.get_linewidths()[i] - except IndexError: - lw = orig_handle.get_linewidths()[0] - if dashes[0] is not None: - legline.set_dashes(dashes[1]) - legline.set_color(color) - legline.set_transform(trans) - legline.set_linewidth(lw) - leglines.append(legline) - return leglines - -x = np.linspace(0, 5, 100) - -plt.figure() -colors = plt.rcParams['axes.prop_cycle'].by_key()['color'][:5] -styles = ['solid', 'dashed', 'dashed', 'dashed', 'solid'] -lines = [] -for i, color, style in zip(range(5), colors, styles): - plt.plot(x, np.sin(x) - .1 * i, c=color, ls=style) - - -# make proxy artists -# make list of one line -- doesn't matter what the coordinates are -line = [[(0, 0)]] -# set up the proxy artist -lc = mcol.LineCollection(5 * line, linestyles=styles, colors=colors) -# create the legend -plt.legend([lc], ['multi-line'], handler_map={type(lc): HandlerDashedLines()}, - handlelength=2.5, handleheight=3) - -plt.show() diff --git a/examples/pylab_examples/legend_demo6.py b/examples/pylab_examples/legend_demo6.py deleted file mode 100644 index 51f8d4ed2d5b..000000000000 --- a/examples/pylab_examples/legend_demo6.py +++ /dev/null @@ -1,39 +0,0 @@ -""" -============ -Legend Demo6 -============ - -Showcases legend entries with more than one legend key. -""" -import matplotlib.pyplot as plt -from matplotlib.legend_handler import HandlerTuple - -fig, (ax1, ax2) = plt.subplots(2, 1) - -# First plot: two legend keys for a single entry -p1 = ax1.scatter([1], [5], c='r', marker='s', s=100) -p2 = ax1.scatter([3], [2], c='b', marker='o', s=100) -# `plot` returns a list, but we want the handle - thus the comma on the left -p3, = ax1.plot([1, 5], [4, 4], 'm-d') - -# Assign two of the handles to the same legend entry by putting them in a tuple -# and using a generic handler map (which would be used for any additional -# tuples of handles like (p1, p3)). -l = ax1.legend([(p1, p3), p2], ['two keys', 'one key'], scatterpoints=1, - numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)}) - -# Second plot: plot two bar charts on top of each other and change the padding -# between the legend keys -x_left = [1, 2, 3] -y_pos = [1, 3, 2] -y_neg = [2, 1, 4] - -rneg = ax2.bar(x_left, y_neg, width=0.5, color='w', hatch='///', label='-1') -rpos = ax2.bar(x_left, y_pos, width=0.5, color='k', label='+1') - -# Treat each legend entry differently by using specific `HandlerTuple`s -l = ax2.legend([(rpos, rneg), (rneg, rpos)], ['pad!=0', 'pad=0'], - handler_map={(rpos, rneg): HandlerTuple(ndivide=None), - (rneg, rpos): HandlerTuple(ndivide=None, pad=0.)}) - -plt.show() diff --git a/examples/pylab_examples/line_collection.py b/examples/pylab_examples/line_collection.py index 0814631d9507..211285027d77 100644 --- a/examples/pylab_examples/line_collection.py +++ b/examples/pylab_examples/line_collection.py @@ -3,6 +3,10 @@ Line Collection =============== +Plotting lines with Matplotlib. + +:class:`matplotlib.collections.LineCollection` allows one to plot multiple +lines on a figure. Below we show off some of its properties. """ import matplotlib.pyplot as plt from matplotlib.collections import LineCollection @@ -35,7 +39,7 @@ # solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq) # where onoffseq is an even length tuple of on and off ink in points. # If linestyle is omitted, 'solid' is used -# See matplotlib.collections.LineCollection for more information +# See :class:`matplotlib.collections.LineCollection` for more information colors = [mcolors.to_rgba(c) for c in plt.rcParams['axes.prop_cycle'].by_key()['color']] @@ -44,3 +48,38 @@ ax.add_collection(line_segments) ax.set_title('Line collection with masked arrays') plt.show() + +############################################################################### +# In order to efficiently plot many lines in a single set of axes, +# Matplotlib has the ability to add the lines all at once. Here is a +# simple example showing how it is done. + +N = 50 +x = np.arange(N) +# Here are many sets of y to plot vs x +ys = [x + i for i in x] + +# We need to set the plot limits, they will not autoscale +ax = plt.axes() +ax.set_xlim(np.min(x), np.max(x)) +ax.set_ylim(np.min(ys), np.max(ys)) + +# colors is sequence of rgba tuples +# linestyle is a string or dash tuple. Legal string values are +# solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq) +# where onoffseq is an even length tuple of on and off ink in points. +# If linestyle is omitted, 'solid' is used +# See :class:`matplotlib.collections.LineCollection` for more information + +# Make a sequence of x,y pairs +line_segments = LineCollection([list(zip(x, y)) for y in ys], + linewidths=(0.5, 1, 1.5, 2), + linestyles='solid') +line_segments.set_array(x) +ax.add_collection(line_segments) +fig = plt.gcf() +axcb = fig.colorbar(line_segments) +axcb.set_label('Line Number') +ax.set_title('Line Collection with mapped colors') +plt.sci(line_segments) # This allows interactive changing of the colormap. +plt.show() diff --git a/examples/pylab_examples/line_collection2.py b/examples/pylab_examples/line_collection2.py deleted file mode 100644 index 71b34d9e46c8..000000000000 --- a/examples/pylab_examples/line_collection2.py +++ /dev/null @@ -1,43 +0,0 @@ -""" -================ -Line Collection2 -================ - -""" -import matplotlib.pyplot as plt -import numpy as np -from matplotlib.collections import LineCollection - -# In order to efficiently plot many lines in a single set of axes, -# Matplotlib has the ability to add the lines all at once. Here is a -# simple example showing how it is done. - -N = 50 -x = np.arange(N) -# Here are many sets of y to plot vs x -ys = [x + i for i in x] - -# We need to set the plot limits, they will not autoscale -ax = plt.axes() -ax.set_xlim(np.min(x), np.max(x)) -ax.set_ylim(np.min(ys), np.max(ys)) - -# colors is sequence of rgba tuples -# linestyle is a string or dash tuple. Legal string values are -# solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq) -# where onoffseq is an even length tuple of on and off ink in points. -# If linestyle is omitted, 'solid' is used -# See matplotlib.collections.LineCollection for more information - -# Make a sequence of x,y pairs -line_segments = LineCollection([list(zip(x, y)) for y in ys], - linewidths=(0.5, 1, 1.5, 2), - linestyles='solid') -line_segments.set_array(x) -ax.add_collection(line_segments) -fig = plt.gcf() -axcb = fig.colorbar(line_segments) -axcb.set_label('Line Number') -ax.set_title('Line Collection with mapped colors') -plt.sci(line_segments) # This allows interactive changing of the colormap. -plt.show() diff --git a/examples/pylab_examples/major_minor_demo1.py b/examples/pylab_examples/major_minor_demo.py similarity index 61% rename from examples/pylab_examples/major_minor_demo1.py rename to examples/pylab_examples/major_minor_demo.py index 9b216626a4fe..76561779b3b6 100644 --- a/examples/pylab_examples/major_minor_demo1.py +++ b/examples/pylab_examples/major_minor_demo.py @@ -1,7 +1,7 @@ """ -================= -Major Minor Demo1 -================= +================ +Major Minor Demo +================ Demonstrate how to use major and minor tickers. @@ -35,7 +35,8 @@ import matplotlib.pyplot as plt import numpy as np -from matplotlib.ticker import MultipleLocator, FormatStrFormatter +from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, + AutoMinorLocator) majorLocator = MultipleLocator(20) majorFormatter = FormatStrFormatter('%d') @@ -55,3 +56,32 @@ ax.xaxis.set_minor_locator(minorLocator) plt.show() + +############################################################################### +# Automatic tick selection for major and minor ticks. +# +# Use interactive pan and zoom to see how the tick intervals +# change. There will be either 4 or 5 minor tick intervals +# per major interval, depending on the major interval. +# +# One can supply an argument to AutoMinorLocator to +# specify a fixed number of minor intervals per major interval, e.g.: +# minorLocator = AutoMinorLocator(2) +# would lead to a single minor tick between major ticks. + +minorLocator = AutoMinorLocator() + + +t = np.arange(0.0, 100.0, 0.01) +s = np.sin(2*np.pi*t)*np.exp(-t*0.01) + +fig, ax = plt.subplots() +plt.plot(t, s) + +ax.xaxis.set_minor_locator(minorLocator) + +plt.tick_params(which='both', width=2) +plt.tick_params(which='major', length=7) +plt.tick_params(which='minor', length=4, color='r') + +plt.show() diff --git a/examples/pylab_examples/major_minor_demo2.py b/examples/pylab_examples/major_minor_demo2.py deleted file mode 100644 index f79413800eae..000000000000 --- a/examples/pylab_examples/major_minor_demo2.py +++ /dev/null @@ -1,37 +0,0 @@ -""" -================= -Major Minor Demo2 -================= - -Automatic tick selection for major and minor ticks. - -Use interactive pan and zoom to see how the tick intervals -change. There will be either 4 or 5 minor tick intervals -per major interval, depending on the major interval. -""" - -import numpy as np -import matplotlib.pyplot as plt -from matplotlib.ticker import AutoMinorLocator - -# One can supply an argument to AutoMinorLocator to -# specify a fixed number of minor intervals per major interval, e.g.: -# minorLocator = AutoMinorLocator(2) -# would lead to a single minor tick between major ticks. - -minorLocator = AutoMinorLocator() - - -t = np.arange(0.0, 100.0, 0.01) -s = np.sin(2*np.pi*t)*np.exp(-t*0.01) - -fig, ax = plt.subplots() -plt.plot(t, s) - -ax.xaxis.set_minor_locator(minorLocator) - -plt.tick_params(which='both', width=2) -plt.tick_params(which='major', length=7) -plt.tick_params(which='minor', length=4, color='r') - -plt.show() diff --git a/examples/pylab_examples/pcolor_demo.py b/examples/pylab_examples/pcolor_demo.py index 38a962f04246..993560ee33e3 100644 --- a/examples/pylab_examples/pcolor_demo.py +++ b/examples/pylab_examples/pcolor_demo.py @@ -3,12 +3,39 @@ Pcolor Demo =========== -Demonstrates similarities between pcolor, pcolormesh, imshow and pcolorfast -for drawing quadrilateral grids. +Generating images with pcolor. +Pcolor allows you to generate 2-D image-style plots. Below we will show how +to do so in Matplotlib. """ import matplotlib.pyplot as plt import numpy as np +from numpy.random import rand +from matplotlib.colors import LogNorm +from matplotlib.mlab import bivariate_normal + +############################################################################### +# A simple pcolor demo +# -------------------- + +Z = rand(6, 10) + +plt.subplot(2, 1, 1) +c = plt.pcolor(Z) +plt.title('default: no edges') + +plt.subplot(2, 1, 2) +c = plt.pcolor(Z, edgecolors='k', linewidths=4) +plt.title('thick edges') + +plt.show() + +############################################################################### +# Comparing pcolor with similar functions +# --------------------------------------- +# +# Demonstrates similarities between pcolor, pcolormesh, imshow and pcolorfast +# for drawing quadrilateral grids. # make these smaller to increase the resolution dx, dy = 0.15, 0.05 @@ -55,3 +82,28 @@ plt.subplots_adjust(wspace=0.5, hspace=0.5) plt.show() + + +############################################################################### +# Pcolor with a log scale +# ----------------------- +# +# The following shows pcolor plots with a log scale. + +N = 100 +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) + +plt.subplot(2, 1, 1) +plt.pcolor(X, Y, Z1, norm=LogNorm(vmin=Z1.min(), vmax=Z1.max()), cmap='PuBu_r') +plt.colorbar() + +plt.subplot(2, 1, 2) +plt.pcolor(X, Y, Z1, cmap='PuBu_r') +plt.colorbar() + +plt.show() diff --git a/examples/pylab_examples/pcolor_log.py b/examples/pylab_examples/pcolor_log.py deleted file mode 100644 index 0ae6e26c30b1..000000000000 --- a/examples/pylab_examples/pcolor_log.py +++ /dev/null @@ -1,30 +0,0 @@ -""" -========== -Pcolor Log -========== - -""" -import matplotlib.pyplot as plt -from matplotlib.colors import LogNorm -import numpy as np -from matplotlib.mlab import bivariate_normal - - -N = 100 -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) - -plt.subplot(2, 1, 1) -plt.pcolor(X, Y, Z1, norm=LogNorm(vmin=Z1.min(), vmax=Z1.max()), cmap='PuBu_r') -plt.colorbar() - -plt.subplot(2, 1, 2) -plt.pcolor(X, Y, Z1, cmap='PuBu_r') -plt.colorbar() - - -plt.show() diff --git a/examples/pylab_examples/pcolor_small.py b/examples/pylab_examples/pcolor_small.py deleted file mode 100644 index 60f20cc4bcb0..000000000000 --- a/examples/pylab_examples/pcolor_small.py +++ /dev/null @@ -1,20 +0,0 @@ -""" -============ -Pcolor Small -============ - -""" -import matplotlib.pyplot as plt -from numpy.random import rand - -Z = rand(6, 10) - -plt.subplot(2, 1, 1) -c = plt.pcolor(Z) -plt.title('default: no edges') - -plt.subplot(2, 1, 2) -c = plt.pcolor(Z, edgecolors='k', linewidths=4) -plt.title('thick edges') - -plt.show() diff --git a/examples/pylab_examples/psd_demo.py b/examples/pylab_examples/psd_demo.py index 50475b1689c8..ba7cda9c086e 100644 --- a/examples/pylab_examples/psd_demo.py +++ b/examples/pylab_examples/psd_demo.py @@ -3,9 +3,15 @@ Psd Demo ======== +Plotting Power Spectral Density (PSD) in Matplotlib. + +The PSD is a common plot in the field of signal processing. Numpy has +many useful libraries for computing a PSD. Below we demo a few examples +of how this can be accomplished and visualized with Matplotlib. """ import matplotlib.pyplot as plt import numpy as np +import matplotlib.mlab as mlab # Fixing random state for reproducibility np.random.seed(19680801) @@ -27,19 +33,140 @@ plt.show() -""" -% compare with MATLAB -dt = 0.01; -t = [0:dt:10]; -nse = randn(size(t)); -r = exp(-t/0.05); -cnse = conv(nse, r)*dt; -cnse = cnse(1:length(t)); -s = 0.1*sin(2*pi*t) + cnse; - -subplot(211) -plot(t,s) -subplot(212) -psd(s, 512, 1/dt) +############################################################################### +# Compare this with the equivalent Matlab code to accomplish the same thing:: +# +# dt = 0.01; +# t = [0:dt:10]; +# nse = randn(size(t)); +# r = exp(-t/0.05); +# cnse = conv(nse, r)*dt; +# cnse = cnse(1:length(t)); +# s = 0.1*sin(2*pi*t) + cnse; +# +# subplot(211) +# plot(t,s) +# subplot(212) +# psd(s, 512, 1/dt) +# +# Below we'll show a slightly more complex example that demonstrates +# how padding affects the resulting PSD. -""" +dt = np.pi / 100. +fs = 1. / dt +t = np.arange(0, 8, dt) +y = 10. * np.sin(2 * np.pi * 4 * t) + 5. * np.sin(2 * np.pi * 4.25 * t) +y = y + np.random.randn(*t.shape) + +# Plot the raw time series +fig = plt.figure() +fig.subplots_adjust(hspace=0.45, wspace=0.3) +ax = fig.add_subplot(2, 1, 1) +ax.plot(t, y) + +# Plot the PSD with different amounts of zero padding. This uses the entire +# time series at once +ax2 = fig.add_subplot(2, 3, 4) +ax2.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs) +ax2.psd(y, NFFT=len(t), pad_to=len(t)*2, Fs=fs) +ax2.psd(y, NFFT=len(t), pad_to=len(t)*4, Fs=fs) +plt.title('zero padding') + +# Plot the PSD with different block sizes, Zero pad to the length of the +# original data sequence. +ax3 = fig.add_subplot(2, 3, 5, sharex=ax2, sharey=ax2) +ax3.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs) +ax3.psd(y, NFFT=len(t)//2, pad_to=len(t), Fs=fs) +ax3.psd(y, NFFT=len(t)//4, pad_to=len(t), Fs=fs) +ax3.set_ylabel('') +plt.title('block size') + +# Plot the PSD with different amounts of overlap between blocks +ax4 = fig.add_subplot(2, 3, 6, sharex=ax2, sharey=ax2) +ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=0, Fs=fs) +ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.05*len(t)/2.), Fs=fs) +ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.2*len(t)/2.), Fs=fs) +ax4.set_ylabel('') +plt.title('overlap') + +plt.show() + + +############################################################################### +# This is a ported version of a MATLAB example from the signal +# processing toolbox that showed some difference at one time between +# Matplotlib's and MATLAB's scaling of the PSD. + +fs = 1000 +t = np.linspace(0, 0.3, 301) +A = np.array([2, 8]).reshape(-1, 1) +f = np.array([150, 140]).reshape(-1, 1) +xn = (A * np.sin(2 * np.pi * f * t)).sum(axis=0) +xn += 5 * np.random.randn(*t.shape) + +fig, (ax0, ax1) = plt.subplots(ncols=2) + +fig.subplots_adjust(hspace=0.45, wspace=0.3) +yticks = np.arange(-50, 30, 10) +yrange = (yticks[0], yticks[-1]) +xticks = np.arange(0, 550, 100) + +ax0.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024, + scale_by_freq=True) +ax0.set_title('Periodogram') +ax0.set_yticks(yticks) +ax0.set_xticks(xticks) +ax0.grid(True) +ax0.set_ylim(yrange) + +ax1.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, pad_to=512, noverlap=75, + scale_by_freq=True) +ax1.set_title('Welch') +ax1.set_xticks(xticks) +ax1.set_yticks(yticks) +ax1.set_ylabel('') # overwrite the y-label added by `psd` +ax1.grid(True) +ax1.set_ylim(yrange) + +plt.show() + +############################################################################### +# This is a ported version of a MATLAB example from the signal +# processing toolbox that showed some difference at one time between +# Matplotlib's and MATLAB's scaling of the PSD. +# +# It uses a complex signal so we can see that complex PSD's work properly. + +prng = np.random.RandomState(19680801) # to ensure reproducibility + +fs = 1000 +t = np.linspace(0, 0.3, 301) +A = np.array([2, 8]).reshape(-1, 1) +f = np.array([150, 140]).reshape(-1, 1) +xn = (A * np.exp(2j * np.pi * f * t)).sum(axis=0) + 5 * prng.randn(*t.shape) + +fig, (ax0, ax1) = plt.subplots(ncols=2) + +fig.subplots_adjust(hspace=0.45, wspace=0.3) +yticks = np.arange(-50, 30, 10) +yrange = (yticks[0], yticks[-1]) +xticks = np.arange(-500, 550, 200) + +ax0.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024, + scale_by_freq=True) +ax0.set_title('Periodogram') +ax0.set_yticks(yticks) +ax0.set_xticks(xticks) +ax0.grid(True) +ax0.set_ylim(yrange) + +ax1.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, pad_to=512, noverlap=75, + scale_by_freq=True) +ax1.set_title('Welch') +ax1.set_xticks(xticks) +ax1.set_yticks(yticks) +ax1.set_ylabel('') # overwrite the y-label added by `psd` +ax1.grid(True) +ax1.set_ylim(yrange) + +plt.show() diff --git a/examples/pylab_examples/psd_demo2.py b/examples/pylab_examples/psd_demo2.py deleted file mode 100644 index 33d3c1ba0513..000000000000 --- a/examples/pylab_examples/psd_demo2.py +++ /dev/null @@ -1,52 +0,0 @@ -""" -========= -Psd Demo2 -========= - -This example shows the effects of some of the different PSD parameters -""" -import numpy as np -import matplotlib.pyplot as plt - -# Fixing random state for reproducibility -np.random.seed(19680801) - - -dt = np.pi / 100. -fs = 1. / dt -t = np.arange(0, 8, dt) -y = 10. * np.sin(2 * np.pi * 4 * t) + 5. * np.sin(2 * np.pi * 4.25 * t) -y = y + np.random.randn(*t.shape) - -# Plot the raw time series -fig = plt.figure() -fig.subplots_adjust(hspace=0.45, wspace=0.3) -ax = fig.add_subplot(2, 1, 1) -ax.plot(t, y) - -# Plot the PSD with different amounts of zero padding. This uses the entire -# time series at once -ax2 = fig.add_subplot(2, 3, 4) -ax2.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs) -ax2.psd(y, NFFT=len(t), pad_to=len(t)*2, Fs=fs) -ax2.psd(y, NFFT=len(t), pad_to=len(t)*4, Fs=fs) -plt.title('zero padding') - -# Plot the PSD with different block sizes, Zero pad to the length of the -# original data sequence. -ax3 = fig.add_subplot(2, 3, 5, sharex=ax2, sharey=ax2) -ax3.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs) -ax3.psd(y, NFFT=len(t)//2, pad_to=len(t), Fs=fs) -ax3.psd(y, NFFT=len(t)//4, pad_to=len(t), Fs=fs) -ax3.set_ylabel('') -plt.title('block size') - -# Plot the PSD with different amounts of overlap between blocks -ax4 = fig.add_subplot(2, 3, 6, sharex=ax2, sharey=ax2) -ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=0, Fs=fs) -ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.05*len(t)/2.), Fs=fs) -ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.2*len(t)/2.), Fs=fs) -ax4.set_ylabel('') -plt.title('overlap') - -plt.show() diff --git a/examples/pylab_examples/psd_demo3.py b/examples/pylab_examples/psd_demo3.py deleted file mode 100644 index 68506b3a23bf..000000000000 --- a/examples/pylab_examples/psd_demo3.py +++ /dev/null @@ -1,49 +0,0 @@ -""" -========= -Psd Demo3 -========= - -This is a ported version of a MATLAB example from the signal -processing toolbox that showed some difference at one time between -Matplotlib's and MATLAB's scaling of the PSD. - -""" - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib.mlab as mlab - -prng = np.random.RandomState(19680801) # to ensure reproducibility - - -fs = 1000 -t = np.linspace(0, 0.3, 301) -A = np.array([2, 8]).reshape(-1, 1) -f = np.array([150, 140]).reshape(-1, 1) -xn = (A * np.sin(2 * np.pi * f * t)).sum(axis=0) + 5 * prng.randn(*t.shape) - -fig, (ax0, ax1) = plt.subplots(ncols=2) - -fig.subplots_adjust(hspace=0.45, wspace=0.3) -yticks = np.arange(-50, 30, 10) -yrange = (yticks[0], yticks[-1]) -xticks = np.arange(0, 550, 100) - -ax0.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024, - scale_by_freq=True) -ax0.set_title('Periodogram') -ax0.set_yticks(yticks) -ax0.set_xticks(xticks) -ax0.grid(True) -ax0.set_ylim(yrange) - -ax1.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, pad_to=512, noverlap=75, - scale_by_freq=True) -ax1.set_title('Welch') -ax1.set_xticks(xticks) -ax1.set_yticks(yticks) -ax1.set_ylabel('') # overwrite the y-label added by `psd` -ax1.grid(True) -ax1.set_ylim(yrange) - -plt.show() diff --git a/examples/pylab_examples/psd_demo_complex.py b/examples/pylab_examples/psd_demo_complex.py deleted file mode 100644 index 75760327523c..000000000000 --- a/examples/pylab_examples/psd_demo_complex.py +++ /dev/null @@ -1,51 +0,0 @@ -""" -================ -Psd Demo Complex -================ - -This is a ported version of a MATLAB example from the signal -processing toolbox that showed some difference at one time between -Matplotlib's and MATLAB's scaling of the PSD. - -This differs from psd_demo3.py in that this uses a complex signal, -so we can see that complex PSD's work properly - -""" - -import numpy as np -import matplotlib.pyplot as plt -import matplotlib.mlab as mlab - -prng = np.random.RandomState(19680801) # to ensure reproducibility - -fs = 1000 -t = np.linspace(0, 0.3, 301) -A = np.array([2, 8]).reshape(-1, 1) -f = np.array([150, 140]).reshape(-1, 1) -xn = (A * np.exp(2j * np.pi * f * t)).sum(axis=0) + 5 * prng.randn(*t.shape) - -fig, (ax0, ax1) = plt.subplots(ncols=2) - -fig.subplots_adjust(hspace=0.45, wspace=0.3) -yticks = np.arange(-50, 30, 10) -yrange = (yticks[0], yticks[-1]) -xticks = np.arange(-500, 550, 200) - -ax0.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024, - scale_by_freq=True) -ax0.set_title('Periodogram') -ax0.set_yticks(yticks) -ax0.set_xticks(xticks) -ax0.grid(True) -ax0.set_ylim(yrange) - -ax1.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, pad_to=512, noverlap=75, - scale_by_freq=True) -ax1.set_title('Welch') -ax1.set_xticks(xticks) -ax1.set_yticks(yticks) -ax1.set_ylabel('') # overwrite the y-label added by `psd` -ax1.grid(True) -ax1.set_ylim(yrange) - -plt.show() diff --git a/examples/pylab_examples/stackplot_demo.py b/examples/pylab_examples/stackplot_demo.py index 8d25970954a0..609c0d0c1902 100644 --- a/examples/pylab_examples/stackplot_demo.py +++ b/examples/pylab_examples/stackplot_demo.py @@ -3,6 +3,11 @@ Stackplot Demo ============== +How to create stackplots with Matplotlib. + +Stackplots are generated by plotting different datasets vertically on +top of one another rather than overlapping with one another. Below we +show some examples to accomplish this with Matplotlib. """ import numpy as np import matplotlib.pyplot as plt @@ -26,3 +31,30 @@ def fnx(): fig, ax = plt.subplots() ax.stackplot(x, y1, y2, y3) plt.show() + +############################################################################### +# Here we'll show a slightly more complex example. + + +def layers(n, m): + """ + Return *n* random Gaussian mixtures, each of length *m*. + """ + def bump(a): + x = 1 / (.1 + np.random.random()) + y = 2 * np.random.random() - .5 + z = 10 / (.1 + np.random.random()) + for i in range(m): + w = (i / float(m) - y) * z + a[i] += x * np.exp(-w * w) + a = np.zeros((m, n)) + for i in range(n): + for j in range(5): + bump(a[:, i]) + return a + +d = layers(3, 100) + +plt.subplots() +plt.stackplot(range(100), d.T, baseline='wiggle') +plt.show() diff --git a/examples/pylab_examples/stackplot_demo2.py b/examples/pylab_examples/stackplot_demo2.py deleted file mode 100644 index d42248330527..000000000000 --- a/examples/pylab_examples/stackplot_demo2.py +++ /dev/null @@ -1,35 +0,0 @@ -""" -=============== -Stackplot Demo2 -=============== - -""" -import numpy as np -import matplotlib.pyplot as plt - -# Fixing random state for reproducibility -np.random.seed(19680801) - - -def layers(n, m): - """ - Return *n* random Gaussian mixtures, each of length *m*. - """ - def bump(a): - x = 1 / (.1 + np.random.random()) - y = 2 * np.random.random() - .5 - z = 10 / (.1 + np.random.random()) - for i in range(m): - w = (i / float(m) - y) * z - a[i] += x * np.exp(-w * w) - a = np.zeros((m, n)) - for i in range(n): - for j in range(5): - bump(a[:, i]) - return a - -d = layers(3, 100) - -plt.subplots() -plt.stackplot(range(100), d.T, baseline='wiggle') -plt.show() diff --git a/examples/pylab_examples/barchart_demo2.py b/examples/statistics/barchart_demo.py similarity index 76% rename from examples/pylab_examples/barchart_demo2.py rename to examples/statistics/barchart_demo.py index 56da16ea786e..42123185fb9b 100644 --- a/examples/pylab_examples/barchart_demo2.py +++ b/examples/statistics/barchart_demo.py @@ -1,25 +1,69 @@ """ -============== -Barchart Demo2 -============== +============= +Barchart Demo +============= -Thanks Josh Hemann for the example +Bar charts of many shapes and sizes with Matplotlib. -This examples comes from an application in which grade school gym -teachers wanted to be able to show parents how their child did across -a handful of fitness tests, and importantly, relative to how other -children did. To extract the plotting code for demo purposes, we'll -just make up some data for little Johnny Doe... +Bar charts are useful for visualizing counts, or summary statistics +with error bars. These examples show a few ways to do this with Matplotlib. """ + +# Credit: Josh Hemann + import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from collections import namedtuple -# Fixing random state for reproducibility -np.random.seed(19680801) +n_groups = 5 + +means_men = (20, 35, 30, 35, 27) +std_men = (2, 3, 4, 1, 2) + +means_women = (25, 32, 34, 20, 25) +std_women = (3, 5, 2, 3, 3) + +fig, ax = plt.subplots() + +index = np.arange(n_groups) +bar_width = 0.35 + +opacity = 0.4 +error_config = {'ecolor': '0.3'} + +rects1 = plt.bar(index, means_men, bar_width, + alpha=opacity, + color='b', + yerr=std_men, + error_kw=error_config, + label='Men') + +rects2 = plt.bar(index + bar_width, means_women, bar_width, + alpha=opacity, + color='r', + yerr=std_women, + error_kw=error_config, + label='Women') + +plt.xlabel('Group') +plt.ylabel('Scores') +plt.title('Scores by group and gender') +plt.xticks(index + bar_width / 2, ('A', 'B', 'C', 'D', 'E')) +plt.legend() + +plt.tight_layout() +plt.show() + + +############################################################################### +# This example comes from an application in which grade school gym +# teachers wanted to be able to show parents how their child did across +# a handful of fitness tests, and importantly, relative to how other +# children did. To extract the plotting code for demo purposes, we'll +# just make up some data for little Johnny Doe... Student = namedtuple('Student', ['name', 'grade', 'gender']) Score = namedtuple('Score', ['score', 'percentile']) diff --git a/examples/pylab_examples/boxplot_demo2.py b/examples/statistics/boxplot_demo.py similarity index 59% rename from examples/pylab_examples/boxplot_demo2.py rename to examples/statistics/boxplot_demo.py index ce5f79dc8ca9..b8893e5c81f3 100644 --- a/examples/pylab_examples/boxplot_demo2.py +++ b/examples/statistics/boxplot_demo.py @@ -1,29 +1,86 @@ """ -============= -Boxplot Demo2 -============= +======== +Boxplots +======== -Thanks Josh Hemann for the example -""" +Visualizing boxplots with matplotlib. -import numpy as np +The following examples show off how to visualize boxplots with +Matplotlib. There are many options to control their appearance and +the statistics that they use to summarize the data. + +""" import matplotlib.pyplot as plt +import numpy as np from matplotlib.patches import Polygon -# Generate some data from five different probability distributions, +# Fixing random state for reproducibility +np.random.seed(19680801) + +# fake up some data +spread = np.random.rand(50) * 100 +center = np.ones(25) * 50 +flier_high = np.random.rand(10) * 100 + 100 +flier_low = np.random.rand(10) * -100 +data = np.concatenate((spread, center, flier_high, flier_low), 0) + +# basic plot +plt.boxplot(data) + +# notched plot +plt.figure() +plt.boxplot(data, 1) + +# change outlier point symbols +plt.figure() +plt.boxplot(data, 0, 'gD') + +# don't show outlier points +plt.figure() +plt.boxplot(data, 0, '') + +# horizontal boxes +plt.figure() +plt.boxplot(data, 0, 'rs', 0) + +# change whisker length +plt.figure() +plt.boxplot(data, 0, 'rs', 0, 0.75) + +# fake up some more data +spread = np.random.rand(50) * 100 +center = np.ones(25) * 40 +flier_high = np.random.rand(10) * 100 + 100 +flier_low = np.random.rand(10) * -100 +d2 = np.concatenate((spread, center, flier_high, flier_low), 0) +data.shape = (-1, 1) +d2.shape = (-1, 1) +# data = concatenate( (data, d2), 1 ) +# Making a 2-D array only works if all the columns are the +# same length. If they are not, then use a list instead. +# This is actually more efficient because boxplot converts +# a 2-D array into a list of vectors internally anyway. +data = [data, d2, d2[::2, 0]] +# multiple box plots on one figure +plt.figure() +plt.boxplot(data) + +plt.show() + + +############################################################################### +# Below we'll generate data from five different probability distributions, # each with different characteristics. We want to play with how an IID # bootstrap resample of the data preserves the distributional # properties of the original sample, and a boxplot is one visual tool # to make this assessment + numDists = 5 randomDists = ['Normal(1,1)', ' Lognormal(1,1)', 'Exp(1)', 'Gumbel(6,4)', 'Triangular(2,9,11)'] N = 500 -# Fixing random state for reproducibility -np.random.seed(19680801) - norm = np.random.normal(1, 1, N) logn = np.random.lognormal(1, 1, N) expo = np.random.exponential(1, N) @@ -126,3 +183,50 @@ size='x-small') plt.show() + +############################################################################### +# Here we write a custom function to bootstrap confidence intervals. +# We can then use the boxplot along with this function to show these intervals. + + +def fakeBootStrapper(n): + ''' + This is just a placeholder for the user's method of + bootstrapping the median and its confidence intervals. + + Returns an arbitrary median and confidence intervals + packed into a tuple + ''' + if n == 1: + med = 0.1 + CI = (-0.25, 0.25) + else: + med = 0.2 + CI = (-0.35, 0.50) + + return med, CI + +inc = 0.1 +e1 = np.random.normal(0, 1, size=(500,)) +e2 = np.random.normal(0, 1, size=(500,)) +e3 = np.random.normal(0, 1 + inc, size=(500,)) +e4 = np.random.normal(0, 1 + 2*inc, size=(500,)) + +treatments = [e1, e2, e3, e4] +med1, CI1 = fakeBootStrapper(1) +med2, CI2 = fakeBootStrapper(2) +medians = [None, None, med1, med2] +conf_intervals = [None, None, CI1, CI2] + +fig, ax = plt.subplots() +pos = np.array(range(len(treatments))) + 1 +bp = ax.boxplot(treatments, sym='k+', positions=pos, + notch=1, bootstrap=5000, + usermedians=medians, + conf_intervals=conf_intervals) + +ax.set_xlabel('treatment') +ax.set_ylabel('response') +plt.setp(bp['whiskers'], color='k', linestyle='-') +plt.setp(bp['fliers'], markersize=3.0) +plt.show() diff --git a/examples/statistics/hexbin_demo.py b/examples/statistics/hexbin_demo.py new file mode 100644 index 000000000000..70333d88b772 --- /dev/null +++ b/examples/statistics/hexbin_demo.py @@ -0,0 +1,96 @@ +""" +=========== +Hexbin Demo +=========== + +Plotting hexbins with Matplotlib. + +Hexbin is an axes method or pyplot function that is essentially +a pcolor of a 2-D histogram with hexagonal cells. It can be +much more informative than a scatter plot. In the first subplot +below, try substituting 'scatter' for 'hexbin'. +""" + +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.mlab as mlab + +# Fixing random state for reproducibility +np.random.seed(19680801) + +n = 100000 +x = np.random.standard_normal(n) +y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n) +xmin = x.min() +xmax = x.max() +ymin = y.min() +ymax = y.max() + +fig, axs = plt.subplots(ncols=2, sharey=True, figsize=(7, 4)) +fig.subplots_adjust(hspace=0.5, left=0.07, right=0.93) +ax = axs[0] +hb = ax.hexbin(x, y, gridsize=50, cmap='inferno') +ax.axis([xmin, xmax, ymin, ymax]) +ax.set_title("Hexagon binning") +cb = fig.colorbar(hb, ax=ax) +cb.set_label('counts') + +ax = axs[1] +hb = ax.hexbin(x, y, gridsize=50, bins='log', cmap='inferno') +ax.axis([xmin, xmax, ymin, ymax]) +ax.set_title("With a log color scale") +cb = fig.colorbar(hb, ax=ax) +cb.set_label('log10(N)') + +plt.show() + + +############################################################################### +# Below we'll simulate some 2-D probability distributions, and show how to +# visualize them with Matplotlib. + +delta = 0.025 +x = y = np.arange(-3.0, 3.0, delta) +X, Y = np.meshgrid(x, y) +Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) +Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) +Z = Z2 - Z1 # difference of Gaussians + +x = X.ravel() +y = Y.ravel() +z = Z.ravel() + +# make some points 20 times more common than others, but same mean +xcond = (-1 < x) & (x < 1) +ycond = (-2 < y) & (y < 0) +cond = xcond & ycond +xnew = x[cond] +ynew = y[cond] +znew = z[cond] +for i in range(20): + x = np.hstack((x, xnew)) + y = np.hstack((y, ynew)) + z = np.hstack((z, znew)) + +xmin = x.min() +xmax = x.max() +ymin = y.min() +ymax = y.max() + +gridsize = 30 + +plt.subplot(211) +plt.hexbin(x, y, C=z, gridsize=gridsize, marginals=True, cmap=plt.cm.RdBu, + vmax=abs(z).max(), vmin=-abs(z).max()) +plt.axis([xmin, xmax, ymin, ymax]) +cb = plt.colorbar() +cb.set_label('mean value') + + +plt.subplot(212) +plt.hexbin(x, y, gridsize=gridsize, cmap=plt.cm.Blues_r) +plt.axis([xmin, xmax, ymin, ymax]) +cb = plt.colorbar() +cb.set_label('N observations') + +plt.show() diff --git a/examples/text_labels_and_annotations/annotation_demo.py b/examples/text_labels_and_annotations/annotation_demo.py new file mode 100644 index 000000000000..9fc9a613a1de --- /dev/null +++ b/examples/text_labels_and_annotations/annotation_demo.py @@ -0,0 +1,395 @@ +""" +================ +Annotating Plots +================ + +The following examples show how it is possible to annotate plots in matplotlib. +This includes highlighting specific points of interest and using various +visual tools to call attention to this point. For a more complete and in-depth +description of the annotation and text tools in :mod:`matplotlib`, see the +`tutorial on annotation `_. +""" + +import matplotlib.pyplot as plt +from matplotlib.patches import Ellipse +import numpy as np +from matplotlib.text import OffsetFrom + + +############################################################################### +# Specifying text points and annotation points +# -------------------------------------------- +# +# You must specify an annotation point `xy=(x,y)` to annotate this point. +# additionally, you may specify a text point `xytext=(x,y)` for the +# location of the text for this annotation. Optionally, you can +# specify the coordinate system of `xy` and `xytext` with one of the +# following strings for `xycoords` and `textcoords` (default is 'data'):: +# +# 'figure points' : points from the lower left corner of the figure +# 'figure pixels' : pixels from the lower left corner of the figure +# 'figure fraction' : 0,0 is lower left of figure and 1,1 is upper, right +# 'axes points' : points from lower left corner of axes +# 'axes pixels' : pixels from lower left corner of axes +# 'axes fraction' : 0,0 is lower left of axes and 1,1 is upper right +# 'offset points' : Specify an offset (in points) from the xy value +# 'offset pixels' : Specify an offset (in pixels) from the xy value +# 'data' : use the axes data coordinate system +# +# Note: for physical coordinate systems (points or pixels) the origin is the +# (bottom, left) of the figure or axes. +# +# Optionally, you can specify arrow properties which draws and arrow +# from the text to the annotated point by giving a dictionary of arrow +# properties +# +# Valid keys are:: +# +# width : the width of the arrow in points +# frac : the fraction of the arrow length occupied by the head +# headwidth : the width of the base of the arrow head in points +# shrink : move the tip and base some percent away from the +# annotated point and text +# any key for matplotlib.patches.polygon (e.g., facecolor) + +# Create our figure and data we'll use for plotting +fig, ax = plt.subplots(figsize=(3, 3)) + +t = np.arange(0.0, 5.0, 0.01) +s = np.cos(2*np.pi*t) + +# Plot a line and add some simple annotations +line, = ax.plot(t, s) +ax.annotate('figure pixels', + xy=(10, 10), xycoords='figure pixels') +ax.annotate('figure points', + xy=(80, 80), xycoords='figure points') +ax.annotate('figure fraction', + xy=(.025, .975), xycoords='figure fraction', + horizontalalignment='left', verticalalignment='top', + fontsize=20) + +# The following examples show off how these arrows are drawn. + +ax.annotate('point offset from data', + xy=(2, 1), xycoords='data', + xytext=(-15, 25), textcoords='offset points', + arrowprops=dict(facecolor='black', shrink=0.05), + horizontalalignment='right', verticalalignment='bottom') + +ax.annotate('axes fraction', + xy=(3, 1), xycoords='data', + xytext=(0.8, 0.95), textcoords='axes fraction', + arrowprops=dict(facecolor='black', shrink=0.05), + horizontalalignment='right', verticalalignment='top') + +# You may also use negative points or pixels to specify from (right, top). +# E.g., (-10, 10) is 10 points to the left of the right side of the axes and 10 +# points above the bottom + +ax.annotate('pixel offset from axes fraction', + xy=(1, 0), xycoords='axes fraction', + xytext=(-20, 20), textcoords='offset pixels', + horizontalalignment='right', + verticalalignment='bottom') + +ax.set(xlim=(-1, 5), ylim=(-3, 5)) + + +############################################################################### +# Using multiple coordinate systems and axis types +# ------------------------------------------------ +# +# You can specify the xypoint and the xytext in different positions and +# coordinate systems, and optionally turn on a connecting line and mark +# the point with a marker. Annotations work on polar axes too. +# +# In the example below, the xy point is in native coordinates (xycoords +# defaults to 'data'). For a polar axes, this is in (theta, radius) space. +# The text in the example is placed in the fractional figure coordinate system. +# Text keyword args like horizontal and vertical alignment are respected. + +fig, ax = plt.subplots(subplot_kw=dict(projection='polar'), figsize=(3, 3)) +r = np.arange(0, 1, 0.001) +theta = 2*2*np.pi*r +line, = ax.plot(theta, r) + +ind = 800 +thisr, thistheta = r[ind], theta[ind] +ax.plot([thistheta], [thisr], 'o') +ax.annotate('a polar annotation', + xy=(thistheta, thisr), # theta, radius + xytext=(0.05, 0.05), # fraction, fraction + textcoords='figure fraction', + arrowprops=dict(facecolor='black', shrink=0.05), + horizontalalignment='left', + verticalalignment='bottom') + +# You can also use polar notation on a cartesian axes. Here the native +# coordinate system ('data') is cartesian, so you need to specify the +# xycoords and textcoords as 'polar' if you want to use (theta, radius). + +el = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5) + +fig, ax = plt.subplots(subplot_kw=dict(aspect='equal')) +ax.add_artist(el) +el.set_clip_box(ax.bbox) +ax.annotate('the top', + xy=(np.pi/2., 10.), # theta, radius + xytext=(np.pi/3, 20.), # theta, radius + xycoords='polar', + textcoords='polar', + arrowprops=dict(facecolor='black', shrink=0.05), + horizontalalignment='left', + verticalalignment='bottom', + clip_on=True) # clip to the axes bounding box + +ax.set(xlim=[-20, 20], ylim=[-20, 20]) + + +############################################################################### +# Customizing arrow and bubble styles +# ----------------------------------- +# +# The arrow between xytext and the annotation point, as well as the bubble +# that covers the annotation text, are highly customizable. Below are a few +# parameter options as well as their resulting output. + +fig, ax = plt.subplots(figsize=(8, 5)) + +t = np.arange(0.0, 5.0, 0.01) +s = np.cos(2*np.pi*t) +line, = ax.plot(t, s, lw=3) + +ax.annotate('straight', + xy=(0, 1), xycoords='data', + xytext=(-50, 30), textcoords='offset points', + arrowprops=dict(arrowstyle="->")) + +ax.annotate('arc3,\nrad 0.2', + xy=(0.5, -1), xycoords='data', + xytext=(-80, -60), textcoords='offset points', + arrowprops=dict(arrowstyle="->", + connectionstyle="arc3,rad=.2")) + +ax.annotate('arc,\nangle 50', + xy=(1., 1), xycoords='data', + xytext=(-90, 50), textcoords='offset points', + arrowprops=dict(arrowstyle="->", + connectionstyle="arc,angleA=0,armA=50,rad=10")) + +ax.annotate('arc,\narms', + xy=(1.5, -1), xycoords='data', + xytext=(-80, -60), textcoords='offset points', + arrowprops=dict(arrowstyle="->", + connectionstyle="arc,angleA=0,armA=40,angleB=-90,armB=30,rad=7")) + +ax.annotate('angle,\nangle 90', + xy=(2., 1), xycoords='data', + xytext=(-70, 30), textcoords='offset points', + arrowprops=dict(arrowstyle="->", + connectionstyle="angle,angleA=0,angleB=90,rad=10")) + +ax.annotate('angle3,\nangle -90', + xy=(2.5, -1), xycoords='data', + xytext=(-80, -60), textcoords='offset points', + arrowprops=dict(arrowstyle="->", + connectionstyle="angle3,angleA=0,angleB=-90")) + +ax.annotate('angle,\nround', + xy=(3., 1), xycoords='data', + xytext=(-60, 30), textcoords='offset points', + bbox=dict(boxstyle="round", fc="0.8"), + arrowprops=dict(arrowstyle="->", + connectionstyle="angle,angleA=0,angleB=90,rad=10")) + +ax.annotate('angle,\nround4', + xy=(3.5, -1), xycoords='data', + xytext=(-70, -80), textcoords='offset points', + size=20, + bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), + arrowprops=dict(arrowstyle="->", + connectionstyle="angle,angleA=0,angleB=-90,rad=10")) + +ax.annotate('angle,\nshrink', + xy=(4., 1), xycoords='data', + xytext=(-60, 30), textcoords='offset points', + bbox=dict(boxstyle="round", fc="0.8"), + arrowprops=dict(arrowstyle="->", + shrinkA=0, shrinkB=10, + connectionstyle="angle,angleA=0,angleB=90,rad=10")) + +# You can pass an empty string to get only annotation arrows rendered +ann = ax.annotate('', xy=(4., 1.), xycoords='data', + xytext=(4.5, -1), textcoords='data', + arrowprops=dict(arrowstyle="<->", + connectionstyle="bar", + ec="k", + shrinkA=5, shrinkB=5)) + +ax.set(xlim=(-1, 5), ylim=(-4, 3)) + +# We'll create another figure so that it doesn't get too cluttered +fig, ax = plt.subplots() + +el = Ellipse((2, -1), 0.5, 0.5) +ax.add_patch(el) + +ax.annotate('$->$', + xy=(2., -1), xycoords='data', + xytext=(-150, -140), textcoords='offset points', + bbox=dict(boxstyle="round", fc="0.8"), + arrowprops=dict(arrowstyle="->", + patchB=el, + connectionstyle="angle,angleA=90,angleB=0,rad=10")) + +ax.annotate('arrow\nfancy', + xy=(2., -1), xycoords='data', + xytext=(-100, 60), textcoords='offset points', + size=20, + # bbox=dict(boxstyle="round", fc="0.8"), + arrowprops=dict(arrowstyle="fancy", + fc="0.6", ec="none", + patchB=el, + connectionstyle="angle3,angleA=0,angleB=-90")) + +ax.annotate('arrow\nsimple', + xy=(2., -1), xycoords='data', + xytext=(100, 60), textcoords='offset points', + size=20, + # bbox=dict(boxstyle="round", fc="0.8"), + arrowprops=dict(arrowstyle="simple", + fc="0.6", ec="none", + patchB=el, + connectionstyle="arc3,rad=0.3")) + +ax.annotate('wedge', + xy=(2., -1), xycoords='data', + xytext=(-100, -100), textcoords='offset points', + size=20, + # bbox=dict(boxstyle="round", fc="0.8"), + arrowprops=dict(arrowstyle="wedge,tail_width=0.7", + fc="0.6", ec="none", + patchB=el, + connectionstyle="arc3,rad=-0.3")) + +ann = ax.annotate('bubble,\ncontours', + xy=(2., -1), xycoords='data', + xytext=(0, -70), textcoords='offset points', + size=20, + bbox=dict(boxstyle="round", + fc=(1.0, 0.7, 0.7), + ec=(1., .5, .5)), + arrowprops=dict(arrowstyle="wedge,tail_width=1.", + fc=(1.0, 0.7, 0.7), ec=(1., .5, .5), + patchA=None, + patchB=el, + relpos=(0.2, 0.8), + connectionstyle="arc3,rad=-0.1")) + +ann = ax.annotate('bubble', + xy=(2., -1), xycoords='data', + xytext=(55, 0), textcoords='offset points', + size=20, va="center", + bbox=dict(boxstyle="round", fc=(1.0, 0.7, 0.7), ec="none"), + arrowprops=dict(arrowstyle="wedge,tail_width=1.", + fc=(1.0, 0.7, 0.7), ec="none", + patchA=None, + patchB=el, + relpos=(0.2, 0.5))) + +ax.set(xlim=(-1, 5), ylim=(-5, 3)) + +############################################################################### +# More examples of coordinate systems +# ----------------------------------- +# +# Below we'll show a few more examples of coordinate systems and how the +# location of annotations may be specified. + +fig, (ax1, ax2) = plt.subplots(1, 2) + +bbox_args = dict(boxstyle="round", fc="0.8") +arrow_args = dict(arrowstyle="->") + +# Here we'll demonstrate the extents of the coordinate system and how +# we place annotating text. + +ax1.annotate('figure fraction : 0, 0', xy=(0, 0), xycoords='figure fraction', + xytext=(20, 20), textcoords='offset points', + ha="left", va="bottom", + bbox=bbox_args, + arrowprops=arrow_args) + +ax1.annotate('figure fraction : 1, 1', xy=(1, 1), xycoords='figure fraction', + xytext=(-20, -20), textcoords='offset points', + ha="right", va="top", + bbox=bbox_args, + arrowprops=arrow_args) + +ax1.annotate('axes fraction : 0, 0', xy=(0, 0), xycoords='axes fraction', + xytext=(20, 20), textcoords='offset points', + ha="left", va="bottom", + bbox=bbox_args, + arrowprops=arrow_args) + +ax1.annotate('axes fraction : 1, 1', xy=(1, 1), xycoords='axes fraction', + xytext=(-20, -20), textcoords='offset points', + ha="right", va="top", + bbox=bbox_args, + arrowprops=arrow_args) + +# It is also possible to generate draggable annotations + +an1 = ax1.annotate('Drag me 1', xy=(.5, .7), xycoords='data', + #xytext=(.5, .7), textcoords='data', + ha="center", va="center", + bbox=bbox_args, + #arrowprops=arrow_args + ) + +an2 = ax1.annotate('Drag me 2', xy=(.5, .5), xycoords=an1, + xytext=(.5, .3), textcoords='axes fraction', + ha="center", va="center", + bbox=bbox_args, + arrowprops=dict(patchB=an1.get_bbox_patch(), + connectionstyle="arc3,rad=0.2", + **arrow_args)) +an1.draggable() +an2.draggable() + +an3 = ax1.annotate('', xy=(.5, .5), xycoords=an2, + xytext=(.5, .5), textcoords=an1, + ha="center", va="center", + bbox=bbox_args, + arrowprops=dict(patchA=an1.get_bbox_patch(), + patchB=an2.get_bbox_patch(), + connectionstyle="arc3,rad=0.2", + **arrow_args)) + +# Finally we'll show off some more complex annotation and placement + +text = ax2.annotate('xy=(0, 1)\nxycoords=("data", "axes fraction")', + xy=(0, 1), xycoords=("data", 'axes fraction'), + xytext=(0, -20), textcoords='offset points', + ha="center", va="top", + bbox=bbox_args, + arrowprops=arrow_args) + +ax2.annotate('xy=(0.5, 0)\nxycoords=artist', + xy=(0.5, 0.), xycoords=text, + xytext=(0, -20), textcoords='offset points', + ha="center", va="top", + bbox=bbox_args, + arrowprops=arrow_args) + +ax2.annotate('xy=(0.8, 0.5)\nxycoords=ax1.transData', + xy=(0.8, 0.5), xycoords=ax1.transData, + xytext=(10, 10), + textcoords=OffsetFrom(ax2.bbox, (0, 0), "points"), + ha="left", va="bottom", + bbox=bbox_args, + arrowprops=arrow_args) + +ax2.set(xlim=[-2, 2], ylim=[-2, 2]) +plt.show() diff --git a/examples/text_labels_and_annotations/legend_demo.py b/examples/text_labels_and_annotations/legend_demo.py new file mode 100644 index 000000000000..2e42e36e0022 --- /dev/null +++ b/examples/text_labels_and_annotations/legend_demo.py @@ -0,0 +1,186 @@ +""" +=========== +Legend Demo +=========== + +Plotting legends in Matplotlib. + +There are many ways to create and customize legends in Matplotlib. Below +we'll show a few examples for how to do so. + +First we'll show off how to make a legend for specific lines. +""" +from __future__ import (absolute_import, division, + print_function, unicode_literals) + +import matplotlib.pyplot as plt +import numpy as np +from matplotlib.legend_handler import (HandlerLineCollection, + HandlerTuple) +import matplotlib.collections as mcol +from matplotlib.lines import Line2D + +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 into l1 using tuple +# unpacking. So l1 is a Line2D instance, not a sequence of lines +l1, = plt.plot(t2, np.exp(-t2)) +l2, l3 = plt.plot(t2, np.sin(2 * np.pi * t2), '--o', t1, np.log(1 + t1), '.') +l4, = plt.plot(t2, np.exp(-t2) * np.sin(2 * np.pi * t2), 's-.') + +plt.legend((l2, l4), ('oscillatory', 'damped'), loc='upper right', shadow=True) +plt.xlabel('time') +plt.ylabel('volts') +plt.title('Damped oscillation') +plt.show() + + +############################################################################### +# Next we'll demonstrate plotting more complex labels. + +x = np.linspace(0, 1) + +# Plot the lines y=x**n for n=1..4. +ax = plt.subplot(2, 1, 1) +for n in range(1, 5): + plt.plot(x, x**n, label="n={0}".format(n)) +plt.legend(loc="upper left", bbox_to_anchor=[0, 1], + ncol=2, shadow=True, title="Legend", fancybox=True) +ax.get_legend().get_title().set_color("red") + +# Demonstrate some more complex labels. +ax = plt.subplot(2, 1, 2) +plt.plot(x, x**2, label="multi\nline") +half_pi = np.linspace(0, np.pi / 2) +plt.plot(np.sin(half_pi), np.cos(half_pi), label=r"$\frac{1}{2}\pi$") +plt.plot(x, 2**(x**2), label="$2^{x^2}$") +plt.legend(shadow=True, fancybox=True) + +plt.show() + + +############################################################################### +# Here we attach legends to more complex plots. + +fig, axes = plt.subplots(3, 1) +top_ax, middle_ax, bottom_ax = axes + +top_ax.bar([0, 1, 2], [0.2, 0.3, 0.1], width=0.4, label="Bar 1", + align="center") +top_ax.bar([0.5, 1.5, 2.5], [0.3, 0.2, 0.2], color="red", width=0.4, + label="Bar 2", align="center") +top_ax.legend() + +middle_ax.errorbar([0, 1, 2], [2, 3, 1], xerr=0.4, fmt="s", label="test 1") +middle_ax.errorbar([0, 1, 2], [3, 2, 4], yerr=0.3, fmt="o", label="test 2") +middle_ax.errorbar([0, 1, 2], [1, 1, 3], xerr=0.4, yerr=0.3, fmt="^", + label="test 3") +middle_ax.legend() + +bottom_ax.stem([0.3, 1.5, 2.7], [1, 3.6, 2.7], label="stem test") +bottom_ax.legend() + +plt.subplots_adjust(hspace=0.7) +plt.show() + +############################################################################### +# Now we'll showcase legend entries with more than one legend key. + +fig, (ax1, ax2) = plt.subplots(2, 1) + +# First plot: two legend keys for a single entry +p1 = ax1.scatter([1], [5], c='r', marker='s', s=100) +p2 = ax1.scatter([3], [2], c='b', marker='o', s=100) +# `plot` returns a list, but we want the handle - thus the comma on the left +p3, = ax1.plot([1, 5], [4, 4], 'm-d') + +# Assign two of the handles to the same legend entry by putting them in a tuple +# and using a generic handler map (which would be used for any additional +# tuples of handles like (p1, p3)). +l = ax1.legend([(p1, p3), p2], ['two keys', 'one key'], scatterpoints=1, + numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)}) + +# Second plot: plot two bar charts on top of each other and change the padding +# between the legend keys +x_left = [1, 2, 3] +y_pos = [1, 3, 2] +y_neg = [2, 1, 4] + +rneg = ax2.bar(x_left, y_neg, width=0.5, color='w', hatch='///', label='-1') +rpos = ax2.bar(x_left, y_pos, width=0.5, color='k', label='+1') + +# Treat each legend entry differently by using specific `HandlerTuple`s +l = ax2.legend([(rpos, rneg), (rneg, rpos)], ['pad!=0', 'pad=0'], + handler_map={(rpos, rneg): HandlerTuple(ndivide=None), + (rneg, rpos): HandlerTuple(ndivide=None, pad=0.)}) + +plt.show() + +############################################################################### +# Finally, it is also possible to write custom objects that define +# how to stylize legends. + + +class HandlerDashedLines(HandlerLineCollection): + """ + Custom Handler for LineCollection instances. + """ + def create_artists(self, legend, orig_handle, + xdescent, ydescent, width, height, fontsize, trans): + # figure out how many lines there are + numlines = len(orig_handle.get_segments()) + xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, + width, height, fontsize) + leglines = [] + # divide the vertical space where the lines will go + # into equal parts based on the number of lines + ydata = ((height) / (numlines + 1)) * np.ones(xdata.shape, float) + # for each line, create the line at the proper location + # and set the dash pattern + for i in range(numlines): + legline = Line2D(xdata, ydata * (numlines - i) - ydescent) + self.update_prop(legline, orig_handle, legend) + # set color, dash pattern, and linewidth to that + # of the lines in linecollection + try: + color = orig_handle.get_colors()[i] + except IndexError: + color = orig_handle.get_colors()[0] + try: + dashes = orig_handle.get_dashes()[i] + except IndexError: + dashes = orig_handle.get_dashes()[0] + try: + lw = orig_handle.get_linewidths()[i] + except IndexError: + lw = orig_handle.get_linewidths()[0] + if dashes[0] is not None: + legline.set_dashes(dashes[1]) + legline.set_color(color) + legline.set_transform(trans) + legline.set_linewidth(lw) + leglines.append(legline) + return leglines + +x = np.linspace(0, 5, 100) + +plt.figure() +colors = plt.rcParams['axes.prop_cycle'].by_key()['color'][:5] +styles = ['solid', 'dashed', 'dashed', 'dashed', 'solid'] +lines = [] +for i, color, style in zip(range(5), colors, styles): + plt.plot(x, np.sin(x) - .1 * i, c=color, ls=style) + + +# make proxy artists +# make list of one line -- doesn't matter what the coordinates are +line = [[(0, 0)]] +# set up the proxy artist +lc = mcol.LineCollection(5 * line, linestyles=styles, colors=colors) +# create the legend +plt.legend([lc], ['multi-line'], handler_map={type(lc): HandlerDashedLines()}, + handlelength=2.5, handleheight=3) + +plt.show() diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index 28cc65dfca3d..f2fb69194849 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -163,9 +163,9 @@ ax.yaxis.set_major_formatter( ymajorFormatter ) ax.yaxis.set_minor_formatter( yminorFormatter ) -See :ref:`sphx_glr_gallery_pylab_examples_major_minor_demo1.py` for an example -of setting major and minor ticks. See the :mod:`matplotlib.dates` module for -more information and examples of using date locators and formatters. +See :ref:`sphx_glr_gallery_pylab_examples_major_minor_demo.py` for an +example of setting major and minor ticks. See the :mod:`matplotlib.dates` +module for more information and examples of using date locators and formatters. """ from __future__ import (absolute_import, division, print_function, diff --git a/tutorials/01_introductory/pyplot.py b/tutorials/01_introductory/pyplot.py index a41102cd5f45..d849d29ca382 100644 --- a/tutorials/01_introductory/pyplot.py +++ b/tutorials/01_introductory/pyplot.py @@ -406,7 +406,7 @@ def f(t): # variety of other coordinate systems one can choose -- see # :ref:`annotations-tutorial` and :ref:`plotting-guide-annotation` for # details. More examples can be found in -# :ref:`sphx_glr_gallery_pylab_examples_annotation_demo.py`. +# :ref:`sphx_glr_gallery_text_labels_and_annotations_annotation_demo.py`. # # # Logarithmic and other nonlinear axes diff --git a/tutorials/01_introductory/sample_plots.py b/tutorials/01_introductory/sample_plots.py index f7294cd332e3..675b7a601dc9 100644 --- a/tutorials/01_introductory/sample_plots.py +++ b/tutorials/01_introductory/sample_plots.py @@ -135,8 +135,8 @@ Use the :func:`~matplotlib.pyplot.bar` command to make bar charts, which includes customizations such as error bars: -.. figure:: ../../gallery/pylab_examples/images/sphx_glr_barchart_demo_001.png - :target: ../../gallery/pylab_examples/barchart_demo.html +.. figure:: ../../gallery/statistics/images/sphx_glr_barchart_demo_001.png + :target: ../../gallery/statistics/barchart_demo.html :align: center :scale: 50 diff --git a/tutorials/text/annotations.py b/tutorials/text/annotations.py index 1fc6e750dd1b..0bf520681de6 100644 --- a/tutorials/text/annotations.py +++ b/tutorials/text/annotations.py @@ -94,7 +94,7 @@ For more on all the wild and wonderful things you can do with annotations, including fancy arrows, see :ref:`plotting-guide-annotation` -and :ref:`sphx_glr_gallery_pylab_examples_annotation_demo.py`. +and :ref:`sphx_glr_gallery_text_labels_and_annotations_annotation_demo.py`. Do not proceed unless you have already read :ref:`annotations-tutorial`, @@ -158,12 +158,12 @@ Square ``square`` pad=0.3 ========== ============== ========================== -.. figure:: ../../gallery/pylab_examples/images/sphx_glr_fancybox_demo2_001.png - :target: ../../gallery/pylab_examples/fancybox_demo2.html +.. figure:: ../../gallery/pylab_examples/images/sphx_glr_fancybox_demo_001.png + :target: ../../gallery/pylab_examples/fancybox_demo.html :align: center :scale: 50 - Fancybox Demo2 + Fancybox Demo Note that the attribute arguments can be specified within the style @@ -513,7 +513,8 @@ Annotation with Simple Coordinates 3 - You may take a look at this example :ref:`sphx_glr_gallery_pylab_examples_annotation_demo3.py`. + You may take a look at this example + :ref:`sphx_glr_gallery_text_labels_and_annotations_annotation_demo.py`. Using ConnectorPatch --------------------