#!/usr/bin/env python # coding: utf-8 # # # # # Basic Plotting in Python using Matplotlib # # ### Modules - Basics #
# By Magnus A. Gjennestad, Vegard Hagen, Aksel Kvaal, Morten Vassvik, Trygve B. Wiig and Peter Berg #
# Last edited: March 11th 2018 # ___ # The following is a brief introduction to plotting in Python, using the library `matplotlib`. From the matplotlib [home page](http://matplotlib.org): *"matplotlib tries to make easy things easy and hard things possible. (...) For simple plotting the pyplot interface provides a MATLAB-like interface, particularly when combined with IPython."* Since this is written in IPython Notebook, pyplot is a natural first choice. Let's get started! # In[1]: import numpy as np from matplotlib import pyplot as plt # Above we have imported numpy, a package for scientific computing with Python, and pyplot. pyplot is part of matplotlib, as seen from how it is imported. Alternatively, it could be imported as follows # In[2]: import matplotlib.pyplot as plt # Also, notice how we have given shorter nicknames to both the numpy and pyplot import, in order to save some typing. Finally, we want to display the plots in the Notebook, not in an external window. To do this we use the command # In[3]: get_ipython().run_line_magic('matplotlib', 'inline') # ### Plotting a Function # __The task:__ # # How to plot a function \$f\$, given # \$\$y=f(x)\$\$ # along an interval # \$\$x=[a,b].\$\$ # # # __The Method:__ # # Two steps are required in the code: # 1. We need to define the range for \$x\$. # 2. We use the \$plt.plot\$ command in which the function is defined. # __Example:__ # # We would like to plot the function # \$\$f(x)=3x^2+x-1\$\$ # for the interval # \$\$x=[-1,2].\$\$ # # __Step 1: Defining the range of \$x\$__ # # In the Python code, we use the command # In[4]: x = np.linspace(-1, 2, 301) # This creates an array of \$301\$ linearly spaced, discrete values of x between \$-1\$ and \$2\$. # # __Step 2: Using the \$plot\$ command__ # # The \$plt.plot\$ command allows us to plot the function. # # We need to specify the variable which is represented by the horizontal axis. # It is mentioned first in the plot command. # # The second expression represents the function, corresponding to the # vertical axis. # In our case, we need to write # In[5]: plt.plot(x, 3*x**2+x-1); # __Further Steps: Adding axes labels, a legend, a plot title, etc.__ # # One option is to add axes labels, a legend, a title, a grid etc. to the plot by using the following commands: # In[6]: plt.plot(x, 3*x**2+x-1) plt.ylabel(r'\$f(x)\$') # label on y-axis plt.xlabel(r'\$x\$') # label on x-axis plt.title(r'Plot of \$f(x)=3x^2+x-1\$') # plot title plt.legend([r'\$f(x)\$'],loc=4) # legend, loc gives location of the legend plt.grid(); # grid # Comment and uncomment the various commends to see how they effect the plot. # # You can also change the size of the figure quickly by using the following command: # In[10]: plt.figure(figsize=(16, 8)) # create figure and change size plt.plot(x, 3*x**2+x-1) plt.ylabel(r'\$f(x)\$') # label on y-axis plt.xlabel(r'\$x\$') # label on x-axis plt.title(r'Plot of \$f(x)=3x^2+x-1\$') # plot title plt.legend([r'\$f(x)\$'], loc=2) # legend plt.grid(); # grid # The \$plt.figure()\$ command also lets you set other parameters related to the figure. In most of the other modules and examples, we have set common figure parameters in the beginning of the module/example, by using the following lines of code: # In[11]: from matplotlib import rc # Set common figure parameters: newparams = {'axes.labelsize': 11, 'axes.linewidth': 1, 'savefig.dpi': 300, 'lines.linewidth': 1.0, 'figure.figsize': (8, 3), 'ytick.labelsize': 10, 'xtick.labelsize': 10, 'ytick.major.pad': 5, 'xtick.major.pad': 5,} plt.rcParams.update(newparams) # ### Multiple Functions in One Plot # Let us plot # \$\$g(x)=3x^3+1\$\$ # in addition to our previous function: # In[12]: plt.plot(x, 3*x**2+x-1, x, 3*x**3+1); # We need to make clear what graph corresponds to what function! We do this using the \$legend()\$ command: # In[13]: plt.plot(x, 3*x**2+x-1, x, 3*x**3+1) # Create legend, and change legend location using "loc" plt.legend([r'\$f(x)\$',r'\$g(x)\$'], loc=2); # This makes things easier to track. # ### Final Note # There are many more commands and options for plotting functions than presented # in this module. However, we covered the most important ones. # # We need to use the matplotlib and pyplot online references when additional plotting features are required.