{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n***********\nUsage Guide\n***********\n\nThis tutorial covers some basic usage patterns and best-practices to\nhelp you get started with Matplotlib.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A simple example\n================\n\nMatplotlib graphs your data on `~.figure.Figure`\\s (i.e., windows, Jupyter\nwidgets, etc.), each of which can contain one or more `~.axes.Axes` (i.e., an\narea where points can be specified in terms of x-y coordinates (or theta-r\nin a polar plot, or x-y-z in a 3D plot, etc.). The most simple way of\ncreating a figure with an axes is using `.pyplot.subplots`. We can then use\n`.Axes.plot` to draw some data on the axes:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, ax = plt.subplots() # Create a figure containing a single axes.\nax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Plot some data on the axes." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Many other plotting libraries or languages do not require you to explicitly\ncreate an axes. For example, in MATLAB, one can just do\n\n.. code-block:: matlab\n\n plot([1, 2, 3, 4], [1, 4, 2, 3]) % MATLAB plot.\n\nand get the desired graph.\n\nIn fact, you can do the same in Matplotlib: for each `~.axes.Axes` graphing\nmethod, there is a corresponding function in the :mod:`matplotlib.pyplot`\nmodule that performs that plot on the \"current\" axes, creating that axes (and\nits parent figure) if they don't exist yet. So the previous example can be\nwritten more shortly as\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Matplotlib plot." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\nParts of a Figure\n=================\n\nNow, let's have a deeper look at the components of a Matplotlib figure.\n\n![](../../_static/anatomy.png)\n\n\n:class:`~matplotlib.figure.Figure`\n----------------------------------\n\nThe **whole** figure. The figure keeps\ntrack of all the child :class:`~matplotlib.axes.Axes`, a smattering of\n'special' artists (titles, figure legends, etc), and the **canvas**.\n(Don't worry too much about the canvas, it is crucial as it is the\nobject that actually does the drawing to get you your plot, but as the\nuser it is more-or-less invisible to you). A figure can contain any\nnumber of :class:`~matplotlib.axes.Axes`, but will typically have\nat least one.\n\nThe easiest way to create a new figure is with pyplot::\n\n fig = plt.figure() # an empty figure with no Axes\n fig, ax = plt.subplots() # a figure with a single Axes\n fig, axs = plt.subplots(2, 2) # a figure with a 2x2 grid of Axes\n\nIt's convenient to create the axes together with the figure, but you can\nalso add axes later on, allowing for more complex axes layouts.\n\n:class:`~matplotlib.axes.Axes`\n------------------------------\n\nThis is what you think of as 'a plot', it is the region of the image\nwith the data space. A given figure\ncan contain many Axes, but a given :class:`~matplotlib.axes.Axes`\nobject can only be in one :class:`~matplotlib.figure.Figure`. The\nAxes contains two (or three in the case of 3D)\n:class:`~matplotlib.axis.Axis` objects (be aware of the difference\nbetween **Axes** and **Axis**) which take care of the data limits (the\ndata limits can also be controlled via the :meth:`.axes.Axes.set_xlim` and\n:meth:`.axes.Axes.set_ylim` methods). Each :class:`~.axes.Axes` has a title\n(set via :meth:`~matplotlib.axes.Axes.set_title`), an x-label (set via\n:meth:`~matplotlib.axes.Axes.set_xlabel`), and a y-label set via\n:meth:`~matplotlib.axes.Axes.set_ylabel`).\n\nThe :class:`~.axes.Axes` class and its member functions are the primary entry\npoint to working with the OO interface.\n\n:class:`~matplotlib.axis.Axis`\n------------------------------\n\nThese are the number-line-like objects. They take\ncare of setting the graph limits and generating the ticks (the marks\non the axis) and ticklabels (strings labeling the ticks). The location of\nthe ticks is determined by a `~matplotlib.ticker.Locator` object and the\nticklabel strings are formatted by a `~matplotlib.ticker.Formatter`. The\ncombination of the correct `.Locator` and `.Formatter` gives very fine\ncontrol over the tick locations and labels.\n\n:class:`~matplotlib.artist.Artist`\n----------------------------------\n\nBasically everything you can see on the figure is an artist (even the\n`.Figure`, `Axes <.axes.Axes>`, and `~.axis.Axis` objects). This includes\n`.Text` objects, `.Line2D` objects, :mod:`.collections` objects, `.Patch`\nobjects ... (you get the idea). When the figure is rendered, all of the\nartists are drawn to the **canvas**. Most Artists are tied to an Axes; such\nan Artist cannot be shared by multiple Axes, or moved from one to another.\n\n\nTypes of inputs to plotting functions\n=====================================\n\nAll of plotting functions expect `numpy.array` or `numpy.ma.masked_array` as\ninput. Classes that are 'array-like' such as `pandas` data objects\nand `numpy.matrix` may or may not work as intended. It is best to\nconvert these to `numpy.array` objects prior to plotting.\n\nFor example, to convert a `pandas.DataFrame` ::\n\n a = pandas.DataFrame(np.random.rand(4, 5), columns = list('abcde'))\n a_asarray = a.values\n\nand to convert a `numpy.matrix` ::\n\n b = np.matrix([[1, 2], [3, 4]])\n b_asarray = np.asarray(b)\n\n\nThe object-oriented interface and the pyplot interface\n======================================================\n\nAs noted above, there are essentially two ways to use Matplotlib:\n\n- Explicitly create figures and axes, and call methods on them (the\n \"object-oriented (OO) style\").\n- Rely on pyplot to automatically create and manage the figures and axes, and\n use pyplot functions for plotting.\n\nSo one can do (OO-style)\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = np.linspace(0, 2, 100)\n\n# Note that even in the OO-style, we use `.pyplot.figure` to create the figure.\nfig, ax = plt.subplots() # Create a figure and an axes.\nax.plot(x, x, label='linear') # Plot some data on the axes.\nax.plot(x, x**2, label='quadratic') # Plot more data on the axes...\nax.plot(x, x**3, label='cubic') # ... and some more.\nax.set_xlabel('x label') # Add an x-label to the axes.\nax.set_ylabel('y label') # Add a y-label to the axes.\nax.set_title(\"Simple Plot\") # Add a title to the axes.\nax.legend() # Add a legend." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or (pyplot-style)\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = np.linspace(0, 2, 100)\n\nplt.plot(x, x, label='linear') # Plot some data on the (implicit) axes.\nplt.plot(x, x**2, label='quadratic') # etc.\nplt.plot(x, x**3, label='cubic')\nplt.xlabel('x label')\nplt.ylabel('y label')\nplt.title(\"Simple Plot\")\nplt.legend()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Actually there is a third approach, for the case where you are embedding\nMatplotlib in a GUI application, which completely drops pyplot, even for\nfigure creation. We won't discuss it here; see the corresponding section in\nthe gallery for more info (`user_interfaces`).\n\nMatplotlib's documentation and examples use both the OO and the pyplot\napproaches (which are equally powerful), and you should feel free to use\neither (however, it is preferable pick one of them and stick to it, instead\nof mixing them). In general, we suggest to restrict pyplot to interactive\nplotting (e.g., in a Jupyter notebook), and to prefer the OO-style for\nnon-interactive plotting (in functions and scripts that are intended to be\nreused as part of a larger project).\n\n
In older examples, you may find examples that instead used the so-called\n ``pylab`` interface, via ``from pylab import *``. This star-import\n imports everything both from pyplot and from :mod:`numpy`, so that one\n could do ::\n\n x = linspace(0, 2, 100)\n plot(x, x, label='linear')\n ...\n\n for an even more MATLAB-like style. This approach is strongly discouraged\n nowadays and deprecated; it is only mentioned here because you may still\n encounter it in the wild.
The names of builtin backends case-insensitive; e.g., 'Qt5Agg' and\n 'qt5agg' are equivalent.
Major changes related to interactivity, and in particular the\n role and behavior of :func:`~matplotlib.pyplot.show`, were made in the\n transition to matplotlib version 1.0, and bugs were fixed in\n 1.0.1. Here we describe the version 1.0.1 behavior for the\n primary interactive backends, with the partial exception of\n *macosx*.
Interactive mode works with suitable backends in ipython and in\n the ordinary python shell, but it does *not* work in the IDLE IDE.\n If the default backend does not support interactivity, an interactive\n backend can be explicitly activated using any of the methods discussed\n in `What is a backend?`_.
Changes related to how line segments are simplified were made\n in version 2.1. Rendering time will still be improved by these\n parameters prior to 2.1, but rendering time for some kinds of\n data will be vastly improved in versions 2.1 and greater.