Matplotlib

A Python 2D plotting library.

Installation

pip install matplotlib

Configure Matplotlib in-line of IPython (~Jupyter) notebook


In [6]:
try:
    %matplotlib inline
except:
    !pip3 install matplotlib


Collecting matplotlib
  Downloading matplotlib-3.2.1-cp37-cp37m-macosx_10_9_x86_64.whl (12.4 MB)
     |████████████████████████████████| 12.4 MB 9.9 MB/s eta 0:00:01
Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/site-packages (from matplotlib) (2.8.1)
Requirement already satisfied: numpy>=1.11 in /usr/local/lib/python3.7/site-packages (from matplotlib) (1.18.2)
Collecting kiwisolver>=1.0.1
  Downloading kiwisolver-1.1.0-cp37-cp37m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (113 kB)
     |████████████████████████████████| 113 kB 14.2 MB/s eta 0:00:01
Collecting pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1
  Downloading pyparsing-2.4.6-py2.py3-none-any.whl (67 kB)
     |████████████████████████████████| 67 kB 8.4 MB/s  eta 0:00:01
Collecting cycler>=0.10
  Downloading cycler-0.10.0-py2.py3-none-any.whl (6.5 kB)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/site-packages (from python-dateutil>=2.1->matplotlib) (1.14.0)
Requirement already satisfied: setuptools in /usr/local/lib/python3.7/site-packages (from kiwisolver>=1.0.1->matplotlib) (46.0.0)
Installing collected packages: kiwisolver, pyparsing, cycler, matplotlib
Successfully installed cycler-0.10.0 kiwisolver-1.1.0 matplotlib-3.2.1 pyparsing-2.4.6

Importing it


In [7]:
import matplotlib.pyplot as plt

Drawing data structures (matrices):


In [8]:
try:
    import numpy as np
except:
    !pip3 install numpy
chess_board = np.zeros([8, 8], dtype=int)
chess_board[0::2, 1::2] = 1
chess_board[1::2, 0::2] = 1
plt.matshow(chess_board, cmap=plt.cm.gray)


Out[8]:
<matplotlib.image.AxesImage at 0x1148abd10>

Drawing 2D curves


In [9]:
resolution = 100
x = np.arange(0, 3*np.pi, np.pi/resolution)
si = np.sin(x)
co = np.cos(x)
plt.plot(x, si, c = 'r')
plt.plot(x, co, c = 'g')
plt.legend(['$\sin(x)$', '$\cos(x)$'])
plt.xlabel('radians')
plt.title('sine($x$) vs. cosine($x$)')
plt.xticks(x*resolution, ['0', '$\pi$', '$2\pi$'], rotation='horizontal')
plt.xlim(0,3*np.pi)
plt.show()


Drawing 3D curves


In [10]:
x = np.array([[(x+y)/25 for x in range(256)] for y in range(256)])
si = np.sin(x)
plt.imshow(si, cmap='hot', interpolation='nearest')
plt.show()



In [11]:
# https://github.com/AeroPython/Taller-Aeropython-PyConEs16
def funcion(x,y):
    return np.cos(x) + np.sin(y)

x_1d = np.linspace(0, 5, 100)
y_1d = np.linspace(-2, 4, 100)
X, Y = np.meshgrid(x_1d, y_1d)
Z = funcion(X,Y)
plt.contourf(X, Y, Z, np.linspace(-2, 2, 100),cmap=plt.cm.Spectral)
plt.colorbar()
cs = plt.contour(X, Y, Z, np.linspace(-2, 2, 9), colors='k')
plt.clabel(cs)


Out[11]:
<a list of 13 text.Text objects>