python plotting tutorial - 2

The second part of Python plotting tutorial.

Before reading this article, PLEASE READ THE TUTORIAL - 1 FIRST.

This article is generated by my Jupyter notebook, using which I am practicing the code from the book Scientific computing with Python3 published by Packt.

All the code below are from this book, and the copyright belongs to the author.

from scipy import *
from matplotlib.pyplot import *
%matplotlib inline

matplotlib objects

Sometimes we want to modify our figure later, so we will need matplotlib objects.

the axes objects

fig = figure(1)
ax = subplot(111)
x = linspace(0,2*pi,100)
# We set up a function that modulates the amplitude of the sin function
amod_sin = lambda x: (1.-0.1*sin(25*x))*sin(x)
# and plot both...
ax.plot(x,sin(x),label = 'sin')
ax.plot(x, amod_sin(x), label = 'modsin')
[<matplotlib.lines.Line2D at 0x156d81da438>]

output_3_1.png-13.5kB

These two plot commands actually fill the list ax.lines with two line2D objects.

help(subplot) # from here we know that subplot(111) equals to subplot(1,1,1)
Help on function subplot in module matplotlib.pyplot:

subplot(*args, **kwargs)
    Return a subplot axes at the given grid position.

    Call signature::

       subplot(nrows, ncols, index, **kwargs)

    In the current figure, create and return an `~.Axes`, at position *index*
    of a (virtual) grid of *nrows* by *ncols* axes.  Indexes go from 1 to
    ``nrows * ncols``, incrementing in row-major order.

    If *nrows*, *ncols* and *index* are all less than 10, they can also be
    given as a single, concatenated, three-digit number.

    For example, ``subplot(2, 3, 3)`` and ``subplot(233)`` both create an
    `~.Axes` at the top right corner of the current figure, occupying half of
    the figure height and a third of the figure width.

    .. note::

       Creating a subplot will delete any pre-existing subplot that overlaps
       with it beyond sharing a boundary::

          import matplotlib.pyplot as plt
          # plot a line, implicitly creating a subplot(111)
          plt.plot([1,2,3])
          # now create a subplot which represents the top plot of a grid
          # with 2 rows and 1 column. Since this subplot will overlap the
          # first, the plot (and its axes) previously created, will be removed
          plt.subplot(211)
          plt.plot(range(12))
          plt.subplot(212, facecolor='y') # creates 2nd subplot with yellow background

       If you do not want this behavior, use the
       :meth:`~matplotlib.figure.Figure.add_subplot` method or the
       :func:`~matplotlib.pyplot.axes` function instead.

    Keyword arguments:

      *facecolor*:
        The background color of the subplot, which can be any valid
        color specifier.  See :mod:`matplotlib.colors` for more
        information.

      *polar*:
        A boolean flag indicating whether the subplot plot should be
        a polar projection.  Defaults to *False*.

      *projection*:
        A string giving the name of a custom projection to be used
        for the subplot. This projection must have been previously
        registered. See :mod:`matplotlib.projections`.

    .. seealso::

        :func:`~matplotlib.pyplot.axes`
            For additional information on :func:`axes` and
            :func:`subplot` keyword arguments.

        :file:`gallery/pie_and_polar_charts/polar_scatter.py`
            For an example

    **Example:**

    .. plot:: gallery/subplots_axes_and_figures/subplot.py

We can use labels to identify the objects:

(Here the index il refers to the sin-curve)

for il, line in enumerate(ax.lines):
    if line.get_label() == 'sin':
        break

Modifying line properties

The line object is an element of the list ax.lines. All the properties are collected in an dictionary:

    dict_keys(['marker', 'markeredgewidth', 'data', 'clip_box',
    'solid_capstyle', 'clip_on', 'rasterized', 'dash_capstyle', 'path',
    'ydata', 'markeredgecolor', 'xdata', 'label', 'alpha', 'linestyle',
    'antialiased', 'snap', 'transform', 'url',
    'transformed_clip_path_and_affine', 'clip_path', 'path_effects',
    'animated', 'contains', 'fillstyle', 'sketch_params', 'xydata',
    'drawstyle', 'markersize', 'linewidth', 'figure', 'markerfacecolor',
    'pickradius', 'agg_filter', 'dash_joinstyle', 'color', 'solid_joinstyle',
    'picker', 'markevery', 'axes', 'children', 'gid', 'zorder', 'visible',
    'markerfacecoloralt'])

we can obtain it by using the following command:

