MatPlotLib

MatPlotLib is another add on library. It allows us to plot anything we desire. But first, as with NumPy, we need to import it.


In [17]:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline 
#^^^This line tells Jupyter to render the plots inside the notebook^^^

The main command used in matplotlib is the plot command. To find out how to use it, we will use some of the sweet functionality of the Jupyter notebook. To retrieve the documentation on any command, type the command into a cell with a question mark after it.


In [18]:
plt.plot?

As we can see, there is a lot of information. The important part are the four indented lines showing you what parameters you can use when you call plot. Let's start plotting some things.


In [24]:
x = np.linspace(0, np.pi*2, 10)
y = np.sin(x)
plt.plot(x,y)


Out[24]:
[<matplotlib.lines.Line2D at 0x7f3823e02e48>]

In [25]:
x = np.linspace(0, np.pi*2, 100)
y = np.sin(x)
plt.plot(x,y)


Out[25]:
[<matplotlib.lines.Line2D at 0x7f3823d605c0>]

That is really all there is to matplotlib. All that is left to discuss is making plots pretty. Let's say that you have made some wondeful measurements of some physical quantity and calculated some other physical quantity. Then you drew some amazing conclusion and you are sure your advisor will love it! Let's model this in the next cell.


In [34]:
x = np.linspace(0,10,1000) #Wonderful measurements
y = x**np.exp(np.sin(x**2))-np.sin(x*np.log(x)) #Wonderful Calculations
plt.plot(x,y)


/usr/local/lib/python3.4/dist-packages/IPython/kernel/__main__.py:2: RuntimeWarning: divide by zero encountered in log
  from IPython.kernel.zmq import kernelapp as app
/usr/local/lib/python3.4/dist-packages/IPython/kernel/__main__.py:2: RuntimeWarning: invalid value encountered in multiply
  from IPython.kernel.zmq import kernelapp as app
Out[34]:
[<matplotlib.lines.Line2D at 0x7f3823bee588>]

Aha! According to the plot above, my Grand Unified Theory is complete. When your advisor looks at the graph, they might pass out due to its poor quality. This graph needs x labels, y labels, a title and maybe even a legend! Doing those things is astoundingly easy! Let's check it out.


In [37]:
plt.plot(x,y, label="Some Physics or Something")
plt.xlabel("I dun measured this!")
plt.ylabel("I dun calculated this!")
plt.title("I dun made this plot!")
plt.legend()


Out[37]:
<matplotlib.legend.Legend at 0x7f3823b11ba8>

I leave this here with less information than I could have given so that you can go explore the documentation.

http://matplotlib.org/index.html

Later in the course we will be learning about effective googling, which will aid you in your ability to find out how to do things.


In [ ]: