Matplotlib Tutorial

Usually what we use is the pyplot module of matplotlib. Let's inline plt and make a simple plot with titles for the axes.


In [2]:
from matplotlib import pyplot as plt
%matplotlib inline

In [9]:
plt.plot([5,6,7,8],[7,4,8,4])

## Adding labels
plt.title("Random Plot")
plt.xlabel("$1/2\cdot x$")
plt.ylabel("Dispersion $[m]$")


Out[9]:
<matplotlib.text.Text at 0x1117b6590>

Styles

We can use a simple style usage for the plots made by plt.

Let's try and use the ggplot style


In [11]:
# import the styles
from matplotlib import style

# select the 'ggplot' style from the default ones
style.use('ggplot')

# and make the same plot -- pretty cool heh? :)
plt.plot([5,6,7,8],[7,4,8,4])
plt.title("Random Plot")
plt.xlabel("$1/2\cdot x$")
plt.ylabel("Dispersion $[m]$")


Out[11]:
<matplotlib.text.Text at 0x11192f4d0>

We can also use some of the formatting options in the plot command. For example color, width, label, etc.


In [21]:
# add 2 plots on the same canvas
plt.plot([2,3,4],[4,9,16], color='green', label="$x^2", lw=2)
plt.plot([2,3,4],[8,27,64], color='red', label="$x^3", lw=3)

# add the legend:
plt.legend()

# add grid
plt.grid(True, color='blue')



Bar chart and Scatter plots

Using the bar and scatter functions we can define a specific kind of plot...


In [22]:
style.use('ggplot')

x = [5,10,15]
y = [6,7,8]

x2 = [6, 7,8]
y2 = [10,11,12]

In [23]:
# now draw a bar chart
plt.bar(x,y)


Out[23]:
<Container object of 3 artists>

In [35]:
# now draw a bar chart
plt.bar(x,y, align='center')
# and let's add another one
plt.bar(x2,y2, color='green', align='center')  #align=center centers
                                       # the bar around the value
                                        # of the value it represents


Out[35]:
<Container object of 3 artists>

Or try a scatter plot


In [37]:
plt.scatter(x,y, label="one")
plt.scatter(x2,y2, color='r', label="two")
plt.legend()


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

Reading from CSV file using NumPy

Say we create a csv file name test.csv. We can use numpy to load the file and use matplotlib to plot it!


In [38]:
import numpy as np # load numpy

In [44]:
x,y = np.loadtxt('test.csv',
                unpack=True,  # unpack the values into x and y ...
                delimiter=',') # these values are separated by a ','
                               # else unpacks the whole dataset into a 
                               # single value (list of lists...)

In [45]:
print x


[  1.   2.   3.   4.   5.   6.   7.   8.   9.  10.  11.  12.  13.  14.  15.
  16.]

In [46]:
plt.plot(x,y)


Out[46]:
[<matplotlib.lines.Line2D at 0x112f95410>]

In [ ]:


In [ ]: