{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Usage Guide\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\nMatplotlib graphs your data on `~.figure.Figure`\\s (e.g., windows, Jupyter\nwidgets, etc.), each of which can contain one or more `~.axes.Axes`, an\narea where points can be specified in terms of x-y coordinates, or theta-r\nin a polar plot, x-y-z in a 3D plot, etc. The simplest 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": [ "\n## Parts of a Figure\n\nHere is a more detailed layout of the components of a Matplotlib figure.\n\n \n\n### :class:`~matplotlib.figure.Figure`\n\nThe **whole** figure. The figure keeps\ntrack of all the child :class:`~matplotlib.axes.Axes`, a group of\n'special' artists (titles, figure legends, etc), and the **canvas**.\n(The canvas is not the primary focus. It is crucial as it is the\nobject that actually does the drawing to get you your plot, but as\nthe user, it is mostly 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\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\nThese are the objects most similar to a number line.\nThey set graph limits and generate 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\nBasically, everything visible on the figure is an artist (even\n`.Figure`, `Axes <.axes.Axes>`, and `~.axis.Axis` objects). This includes\n`.Text` objects, `.Line2D` objects, :mod:`.collections` objects, `.Patch`\nobjects, etc... 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\n## Types of inputs to plotting functions\n\nAll of plotting functions expect `numpy.array` or `numpy.ma.masked_array` as\ninput. Classes that are similar to arrays ('array-like') such as `pandas`\ndata objects and `numpy.matrix` may not work as intended. Common convention\nis to convert 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\n## The object-oriented interface and the pyplot interface\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) # Sample data.\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) # Sample data.\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": [ "In addition, there is a third approach, for the case when 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

#### Note

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.

\n\nIf you need to make the same plots over and over\nagain with different data sets, use the recommended signature function below.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def my_plotter(ax, data1, data2, param_dict):\n \"\"\"\n A helper function to make a graph\n\n Parameters\n ----------\n ax : Axes\n The axes to draw to\n\n data1 : array\n The x data\n\n data2 : array\n The y data\n\n param_dict : dict\n Dictionary of keyword arguments to pass to ax.plot\n\n Returns\n -------\n out : list\n list of artists added\n \"\"\"\n out = ax.plot(data1, data2, **param_dict)\n return out" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which you would then use as:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "data1, data2, data3, data4 = np.random.randn(4, 100)\nfig, ax = plt.subplots(1, 1)\nmy_plotter(ax, data1, data2, {'marker': 'x'})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or if you wanted to have two sub-plots:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, (ax1, ax2) = plt.subplots(1, 2)\nmy_plotter(ax1, data1, data2, {'marker': 'x'})\nmy_plotter(ax2, data3, data4, {'marker': 'o'})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These examples provide convenience for more complex graphs.\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.7" } }, "nbformat": 4, "nbformat_minor": 0 }