ax.lines[il].properties()
{'agg_filter': None,
 'alpha': None,
 'animated': False,
 'antialiased': True,
 'children': [],
 'clip_box': TransformedBbox(Bbox([[0.0, 0.0], [1.0, 1.0]]), CompositeGenericTransform(CompositeGenericTransform(BboxTransformTo(Bbox([[0.0, 0.0], [1.0, 1.0]])), Affine2D(array([[ 1.,  0.,  0.],
        [ 0.,  1.,  0.],
        [ 0.,  0.,  1.]]))), BboxTransformTo(TransformedBbox(Bbox([[0.125, 0.125], [0.9, 0.88]]), BboxTransformTo(TransformedBbox(Bbox([[0.0, 0.0], [6.0, 4.0]]), Affine2D(array([[ 72.,   0.,   0.],
        [  0.,  72.,   0.],
        [  0.,   0.,   1.]])))))))),
 'clip_on': True,
 'clip_path': None,
 'color': '#1f77b4',
 'contains': None,
 'dash_capstyle': 'butt',
 'dash_joinstyle': 'round',
 'data': (array([ 0.        ,  0.06346652,  0.12693304,  0.19039955,  0.25386607,
          0.31733259,  0.38079911,  0.44426563,  0.50773215,  0.57119866,
          0.63466518,  0.6981317 ,  0.76159822,  0.82506474,  0.88853126,
          0.95199777,  1.01546429,  1.07893081,  1.14239733,  1.20586385,
          1.26933037,  1.33279688,  1.3962634 ,  1.45972992,  1.52319644,
          1.58666296,  1.65012947,  1.71359599,  1.77706251,  1.84052903,
          1.90399555,  1.96746207,  2.03092858,  2.0943951 ,  2.15786162,
          2.22132814,  2.28479466,  2.34826118,  2.41172769,  2.47519421,
          2.53866073,  2.60212725,  2.66559377,  2.72906028,  2.7925268 ,
          2.85599332,  2.91945984,  2.98292636,  3.04639288,  3.10985939,
          3.17332591,  3.23679243,  3.30025895,  3.36372547,  3.42719199,
          3.4906585 ,  3.55412502,  3.61759154,  3.68105806,  3.74452458,
          3.8079911 ,  3.87145761,  3.93492413,  3.99839065,  4.06185717,
          4.12532369,  4.1887902 ,  4.25225672,  4.31572324,  4.37918976,
          4.44265628,  4.5061228 ,  4.56958931,  4.63305583,  4.69652235,
          4.75998887,  4.82345539,  4.88692191,  4.95038842,  5.01385494,
          5.07732146,  5.14078798,  5.2042545 ,  5.26772102,  5.33118753,
          5.39465405,  5.45812057,  5.52158709,  5.58505361,  5.64852012,
          5.71198664,  5.77545316,  5.83891968,  5.9023862 ,  5.96585272,
          6.02931923,  6.09278575,  6.15625227,  6.21971879,  6.28318531]),
  array([  0.00000000e+00,   6.34239197e-02,   1.26592454e-01,
           1.89251244e-01,   2.51147987e-01,   3.12033446e-01,
           3.71662456e-01,   4.29794912e-01,   4.86196736e-01,
           5.40640817e-01,   5.92907929e-01,   6.42787610e-01,
           6.90079011e-01,   7.34591709e-01,   7.76146464e-01,
           8.14575952e-01,   8.49725430e-01,   8.81453363e-01,
           9.09631995e-01,   9.34147860e-01,   9.54902241e-01,
           9.71811568e-01,   9.84807753e-01,   9.93838464e-01,
           9.98867339e-01,   9.99874128e-01,   9.96854776e-01,
           9.89821442e-01,   9.78802446e-01,   9.63842159e-01,
           9.45000819e-01,   9.22354294e-01,   8.95993774e-01,
           8.66025404e-01,   8.32569855e-01,   7.95761841e-01,
           7.55749574e-01,   7.12694171e-01,   6.66769001e-01,
           6.18158986e-01,   5.67059864e-01,   5.13677392e-01,
           4.58226522e-01,   4.00930535e-01,   3.42020143e-01,
           2.81732557e-01,   2.20310533e-01,   1.58001396e-01,
           9.50560433e-02,   3.17279335e-02,  -3.17279335e-02,
          -9.50560433e-02,  -1.58001396e-01,  -2.20310533e-01,
          -2.81732557e-01,  -3.42020143e-01,  -4.00930535e-01,
          -4.58226522e-01,  -5.13677392e-01,  -5.67059864e-01,
          -6.18158986e-01,  -6.66769001e-01,  -7.12694171e-01,
          -7.55749574e-01,  -7.95761841e-01,  -8.32569855e-01,
          -8.66025404e-01,  -8.95993774e-01,  -9.22354294e-01,
          -9.45000819e-01,  -9.63842159e-01,  -9.78802446e-01,
          -9.89821442e-01,  -9.96854776e-01,  -9.99874128e-01,
          -9.98867339e-01,  -9.93838464e-01,  -9.84807753e-01,
          -9.71811568e-01,  -9.54902241e-01,  -9.34147860e-01,
          -9.09631995e-01,  -8.81453363e-01,  -8.49725430e-01,
          -8.14575952e-01,  -7.76146464e-01,  -7.34591709e-01,
          -6.90079011e-01,  -6.42787610e-01,  -5.92907929e-01,
          -5.40640817e-01,  -4.86196736e-01,  -4.29794912e-01,
          -3.71662456e-01,  -3.12033446e-01,  -2.51147987e-01,
          -1.89251244e-01,  -1.26592454e-01,  -6.34239197e-02,
          -2.44929360e-16])),
 'drawstyle': 'default',
 'figure': <matplotlib.figure.Figure at 0x156d6177a90>,
 'fillstyle': 'full',
 'gid': None,
 'label': 'sin',
 'linestyle': '-',
 'linewidth': 1.5,
 'marker': 'None',
 'markeredgecolor': '#1f77b4',
 'markeredgewidth': 1.0,
 'markerfacecolor': '#1f77b4',
 'markerfacecoloralt': 'none',
 'markersize': 6.0,
 'markevery': None,
 'path': Path(array([[  0.00000000e+00,   0.00000000e+00],
        [  6.34665183e-02,   6.34239197e-02],
        [  1.26933037e-01,   1.26592454e-01],
        [  1.90399555e-01,   1.89251244e-01],
        [  2.53866073e-01,   2.51147987e-01],
        [  3.17332591e-01,   3.12033446e-01],
        [  3.80799110e-01,   3.71662456e-01],
        [  4.44265628e-01,   4.29794912e-01],
        [  5.07732146e-01,   4.86196736e-01],
        [  5.71198664e-01,   5.40640817e-01],
        [  6.34665183e-01,   5.92907929e-01],
        [  6.98131701e-01,   6.42787610e-01],
        [  7.61598219e-01,   6.90079011e-01],
        [  8.25064737e-01,   7.34591709e-01],
        [  8.88531256e-01,   7.76146464e-01],
        [  9.51997774e-01,   8.14575952e-01],
        [  1.01546429e+00,   8.49725430e-01],
        [  1.07893081e+00,   8.81453363e-01],
        [  1.14239733e+00,   9.09631995e-01],
        [  1.20586385e+00,   9.34147860e-01],
        [  1.26933037e+00,   9.54902241e-01],
        [  1.33279688e+00,   9.71811568e-01],
        [  1.39626340e+00,   9.84807753e-01],
        [  1.45972992e+00,   9.93838464e-01],
        [  1.52319644e+00,   9.98867339e-01],
        [  1.58666296e+00,   9.99874128e-01],
        [  1.65012947e+00,   9.96854776e-01],
        [  1.71359599e+00,   9.89821442e-01],
        [  1.77706251e+00,   9.78802446e-01],
        [  1.84052903e+00,   9.63842159e-01],
        [  1.90399555e+00,   9.45000819e-01],
        [  1.96746207e+00,   9.22354294e-01],
        [  2.03092858e+00,   8.95993774e-01],
        [  2.09439510e+00,   8.66025404e-01],
        [  2.15786162e+00,   8.32569855e-01],
        [  2.22132814e+00,   7.95761841e-01],
        [  2.28479466e+00,   7.55749574e-01],
        [  2.34826118e+00,   7.12694171e-01],
        [  2.41172769e+00,   6.66769001e-01],
        [  2.47519421e+00,   6.18158986e-01],
        [  2.53866073e+00,   5.67059864e-01],
        [  2.60212725e+00,   5.13677392e-01],
        [  2.66559377e+00,   4.58226522e-01],
        [  2.72906028e+00,   4.00930535e-01],
        [  2.79252680e+00,   3.42020143e-01],
        [  2.85599332e+00,   2.81732557e-01],
        [  2.91945984e+00,   2.20310533e-01],
        [  2.98292636e+00,   1.58001396e-01],
        [  3.04639288e+00,   9.50560433e-02],
        [  3.10985939e+00,   3.17279335e-02],
        [  3.17332591e+00,  -3.17279335e-02],
        [  3.23679243e+00,  -9.50560433e-02],
        [  3.30025895e+00,  -1.58001396e-01],
        [  3.36372547e+00,  -2.20310533e-01],
        [  3.42719199e+00,  -2.81732557e-01],
        [  3.49065850e+00,  -3.42020143e-01],
        [  3.55412502e+00,  -4.00930535e-01],
        [  3.61759154e+00,  -4.58226522e-01],
        [  3.68105806e+00,  -5.13677392e-01],
        [  3.74452458e+00,  -5.67059864e-01],
        [  3.80799110e+00,  -6.18158986e-01],
        [  3.87145761e+00,  -6.66769001e-01],
        [  3.93492413e+00,  -7.12694171e-01],
        [  3.99839065e+00,  -7.55749574e-01],
        [  4.06185717e+00,  -7.95761841e-01],
        [  4.12532369e+00,  -8.32569855e-01],
        [  4.18879020e+00,  -8.66025404e-01],
        [  4.25225672e+00,  -8.95993774e-01],
        [  4.31572324e+00,  -9.22354294e-01],
        [  4.37918976e+00,  -9.45000819e-01],
        [  4.44265628e+00,  -9.63842159e-01],
        [  4.50612280e+00,  -9.78802446e-01],
        [  4.56958931e+00,  -9.89821442e-01],
        [  4.63305583e+00,  -9.96854776e-01],
        [  4.69652235e+00,  -9.99874128e-01],
        [  4.75998887e+00,  -9.98867339e-01],
        [  4.82345539e+00,  -9.93838464e-01],
        [  4.88692191e+00,  -9.84807753e-01],
        [  4.95038842e+00,  -9.71811568e-01],
        [  5.01385494e+00,  -9.54902241e-01],
        [  5.07732146e+00,  -9.34147860e-01],
        [  5.14078798e+00,  -9.09631995e-01],
        [  5.20425450e+00,  -8.81453363e-01],
        [  5.26772102e+00,  -8.49725430e-01],
        [  5.33118753e+00,  -8.14575952e-01],
        [  5.39465405e+00,  -7.76146464e-01],
        [  5.45812057e+00,  -7.34591709e-01],
        [  5.52158709e+00,  -6.90079011e-01],
        [  5.58505361e+00,  -6.42787610e-01],
        [  5.64852012e+00,  -5.92907929e-01],
        [  5.71198664e+00,  -5.40640817e-01],
        [  5.77545316e+00,  -4.86196736e-01],
        [  5.83891968e+00,  -4.29794912e-01],
        [  5.90238620e+00,  -3.71662456e-01],
        [  5.96585272e+00,  -3.12033446e-01],
        [  6.02931923e+00,  -2.51147987e-01],
        [  6.09278575e+00,  -1.89251244e-01],
        [  6.15625227e+00,  -1.26592454e-01],
        [  6.21971879e+00,  -6.34239197e-02],
        [  6.28318531e+00,  -2.44929360e-16]]), None),
 'path_effects': [],
 'picker': None,
 'pickradius': 5,
 'rasterized': None,
 'sketch_params': None,
 'snap': None,
 'solid_capstyle': 'projecting',
 'solid_joinstyle': 'round',
 'transform': CompositeGenericTransform(TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())), CompositeGenericTransform(BboxTransformFrom(TransformedBbox(Bbox([[-0.3141592653589793, -1.201036728154288], [6.5973445725385655, 1.1956164529218232]]), TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())))), BboxTransformTo(TransformedBbox(Bbox([[0.125, 0.125], [0.9, 0.88]]), BboxTransformTo(TransformedBbox(Bbox([[0.0, 0.0], [6.0, 4.0]]), Affine2D(array([[ 72.,   0.,   0.],
        [  0.,  72.,   0.],
        [  0.,   0.,   1.]])))))))),
 'transformed_clip_path_and_affine': (None, None),
 'url': None,
 'visible': True,
 'xdata': array([ 0.        ,  0.06346652,  0.12693304,  0.19039955,  0.25386607,
         0.31733259,  0.38079911,  0.44426563,  0.50773215,  0.57119866,
         0.63466518,  0.6981317 ,  0.76159822,  0.82506474,  0.88853126,
         0.95199777,  1.01546429,  1.07893081,  1.14239733,  1.20586385,
         1.26933037,  1.33279688,  1.3962634 ,  1.45972992,  1.52319644,
         1.58666296,  1.65012947,  1.71359599,  1.77706251,  1.84052903,
         1.90399555,  1.96746207,  2.03092858,  2.0943951 ,  2.15786162,
         2.22132814,  2.28479466,  2.34826118,  2.41172769,  2.47519421,
         2.53866073,  2.60212725,  2.66559377,  2.72906028,  2.7925268 ,
         2.85599332,  2.91945984,  2.98292636,  3.04639288,  3.10985939,
         3.17332591,  3.23679243,  3.30025895,  3.36372547,  3.42719199,
         3.4906585 ,  3.55412502,  3.61759154,  3.68105806,  3.74452458,
         3.8079911 ,  3.87145761,  3.93492413,  3.99839065,  4.06185717,
         4.12532369,  4.1887902 ,  4.25225672,  4.31572324,  4.37918976,
         4.44265628,  4.5061228 ,  4.56958931,  4.63305583,  4.69652235,
         4.75998887,  4.82345539,  4.88692191,  4.95038842,  5.01385494,
         5.07732146,  5.14078798,  5.2042545 ,  5.26772102,  5.33118753,
         5.39465405,  5.45812057,  5.52158709,  5.58505361,  5.64852012,
         5.71198664,  5.77545316,  5.83891968,  5.9023862 ,  5.96585272,
         6.02931923,  6.09278575,  6.15625227,  6.21971879,  6.28318531]),
 'xydata': array([[  0.00000000e+00,   0.00000000e+00],
        [  6.34665183e-02,   6.34239197e-02],
        [  1.26933037e-01,   1.26592454e-01],
        [  1.90399555e-01,   1.89251244e-01],
        [  2.53866073e-01,   2.51147987e-01],
        [  3.17332591e-01,   3.12033446e-01],
        [  3.80799110e-01,   3.71662456e-01],
        [  4.44265628e-01,   4.29794912e-01],
        [  5.07732146e-01,   4.86196736e-01],
        [  5.71198664e-01,   5.40640817e-01],
        [  6.34665183e-01,   5.92907929e-01],
        [  6.98131701e-01,   6.42787610e-01],
        [  7.61598219e-01,   6.90079011e-01],
        [  8.25064737e-01,   7.34591709e-01],
        [  8.88531256e-01,   7.76146464e-01],
        [  9.51997774e-01,   8.14575952e-01],
        [  1.01546429e+00,   8.49725430e-01],
        [  1.07893081e+00,   8.81453363e-01],
        [  1.14239733e+00,   9.09631995e-01],
        [  1.20586385e+00,   9.34147860e-01],
        [  1.26933037e+00,   9.54902241e-01],
        [  1.33279688e+00,   9.71811568e-01],
        [  1.39626340e+00,   9.84807753e-01],
        [  1.45972992e+00,   9.93838464e-01],
        [  1.52319644e+00,   9.98867339e-01],
        [  1.58666296e+00,   9.99874128e-01],
        [  1.65012947e+00,   9.96854776e-01],
        [  1.71359599e+00,   9.89821442e-01],
        [  1.77706251e+00,   9.78802446e-01],
        [  1.84052903e+00,   9.63842159e-01],
        [  1.90399555e+00,   9.45000819e-01],
        [  1.96746207e+00,   9.22354294e-01],
        [  2.03092858e+00,   8.95993774e-01],
        [  2.09439510e+00,   8.66025404e-01],
        [  2.15786162e+00,   8.32569855e-01],
        [  2.22132814e+00,   7.95761841e-01],
        [  2.28479466e+00,   7.55749574e-01],
        [  2.34826118e+00,   7.12694171e-01],
        [  2.41172769e+00,   6.66769001e-01],
        [  2.47519421e+00,   6.18158986e-01],
        [  2.53866073e+00,   5.67059864e-01],
        [  2.60212725e+00,   5.13677392e-01],
        [  2.66559377e+00,   4.58226522e-01],
        [  2.72906028e+00,   4.00930535e-01],
        [  2.79252680e+00,   3.42020143e-01],
        [  2.85599332e+00,   2.81732557e-01],
        [  2.91945984e+00,   2.20310533e-01],
        [  2.98292636e+00,   1.58001396e-01],
        [  3.04639288e+00,   9.50560433e-02],
        [  3.10985939e+00,   3.17279335e-02],
        [  3.17332591e+00,  -3.17279335e-02],
        [  3.23679243e+00,  -9.50560433e-02],
        [  3.30025895e+00,  -1.58001396e-01],
        [  3.36372547e+00,  -2.20310533e-01],
        [  3.42719199e+00,  -2.81732557e-01],
        [  3.49065850e+00,  -3.42020143e-01],
        [  3.55412502e+00,  -4.00930535e-01],
        [  3.61759154e+00,  -4.58226522e-01],
        [  3.68105806e+00,  -5.13677392e-01],
        [  3.74452458e+00,  -5.67059864e-01],
        [  3.80799110e+00,  -6.18158986e-01],
        [  3.87145761e+00,  -6.66769001e-01],
        [  3.93492413e+00,  -7.12694171e-01],
        [  3.99839065e+00,  -7.55749574e-01],
        [  4.06185717e+00,  -7.95761841e-01],
        [  4.12532369e+00,  -8.32569855e-01],
        [  4.18879020e+00,  -8.66025404e-01],
        [  4.25225672e+00,  -8.95993774e-01],
        [  4.31572324e+00,  -9.22354294e-01],
        [  4.37918976e+00,  -9.45000819e-01],
        [  4.44265628e+00,  -9.63842159e-01],
        [  4.50612280e+00,  -9.78802446e-01],
        [  4.56958931e+00,  -9.89821442e-01],
        [  4.63305583e+00,  -9.96854776e-01],
        [  4.69652235e+00,  -9.99874128e-01],
        [  4.75998887e+00,  -9.98867339e-01],
        [  4.82345539e+00,  -9.93838464e-01],
        [  4.88692191e+00,  -9.84807753e-01],
        [  4.95038842e+00,  -9.71811568e-01],
        [  5.01385494e+00,  -9.54902241e-01],
        [  5.07732146e+00,  -9.34147860e-01],
        [  5.14078798e+00,  -9.09631995e-01],
        [  5.20425450e+00,  -8.81453363e-01],
        [  5.26772102e+00,  -8.49725430e-01],
        [  5.33118753e+00,  -8.14575952e-01],
        [  5.39465405e+00,  -7.76146464e-01],
        [  5.45812057e+00,  -7.34591709e-01],
        [  5.52158709e+00,  -6.90079011e-01],
        [  5.58505361e+00,  -6.42787610e-01],
        [  5.64852012e+00,  -5.92907929e-01],
        [  5.71198664e+00,  -5.40640817e-01],
        [  5.77545316e+00,  -4.86196736e-01],
        [  5.83891968e+00,  -4.29794912e-01],
        [  5.90238620e+00,  -3.71662456e-01],
        [  5.96585272e+00,  -3.12033446e-01],
        [  6.02931923e+00,  -2.51147987e-01],
        [  6.09278575e+00,  -1.89251244e-01],
        [  6.15625227e+00,  -1.26592454e-01],
        [  6.21971879e+00,  -6.34239197e-02],
        [  6.28318531e+00,  -2.44929360e-16]]),
 'ydata': array([  0.00000000e+00,   6.34239197e-02,   1.26592454e-01,
          1.89251244e-01,   2.51147987e-01,   3.12033446e-01,
          3.71662456e-01,   4.29794912e-01,   4.86196736e-01,
          5.40640817e-01,   5.92907929e-01,   6.42787610e-01,
          6.90079011e-01,   7.34591709e-01,   7.76146464e-01,
          8.14575952e-01,   8.49725430e-01,   8.81453363e-01,
          9.09631995e-01,   9.34147860e-01,   9.54902241e-01,
          9.71811568e-01,   9.84807753e-01,   9.93838464e-01,
          9.98867339e-01,   9.99874128e-01,   9.96854776e-01,
          9.89821442e-01,   9.78802446e-01,   9.63842159e-01,
          9.45000819e-01,   9.22354294e-01,   8.95993774e-01,
          8.66025404e-01,   8.32569855e-01,   7.95761841e-01,
          7.55749574e-01,   7.12694171e-01,   6.66769001e-01,
          6.18158986e-01,   5.67059864e-01,   5.13677392e-01,
          4.58226522e-01,   4.00930535e-01,   3.42020143e-01,
          2.81732557e-01,   2.20310533e-01,   1.58001396e-01,
          9.50560433e-02,   3.17279335e-02,  -3.17279335e-02,
         -9.50560433e-02,  -1.58001396e-01,  -2.20310533e-01,
         -2.81732557e-01,  -3.42020143e-01,  -4.00930535e-01,
         -4.58226522e-01,  -5.13677392e-01,  -5.67059864e-01,
         -6.18158986e-01,  -6.66769001e-01,  -7.12694171e-01,
         -7.55749574e-01,  -7.95761841e-01,  -8.32569855e-01,
         -8.66025404e-01,  -8.95993774e-01,  -9.22354294e-01,
         -9.45000819e-01,  -9.63842159e-01,  -9.78802446e-01,
         -9.89821442e-01,  -9.96854776e-01,  -9.99874128e-01,
         -9.98867339e-01,  -9.93838464e-01,  -9.84807753e-01,
         -9.71811568e-01,  -9.54902241e-01,  -9.34147860e-01,
         -9.09631995e-01,  -8.81453363e-01,  -8.49725430e-01,
         -8.14575952e-01,  -7.76146464e-01,  -7.34591709e-01,
         -6.90079011e-01,  -6.42787610e-01,  -5.92907929e-01,
         -5.40640817e-01,  -4.86196736e-01,  -4.29794912e-01,
         -3.71662456e-01,  -3.12033446e-01,  -2.51147987e-01,
         -1.89251244e-01,  -1.26592454e-01,  -6.34239197e-02,
         -2.44929360e-16]),
 'zorder': 2}

