Tutorial: Plotting with matplotlib

This tutorial will give you an introductory tutorial to plotting data with matplotlib.


In [1]:
%matplotlib inline

To import the pyplot library of the matplotlib simply do:


In [2]:
import matplotlib.pyplot as plt

Plot in canvas with the plot command:


In [3]:
plt.plot([1,2,3],[4,5,1])


Out[3]:
[<matplotlib.lines.Line2D at 0x106d75c90>]

The above simply makes the canvas (in this tutorial since the matplotlib is loaded inline the plot is produced, while in a script the plot is not yet shown). To show the plotted canvas simply ask pyplot to show the plot:


In [5]:
plt.show()

Title and labels

To set labels ask plt to modify the title, xlabel and ylabel:


In [7]:
plt.title("Info");
plt.xlabel("X");
plt.ylabel("Y");



Styles

To use styles import the styles library of pyplot


In [9]:
from matplotlib import style

and to use it


In [10]:
style.use("ggplot")

In [11]:
plt.plot([1,2,3],[4,5,1])


Out[11]:
[<matplotlib.lines.Line2D at 0x1070b4090>]

One can also play around with the arguments of the plot command. For example:


In [12]:
plt.plot([1,2,3],[4,5,1], linewidth=5)


Out[12]:
[<matplotlib.lines.Line2D at 0x1071aa7d0>]

Plot two lines and label them in the legend and also make a grid:


In [13]:
x = [5,8,10];
y = [12,16,6];
x2 = [6,9,11];
y2 = [6,15,7];

In [15]:
plt.plot(x,y,'g',label='line one', linewidth=5); # a green line of width 5 called line one
plt.plot(x2,y2,'c',label='line one', linewidth=5); # a cyan line of width 5 called line two
plt.title("Info");
plt.xlabel("X"); 
plt.xlabel("Y");

plt.legend(); ## to make the legend USE THIS AFTER THE PLOT LINES

plt.grid(True, color='k');
plt.show()



In [ ]: