.. _ch05-python-matplotlib: =============================================================== Matplotlib =============================================================== An extensive examples of using `Matplotlib `_ is found at `Matplotlib example site `_. See also a summary of `pyplot commands `_. Some useful plotting options are also found at `Scipy note `_. ------------------------------------------------------------------------------ Introduction ------------------------------------------------------------------------------ ``matplotlib`` is probably the single most used Python package for 2D-graphics. It provides both a very quick way to visualize data from Python and publication-quality figures in many formats. We are going to explore matplotlib in interactive mode covering most common cases. We also look at the class library which is provided with an object-oriented interface. ------------------------------------------------------------------------------ IPython ------------------------------------------------------------------------------ ``IPython`` is an enhanced interactive Python shell that has lots of interesting features including named inputs and outputs, access to shell commands, improved debugging and many more. When we start it with the command line argument ``--pylab``, it allows interactive matplotlib sessions that has Matlab/Mathematica-like functionality. ------------------------------------------------------------------------------ pylab ------------------------------------------------------------------------------ ``pylab`` provides a procedural interface to the matplotlib object-oriented plotting library. It is modeled closely after Matlab(TM). Therefore, the majority of plotting commands in pylab has Matlab(TM) analogs with similar arguments. Important commands are explained with interactive examples. .. note:: ``pylab`` includes not only ``matplotlib`` but also ``numpy``. ------------------------------------------------------------------------------ Matplotlib and pylab ------------------------------------------------------------------------------ There are nice tools for making plots of 1d and 2d data (curves, contour plots, etc.) in the module `matplotlib `_. Many of these plot commands are very similar to those in Matlab. To see some of what's possible (and learn how to do it), visit the `matplotlib gallery `_. Clicking on a figure displays the Python commands needed to create it. The best way to get matplotlib working interactively in a standard Python shell is to do:: $ python >>> import numpy as np >>> import matplotlib.pyplot as plt >>> plt.interactive(True) >>> x = np.linspace(-1, 1, 20) >>> plt.plot(x, x**2, 'o-') Notice also that, since ``pylab`` includes both ``matplotlib`` and ``numpy``, you can get the exact same features using a more compact way as follow:: $ python >>> import pylab >>> pylab.interactive(True) Then you should be able to do:: >>> x = pylab.linspace(-1, 1, 20) >>> pylab.plot(x, x**2, 'o-') and see a plot of a parabola appear. See Figure :num:`fig01`. .. _fig01: .. figure:: ./_figures/figure_1.png :align: center :scale: 50 % A simple plot of :math:`y = x^2`. You should also be able to use the buttons at the bottom of the window, e.g click the magnifying glass and then use the mouse to select a rectangle in the plot to zoom in. Alternatively, you could do:: >>> from pylab import * >>> interactive(True) With this approach you don't need to start every pylab function name with pylab, e.g.:: >>> x = linspace(-1, 1, 20) >>> plot(x, x**2, 'o-') In these notes we'll generally use module names just so it's clear where things come from. If you use the IPython shell instead, you can do:: $ ipython --pylab In [1]: x = linspace(-1, 1, 20) In [2]: plot(x, x**2, 'o-') The ``--pylab`` flag causes everything to be imported from pylab and set up for interactive plotting. .. _ch05-python-matplotlib-flash1d-hdf5: ------------------------------------------------------------------------------ Labels, titles, grids, overplots, legends ------------------------------------------------------------------------------ We continue using a plotting mode in a standard Python shell in our first example. To add titles in :math:`x` and :math:`y` axes, and a plot title:: >>> plt.xlabel('x') >>> plt.ylabel('y') >>> plt.title('y=x^2') .. note:: To use greek letters as in LaTex, you should use raw strings (precede the quotes with an ``r``) and surround the math text with dollar signs ($), as in TeX. For example:: >>> plt.xlabel(r'$\alpha$') One can also put some grid lines:: >>> plt.grid(True) .. _fig02: .. figure:: ./_figures/figure_2.png :align: center :scale: 50 % A simple plot of :math:`y = x^2`. We now consider a more richful example of plotting more than one functions in the same figure. In the script below, we’ve instantiated (and commented) all the figure settings that influence the appearance of the plot. The settings have been explicitly set to their default values, but now you can interactively play with the values to explore their effects (see Line properties and Line styles below). .. literalinclude:: ./codes/plot_sin_cos.py :language: python :linenos: .. _fig03: .. figure:: ./_figures/figure_sin_cos.png :align: center :scale: 50 % A figure of :math:`\sin(x)` and :math:`\cos(x)` functions over :math:`[-\pi,\pi]`. The next example demonstrates a simple way to read in a FLASH 2D data, extract a 1D slice, and plot a 1D density profile. The test problem is called the Shu-Osher hydrodynamics shock tube problem, details of which is available at `the FLASH users guide `_. .. literalinclude:: ./codes/plot_flash_1d.py :language: python :linenos: .. _fig04: .. figure:: ./_figures/figure_3.png :align: center :scale: 50 % A 1D density profile of the Shu-Osher shock tube problem. .. _ch05-python-matplotlib-flash2d3d-hdf5: ------------------------------------------------------------------------------ Advanced plots -- 2D, 3D plots, subplots and more ------------------------------------------------------------------------------ We have so far only covered some basic features of producing 1D plots. Obviously there are lot more to learn. We briefly take a look at an example which produces 2D and 3D plots of a FLASH code simulation. The simulation is a 2D Sedov explosion on a uniform grid of size :math:`256 \times 256` (see more about the problem in `the FLASH users guide `_ ). .. literalinclude:: ./codes/plot_flash_2d.py :language: python :linenos: * 1D slice plot using ``plot``, lines 111 - 122: .. _fig05: .. figure:: ./_figures/figure_4.png :align: center :scale: 50 % 1D slice plot of 2D density at t=0.05. * 2D plot using ``imshow``, lines 126 - 131: .. _fig06: .. figure:: ./_figures/figure_5.png :align: center :scale: 50 % 2D pseducolor plot of density at t=0.05. * 3D surface plot using ``plot_surface``, lines 134 - 140: .. _fig07: .. figure:: ./_figures/figure_6.png :align: center :scale: 50 % 3D surface plot of density at t=0.05. * 3D wireframe plot using ``plot_wireframe``, lines 144 - 150: .. _fig08: .. figure:: ./_figures/figure_7.png :align: center :scale: 50 % 3D wireframe plot of density at t=0.05. * 3D contour plot using ``contourf``, lines 153 - 159: .. _fig09: .. figure:: ./_figures/figure_8.png :align: center :scale: 50 % 3D contour plot of density at t=0.05. One can also produce a plot with multiple subplots: .. literalinclude:: ./codes/plot_flash_subplot.py :language: python :linenos: .. note:: Notice in the above example that there are two ``for-loops``, where the first loop finds the global min and max of the time varying densities over a series of times, :math:`t=0.01, 0.02, 0.03, 0.04, 0.05, 0.06`. The second loop uses the obtained min (:math:`\rho_{\min}`) and max (:math:`\rho_{\max}`) in order to plot six subfigures in the same consistent color scheme. Otherwise, all six subfigures would be in different color scales, which will make it hard to cross compare the density values over time. .. _fig10: .. figure:: ./_figures/figure_9.png :align: center :scale: 60 % 2D subplots of density at various times. You can learn more from the provided examples from Matplotlib tutorial pages and see how you can plot them: * `matplotlib homepage `_ * `gallery `_ * `3D plotting tips `_ * `pyplot commands `_