We can modify such properties.

For example we can change the linestyle of the sin-curve:

(As you can see now, the linestyle and the linewidth now is ‘-‘ and 1.5)

ax.lines[il].set_linestyle('-.')
ax.lines[il].set_linewidth(2)

We can even modify the data, as shown:

ydata=ax.lines[il].get_ydata()
ydata[-1]=-0.5
ax.lines[il].set_ydata(ydata)

Now we plot the curves again.

(simply showing the same figure is enough)

As you can see in the following figure, the linestyle of the sin-curve has changed and its last data point is now corrupted.

fig

output_15_0.png-13.7kB

Annotations

we can use the annotate method to make annotations.

Its properties can be given in a dictionary:

annot1=ax.annotate('amplitude modulated\n curve', (2.1,1.0),(3.2,0.5),
 arrowprops={'width':2,'color':'k',
'connectionstyle':'arc3,rad=+0.5',
 'shrink':0.05},
 verticalalignment='bottom', horizontalalignment='left',fontsize=15,
 bbox={'facecolor':'gray', 'alpha':0.1, 'pad':10})
annot2=ax.annotate('corrupted data', (6.3,-0.5),(6.1,-1.1),
 arrowprops={'width':0.5,'color':'k','shrink':0.1},
 horizontalalignment='center', fontsize=12)

