{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Quick start guide\n\nThis tutorial covers some basic usage patterns and best practices to\nhelp you get started with Matplotlib.\n\n.. redirect-from:: /tutorials/introductory/usage\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A simple example\n\nMatplotlib graphs your data on `.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": [ "\n## Parts of a Figure\n\nHere are 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, colorbars, etc), and\neven nested subfigures.\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 is often convenient to create the Axes together with the Figure, but you\ncan also manually add Axes later on. Note that many\n:doc:`Matplotlib backends ` support zooming and\npanning on figure windows.\n\n### :class:`~matplotlib.axes.Axes`\n\nAn Axes is an Artist attached to a Figure that contains a region for\nplotting data, and usually includes two (or three in the case of 3D)\n:class:`~matplotlib.axis.Axis` objects (be aware of the difference\nbetween **Axes** and **Axis**) that provide ticks and tick labels to\nprovide scales for the data in the Axes. Each :class:`~.axes.Axes` also\nhas 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\nentry point to working with the OOP interface, and have most of the\nplotting methods defined on them (e.g. ``ax.plot()``, shown above, uses\nthe `~.Axes.plot` method)\n\n### :class:`~matplotlib.axis.Axis`\n\nThese objects set the scale and limits and generate ticks (the marks\non the Axis) and ticklabels (strings labeling the ticks). The location\nof the 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\nPlotting functions expect `numpy.array` or `numpy.ma.masked_array` as\ninput, or objects that can be passed to `numpy.asarray`.\nClasses 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.\nFor example, to convert a `numpy.matrix` ::\n\n b = np.matrix([[1, 2], [3, 4]])\n b_asarray = np.asarray(b)\n\nMost methods will also parse an addressable object like a *dict*, a\n`numpy.recarray`, or a `pandas.DataFrame`. Matplotlib allows you to\nprovide the ``data`` keyword argument and generate plots passing the\nstrings corresponding to the *x* and *y* variables.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "np.random.seed(19680801) # seed the random number generator.\ndata = {'a': np.arange(50),\n 'c': np.random.randint(0, 50, 50),\n 'd': np.random.randn(50)}\ndata['b'] = data['a'] + 10 * np.random.randn(50)\ndata['d'] = np.abs(data['d']) * 100\n\nfig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')\nax.scatter('a', 'b', c='c', s='d', data=data)\nax.set_xlabel('entry a')\nax.set_ylabel('entry b')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n## Coding styles\n\n### The explicit and the implicit interfaces\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 implicitly create and manage the Figures and Axes, and\n use pyplot functions for plotting.\n\nSee `api_interfaces` for an explanation of the tradeoffs between the\nimplicit and explicit interfaces.\n\nSo one can use the 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(figsize=(5, 2.7), layout='constrained')\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 the 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.figure(figsize=(5, 2.7), layout='constrained')\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. See the corresponding section in the gallery for more info:\n`user_interfaces`.)\n\nMatplotlib's documentation and examples use both the OO and the pyplot\nstyles. In general, we suggest using the OO style, particularly for\ncomplicated plots, and functions and scripts that are intended to be reused\nas part of a larger project. However, the pyplot style can be very convenient\nfor quick interactive work.\n\n
You may find older examples that use the ``pylab`` interface,\n via ``from pylab import *``. This approach is strongly deprecated.