First introduction to Matplotlib ================================ The last big topic to look at is plotting. Thanks to a very nice plotting library called ``matplotlib`` plotting of (scientific) data from within python has become almost trivial. The webpage of Matplotlib is located at: http://matplotlib.org/index.html Matplotlib is mainly for two-dimensional plots (although there are some limited capabilities for 3 dimensional stuff.) We will concentrate on 2D and only show a few very basic examples. Matplotlib can do a few things more than just plotting. We will use only one submodule, namely ``matplotlib.pyplot``. This is what we need to import before we can do any plotting. .. .. note:: If you use *spyder* as your Python IDE you may run into some troubles with matplotlib on the *fedora machines at ETH*. There are two workarounds for this, please see :doc:`matplotlib_spyder`. First steps ----------- Now let start with plotting and make a first simple example: .. sourcecode:: ipython In [1]: from numpy import * In [2]: from matplotlib.pyplot import * In [3]: x = linspace(-2, 2, 200) In [4]: y = (x**5 + 4*x**4 + 3*x**3 + 2*x**2 + x + 1)*exp(-x**2) In [5]: figure() # Make a new figure Out[5]: In [6]: plot(x, y) # Plot some data Out[6]: [] In [7]: grid(True) # Set the thin grid lines In [8]: savefig("plot_1.png") # Save the figure to a file "png", # "pdf", "eps" and some more file types are valid And the result then looks like: .. image:: images/plot_1.png :scale: 50 % With only a couple of lines of python we get such a nice plot! Additionally to saving the figure to a file we can also show it right from the python interpreter by using the command ``show()`` instead of ``savefig``. Now there are many options available to change the look or other features of the resulting figure. Usually most have reasonable defaults. In the next example we show some useful things: .. sourcecode:: ipython In [9]: from scipy.special import gamma In [10]: from scipy.special.orthogonal import eval_hermite In [11]: x = linspace(-5, 5, 1000) In [12]: psi = lambda n,x: 1.0/sqrt((2**n*gamma(n+1)*sqrt(pi))) * exp(-x**2/2.0) * eval_hermite(n, x) In [13]: figure() Out[13]: In [14]: for n in xrange(6): ....: plot(x, psi(n,x), label=r"$\psi_"+str(n)+r"(x)$") # The 'label' to put into the legend ....: In [15]: grid(True) In [16]: xlim(-5,5) # Specify the range of the x axis shown Out[16]: (-5, 5) In [17]: ylim(-0.8,0.8) # Specify the range of the y axis shown Out[17]: (-0.8, 0.8) In [18]: xlabel(r"$x$") # Put a label on the x axis Out[18]: In [19]: ylabel(r"$\psi_n(x)$") # Put a label on the y axis Out[19]: In [20]: legend(loc="lower right") # Add a legend table Out[20]: In [21]: title(r"Hermite functions $\psi_n$") # And a title on top of the figure Out[21]: In [22]: savefig("plot_2.png") Which results in: .. image:: images/plot_2.png :scale: 100 % We can easily make a plot that contains several so called *subplots* .. sourcecode:: ipython In [3]: x = linspace(-2, 2, 100) In [4]: figure() Out[4]: In [5]: subplot(2,2,1) # Two rows and two cols of plots, select first one Out[5]: In [6]: plot(x, x) Out[6]: [] In [7]: subplot(2,2,2) # Two rows and two cols of plots, select second one Out[7]: In [8]: plot(x, x**2) Out[8]: [] In [9]: subplot(2,2,3) # Two rows and two cols of plots, select third one Out[9]: In [10]: plot(x, x**3) Out[10]: [] In [11]: subplot(2,2,4) # Two rows and two cols of plots, select fourth one Out[11]: In [12]: plot(x, x**4) Out[12]: [] In [13]: savefig("plot_subplots.png") and we get the following image .. image:: images/plot_subplots.png :scale: 80 % We can make one (command ``semilogx``, ``semilogy``) or both (command ``loglog``) axes log scale .. sourcecode:: ipython In [70]: figure() Out[70]: In [71]: semilogy(x, 2**x, "r-", label=r"$2^x$") Out[71]: [] In [72]: semilogy(x, 3**x, "g-", label=r"$3^x$") Out[72]: [] In [73]: semilogy(x, 4**x, "b-", label=r"$4^x$") Out[73]: [] In [74]: semilogy(x, 5**x, "c-", label=r"$5^x$") Out[74]: [] In [75]: semilogy(x, 6**x, "m-", label=r"$6^x$") Out[75]: [] In [76]: semilogy(x, 7**x, "y-", label=r"$7^x$") Out[76]: [] In [77]: grid(True) In [78]: legend(loc="lower right") Out[78]: In [79]: savefig("plot_semilogy.png") .. image:: images/plot_semilogy.png :scale: 80 % .. sourcecode:: ipython In [35]: figure() Out[35]: In [36]: loglog(x, x, "r-", label=r"$x$") Out[36]: [] In [37]: loglog(x, x**2, "g-", label=r"$x^2$") Out[37]: [] In [38]: loglog(x, x**3, "b-", label=r"$x^3$") Out[38]: [] In [39]: loglog(x, x**4, "c-", label=r"$x^4$") Out[39]: [] In [40]: loglog(x, x**5, "m-", label=r"$x^5$") Out[40]: [] In [41]: loglog(x, x**6, "y-", label=r"$x^6$") Out[41]: [] In [42]: grid(True) In [43]: legend(loc="lower right") Out[43]: In [44]: savefig("plot_loglog.png") .. image:: images/plot_loglog.png :scale: 80 % Log scale plots are commonly used for convergence plots as we will see later. Often one wants to fit some polynomials and plot the result. This is what the following example does. (For fitting in log scaled plots one has to apply ``log`` manually before doing a ``polyfit``. The result has to be transformed back again.) .. sourcecode:: ipython In [6]: x = random.rand(10) # Some random points In [7]: offset = random.rand(10) In [8]: y = x + 0.25*offset In [9]: p = polyfit(x, y, 1) # Fit a polynomial of first degree (line) In [10]: u = linspace(-0.1, 1.1, 10) # Evaluate the polynomial at (other) points In [11]: v = polyval(p, u) In [12]: figure() Out[12]: In [13]: plot(x, y, ".") Out[13]: [] In [14]: plot(u, v, "--r") Out[14]: [] In [15]: grid(True) In [16]: show() .. image:: images/polyfit.png :scale: 50 % Matplotlib knows many different line and marker styles. The following plot show only a small subset of what's available. .. image:: images/plot_linestyles.png :scale: 50 % .. image:: images/plot_markerstyles.png :scale: 50 % For some more examples see http://matplotlib.org/examples/pylab_examples/line_styles.html and http://matplotlib.org/examples/pylab_examples/filledmarker_demo.html and the reference plots: * `Line Styles `_ * `Markers `_ There are several other plot types too, for example scatter plots and polar plots .. sourcecode:: ipython In [141]: x = random.rand(100) In [142]: y = random.rand(100) In [143]: figure() Out[143]: In [144]: scatter(x, y) Out[144]: In [145]: grid(True) In [146]: savefig("plot_scatter.png") .. image:: images/plot_scatter.png :scale: 50 % .. sourcecode:: ipython In [148]: phi = linspace(0, 2*pi, 200) In [149]: figure() Out[149]: In [150]: polar(phi, sin(phi)*cos(phi)) Out[150]: [] In [151]: grid(True) In [152]: savefig("plot_polar.png") .. image:: images/plot_polar.png :scale: 50 % A simple contour plot of an implicit function .. sourcecode:: ipython In [2]: x = linspace(-8,8,100) In [3]: y = linspace(-8,8,100) In [4]: X, Y = meshgrid(x, y) In [5]: f = lambda u,v: sin(u)*cos(2*v)+0.1 In [6]: Z = f(X, Y) In [7]: contour(X,Y,Z) # Plot the contour lines Out[7]: In [8]: colorbar() # Make a legend for the colors Out[8]: In [9]: show() .. image:: images/contour.png :scale: 50 % Matplotlib knows many more plot types like advanced contour and density plots, matrix and discrete plots, stem plots, stream lines, vector fields, various types of charts and histograms as well as some (limited) 3D plotting. To end this chapter we show a somehwat longer contour plot example .. literalinclude:: TutCodes/qfmesh.py :language: python .. plot:: TutCodes/qfmesh.py The official tutorial is also quite a good introduction. You should continue reading: http://matplotlib.org/users/pyplot_tutorial.html if you want to know more right now. Another very good tutorial with many examples is this one: http://www.labri.fr/perso/nrougier/teaching/matplotlib/ The Matplotlib Gallery ---------------------- It is always a good idea to look at the Matplotlib gallery http://matplotlib.org/gallery.html when you intend to do a new kind of plot and are not sure how to continue best. The gallery contains many examples with full source code of almost every plot imaginable. You might get either your ploting program already tipped or good visualization ideas. There are also two less prominent spots to look for examples: http://matplotlib.org/users/screenshots.html http://matplotlib.org/examples/index.html Further information on Matplotlib --------------------------------- - `User's Guide `_