In this example, the arrow points to the point (2.1,1.0), and the left bottom of the text is (3.2,0.5).

fig

output_19_0.png-20kB

Sometimes you need to remove such annotations, so you will need to do this:

annot1.remove()
fig

output_21_0.png-15.6kB

filling areas between curves

Filling is done by the axis method:

ax.fill_between(x, y1, y2)

As for our example, we use:

axf = ax.fill_between(x, sin(x), amod_sin(x), facecolor='gray')
fig

output_23_0.png-16kB

axf.remove() # if you wanna try partial filling, do not forget to remove the complete filling first
fig

output_24_0.png-15.6kB

Use where to add addtional conditions.

axf = ax.fill_between(x, sin(x), amod_sin(x), where = sin(x) - amod_sin(x) > 0, facecolor = 'gray')
fig

output_26_0.png-15.8kB

Only the lower part is filled here.

ticks and ticklabels

here since it is a sin-curve, we need not labels from 0-7, what we need is something about $\pi$.

Thus we need to remove labels from the x-axis and y-axis and introducing problem relating tick labels.

ax.set_xticks(array([0,pi/2, pi, 3*pi/2, 2*pi]))
ax.set_xticklabels(('$0$', '$\pi/2$','$\pi$', '$3\pi/2$', '$2\pi$'),fontsize = 18)
ax.set_yticks(array([-1.,0.,1]))
ax.set_yticklabels(('$-1$','$0$','$1$'),fontsize=18)
fig

