Matplotlib Quick Starter


Introduction

Matplotlib is an open source plotting library for Python (NumPy), designed closely to MATLAB.

import datetime;
today = datetime.date.today();
print("Last update to this tutorial is on: " + str(today) + '.');

Last update to this tutorial is on: 2017-04-20.

Installation

Python 3.X (with many useful libs such NumPy, Matplotlib) & Jupyter notebook (GUI Python Code Editor, try it online here: https://try.jupyter.org/)

Follow the instructions on installing Anaconda: https://jupyter.org/install.html (Select the Python 3.6 Version)

Jupyter notebook Startup

Open CMD, type command “jupyter notebook”, or use GUI/click the shortcut provided by Anaconda. A Brower tab will then open automatically which will serve as the Jupyter notebook GUI.

Basic Concepts

Figure, Axes, Axis, Label, Title.
Basic Concepts in One Picture
(Source: https://stackoverflow.com/questions/5575451/difference-between-axes-and-axis-in-matplotlib)

Caveats (differences from R/Matlab)

  • >”Python uses whitespace indentation to delimit blocks 鈥?rather than curly braces (such as R) or keywords (like Matlab).”
  • Python Array index starts from 0, not 1.
a=[1,2,3];print(a[0]);print(a[0:3]);print(a[1:2]);

1
[1, 2, 3]
[2]

print(range(0,3));[print(item) for item in range(0,3)];

range(0, 3)
0
1
2

[None, None, None]

import numpy as np;
print(np.arange(0,3));

[0 1 2]

print(np.arange(1,3));

[1 2]

Data Frame

Use the Pandas library’s DataFrame.

import pandas as pd;
df = pd.DataFrame(np.random.randn(10, 4),
columns=['A', 'B', 'C', 'D'])
print(df);
#save as csv
#http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html
#without row&col names
df.to_csv("testdf.csv", sep=',', encoding='utf-8', header=False, index=False);
#with row&col names
df.to_csv("testdf_h.csv", sep=',', encoding='utf-8');

A B C D
0 -1.014364 1.596540 -0.108221 -1.823591
1 -0.116949 -0.689782 1.079104 -1.789734
2 -0.142476 0.291735 -1.131466 0.434949
3 0.244108 0.750199 -0.071948 -0.712610
4 0.231627 -1.088888 -0.297135 -1.035525
5 -0.208720 1.399208 -0.056391 0.337395
6 -0.110237 0.107358 -0.477970 0.146098
7 -1.322285 -1.784505 -0.430574 0.301780
8 1.160056 0.219417 -0.004264 0.295931
9 -0.289534 -0.847578 -1.248237 0.423540

print(df.A);print(df['A']);
print(df.head(2));print(df.tail(1));
print(df[0:2]);
#more on indexing DataFrame: http://pandas.pydata.org/pandas-docs/stable/indexing.html

0 -1.014364
1 -0.116949
2 -0.142476
3 0.244108
4 0.231627
5 -0.208720
6 -0.110237
7 -1.322285
8 1.160056
9 -0.289534
Name: A, dtype: float64
0 -1.014364
1 -0.116949
2 -0.142476
3 0.244108
4 0.231627
5 -0.208720
6 -0.110237
7 -1.322285
8 1.160056
9 -0.289534
Name: A, dtype: float64
A B C D
0 -1.014364 1.596540 -0.108221 -1.823591
1 -0.116949 -0.689782 1.079104 -1.789734
A B C D
9 -0.289534 -0.847578 -1.248237 0.42354
A B C D
0 -1.014364 1.596540 -0.108221 -1.823591
1 -0.116949 -0.689782 1.079104 -1.789734

#plot the dataframe
import matplotlib;
df.plot();
from matplotlib import pyplot as plt;
#import seaborn as sns;#for prettier and more modern looking plots
plt.show();

png

Data Reading

#.csv
data = np.genfromtxt('testdf.csv', delimiter=',');
print(data);

[[-1.01436359 1.59653987 -0.10822136 -1.82359099]
[-0.11694886 -0.68978195 1.07910421 -1.78973429]
[-0.14247617 0.2917351 -1.13146572 0.43494858]
[ 0.24410795 0.75019903 -0.07194834 -0.71261019]
[ 0.23162687 -1.08888755 -0.29713512 -1.03552483]
[-0.2087203 1.39920758 -0.0563915 0.33739505]
[-0.11023713 0.10735848 -0.47797021 0.14609759]
[-1.32228453 -1.78450518 -0.430574 0.30177967]
[ 1.16005589 0.21941725 -0.00426369 0.29593072]
[-0.28953365 -0.84757817 -1.24823735 0.42354013]]

df = pd.read_csv('testdf_h.csv', index_col=0);
print(df);

A B C D
0 -1.014364 1.596540 -0.108221 -1.823591
1 -0.116949 -0.689782 1.079104 -1.789734
2 -0.142476 0.291735 -1.131466 0.434949
3 0.244108 0.750199 -0.071948 -0.712610
4 0.231627 -1.088888 -0.297135 -1.035525
5 -0.208720 1.399208 -0.056391 0.337395
6 -0.110237 0.107358 -0.477970 0.146098
7 -1.322285 -1.784505 -0.430574 0.301780
8 1.160056 0.219417 -0.004264 0.295931
9 -0.289534 -0.847578 -1.248237 0.423540

#.mat
#https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html
import scipy.io;
mat = scipy.io.loadmat('test.mat');
print(mat);
print(mat['statv']);
a = mat['statv'];
print(a[0][1]);

{‘header‘: b’MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Sun Sep 20 23:44:24 2015’, ‘version‘: ‘1.0’, ‘globals‘: [], ‘statv’: array([[ 1.2669639 , 0.02830414, 2.73350272, …, -0.3983385 ,
-0.28558057, 0.42386497]])}
[[ 1.2669639 0.02830414 2.73350272 …, -0.3983385 -0.28558057
0.42386497]]
0.0283041424542

#.rds
import rpy2.robjects as robjects;
from rpy2.robjects import pandas2ri;
pandas2ri.activate();
readRDS = robjects.r['readRDS'];
df = readRDS('test.rds');
df = pandas2ri.ri2py(df);
#do something with the dataframe
print(df);
print(df[1]);

[[ 0. 0.0544 33.90019329 0.0544 33.90040828 0.0525
33.89634078 0.0618 0.0619 0.0619 0.0532 ]
[ 0.8 0.9495 33.89941492 0.9494 33.89914541 0.9477
32.05498535 0.9565 0.9564 0.9564 0.9469 ]]
[ 0.8 0.9495 33.89941492 0.9494 33.89914541 0.9477
32.05498535 0.9565 0.9564 0.9564 0.9469 ]

Subplots

x = np.linspace(0, 20, 100);
fig, axes = plt.subplots(nrows=2);
for i in range(1,10):
axes[0].plot(x, i * (x - 10)**3)
for i in range(1,10):
axes[1].plot(x, i * np.sin(x))
plt.show();

png

Save Figure

data = np.genfromtxt('testdf.csv', delimiter=',');
fig = plt.figure();
ax1 = fig.add_subplot(111);
ax1.plot(data);
plt.show();
fig.savefig('test.eps', format='eps', dpi=1000);

png

Coding Styles (guideline for writing your custom function to plot on an axes)

https://matplotlib.org/faq/usage_faq.html#coding-styles

Links:

Books:

Advertisements
This entry was posted in data visualization, programming, Python. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s