matplotlib and seaborn essentials


In [1]:
import numpy as np
import matplotlib.pyplot as plt
import seaborn
%matplotlib inline

Common plots with matplotlib


In [2]:
y = np.random.randn(1000)

In [3]:
plt.plot(y)

In [4]:
x = np.linspace(-10., 10., 1000)
y = np.sin(3 * x) * np.exp(-.1 * x**2)

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

In [6]:
x = np.linspace(-5., 5., 100)
y = np.sin(3 * x) * np.exp(-.1 * x ** 2)

In [7]:
plt.plot(x, y, '--^',
         lw=3, color='#fdbb84',
         mfc='#2b8cbe', ms=8)

In [8]:
x = np.random.randn(100)
y = x + np.random.randn(100)

In [9]:
plt.scatter(x, y)

Customizing matplotlib figures


In [10]:
# Left panel.
plt.subplot(1, 2, 1)
x = np.linspace(-10., 10., 1000)
plt.plot(x, np.sin(x), '-r', label='sinus')
plt.plot(x, np.cos(x), ':g', lw=1, label='cosinus')
plt.xticks([-10, 0, 10])
plt.yticks([-1, 0, 1])
plt.ylim(-2, 2)
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.title("Two plots")
plt.legend()

# Right panel.
plt.subplot(1, 2, 2, polar=True)
x = np.linspace(0, 2 * np.pi, 1000)
plt.plot(x, 1 + 2 * np.cos(6 * x))
plt.yticks([])
plt.xlim(-.1, 3.1)
plt.ylim(-.1, 3.1)
plt.xticks(np.linspace(0, 5 * np.pi / 3, 6))
plt.title("A polar plot")
plt.grid(color='k', linewidth=1, linestyle=':')

Interacting with matplotlib figures in the Notebook


In [11]:
from ipywidgets import interact

In [12]:
x = np.linspace(-5., 5., 1000)

In [13]:
@interact
def plot_sin(a=(1, 10)):
    plt.plot(x, np.sin(a*x))
    plt.ylim(-1, 1)

In [14]:
%matplotlib qt

In [15]:
lines = plt.plot([0, 1], [0, 1], 'b')

In [16]:
lines


Out[16]:
[<matplotlib.lines.Line2D at 0x7ffa434542e8>]

In [17]:
lines[0].set_color('r')
plt.draw()

High-level plotting with seaborn


In [18]:
df = seaborn.load_dataset("iris")
df.head(3)


Out[18]:
   sepal_length  sepal_width  petal_length  petal_width species
0           5.1          3.5           1.4          0.2  setosa
1           4.9          3.0           1.4          0.2  setosa
2           4.7          3.2           1.3          0.2  setosa

In [19]:
seaborn.pairplot(df, hue="species", size=2.5)