output_28_0.png-15.8kB

making 3D plots

There are some useful matplotlib tool kits and modules that can be used for a variety of

special purposes. Here we introduce the mplot3d toolkit to produce 3D-plots.

Adding the keyword projection='3d' to the axes object as shown in the following example:

from mpl_toolkits.mplot3d import axes3d

fig = figure()
ax = fig.gca(projection = '3d')
# plot points in 3D
class1 = 0.6 * random.standard_normal((200,3))
ax.plot(class1[:,0], class1[:,1],class1[:,2],'o')

class2 = 1.2 * random.standard_normal((200,3)) + array([5,4,0])
ax.plot(class2[:,0],class2[:,1],class2[:,2],'o')

class3 = 0.3 * random.standard_normal((200,3)) + array([0,3,2])
ax.plot(class3[:,0],class3[:,1],class3[:,2],'o')
[<mpl_toolkits.mplot3d.art3d.Line3D at 0x156d83a7ef0>]

output_30_1.png-26.9kB

plotting surface: (alpha is the parameter to set the transparency)

X,Y,Z = axes3d.get_test_data(0.05)
fig = figure()
ax = fig.gca(projection='3d')
# surface plot with transparency 0.5
ax.plot_surface(X,Y,Z,alpha=0.5)
<mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x156d83b4898>

output_32_1.png-50.5kB

help(axes3d.get_test_data)
Help on function get_test_data in module mpl_toolkits.mplot3d.axes3d:

get_test_data(delta=0.05)
    Return a tuple X, Y, Z with a test data set.

You can also plot contours in any of the coordinate projections as in the next example.

fig = figure()
ax = fig.gca(projection = '3d')
ax.plot_wireframe(X,Y,Z,rstride = 5,cstride = 5)

# plot contour projection on each axis plane
ax.contour(X,Y,Z, zdir='z',offset = -100)
ax.contour(X,Y,Z, zdir='x',offset = -40)
ax.contour(X,Y,Z, zdir='y',offset = 40)

# set axis limits
ax.set_xlim3d(-40,40)
ax.set_ylim3d(-40,40)
ax.set_zlim3d(-100,100)

# set labels
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
Text(0.5,0,'Z axis')

output_35_1.png-64.4kB

since we use Jupyter notebook‘s magic command to show figures inline, we cannot rotate and do any other adjustment here.

You can go to the mplot3d documentation website for more information.

making movies from plots

use the visvis module to save your evolving data as a movie.

# Install a pip package in the current Jupyter kernel
import sys
!{sys.executable} -m pip install visvis
Collecting visvis
  Using cached visvis-1.10.0.tar.gz
Requirement already satisfied: numpy in c:\users\huang\pycharmprojects\review_python\venv\lib\site-packages (from visvis)
Collecting pyOpenGl (from visvis)
  Using cached PyOpenGL-3.1.0.tar.gz
Building wheels for collected packages: visvis, pyOpenGl
  Running setup.py bdist_wheel for visvis: started
  Running setup.py bdist_wheel for visvis: finished with status 'done'
  Stored in directory: C:\Users\huang\AppData\Local\pip\Cache\wheels\de\cc\f6\883f1e175e8da4436208c35194ce35555e76b32e82afef4e5c
  Running setup.py bdist_wheel for pyOpenGl: started
  Running setup.py bdist_wheel for pyOpenGl: finished with status 'done'
  Stored in directory: C:\Users\huang\AppData\Local\pip\Cache\wheels\1c\17\50\f69d63e0a8169fb890f5a167817a73391be85d30e86fd29504
Successfully built visvis pyOpenGl
Installing collected packages: pyOpenGl, visvis
Successfully installed pyOpenGl-3.1.0 visvis-1.10.0
import visvis.vvmovie as vv

# create initial function values
x = linspace(-255,255,511)
X,Y = meshgrid(x,x)

f = sqrt(X*X+Y*Y) - 40 #radius 40
# evolve and store in a list
imlist = []
for iteration in range(200):
    imlist.append((f>0)*255)
    f -= 1 # move outwards one pixel
vv.images2swf.writeSwf('circle_evolution.swf',imlist)

the pic can also be saved as gif or avi and it can even be shown in the figure window with more packages installed.(e.g. pyOpenGL and PIL, the python imaging library)

If you want to know more about it, go to the documentation webpage of visvis for more information.

Another option is to use savefig to create images, one for each frame.

# create initial function values
x = linspace(-255,255,511)
X,Y = meshgrid(x,x)
f = sqrt(X*X+Y*Y) - 40 #radius 40
for iteration in range(200):
    imshow((f>0)*255)
    gray()
    axis('off')
    savefig('circle_evolution_{:d}.png'.format(iteration))
    f -= 1

You’d better not run the code above unless you want 200 pngs stored in your computer.

This blog is under a CC BY-NC-SA 3.0 Unported License
Link to this article: http://huangweiran.club/2018/01/14/python-plotting-tutorial-2/