In [1]:
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.style.use('classic')
%matplotlib inline

In [4]:
import numpy as np
fig = plt.figure()
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--')


Out[4]:
[<matplotlib.lines.Line2D at 0x10eab7050>]

In [5]:
fig.canvas.get_supported_filetypes()


Out[5]:
{u'eps': u'Encapsulated Postscript',
 u'jpeg': u'Joint Photographic Experts Group',
 u'jpg': u'Joint Photographic Experts Group',
 u'pdf': u'Portable Document Format',
 u'pgf': u'PGF code for LaTeX',
 u'png': u'Portable Network Graphics',
 u'ps': u'Postscript',
 u'raw': u'Raw RGBA bitmap',
 u'rgba': u'Raw RGBA bitmap',
 u'svg': u'Scalable Vector Graphics',
 u'svgz': u'Scalable Vector Graphics',
 u'tif': u'Tagged Image File Format',
 u'tiff': u'Tagged Image File Format'}

In [6]:
plt.figure()
plt.subplot(211)
plt.plot(x, np.sin(x))
plt.subplot(212)
plt.plot(x, np.cos(x))
# plt.gcf() (get current figure)
# plt.gca() (get current axes)


Out[6]:
[<matplotlib.lines.Line2D at 0x10f348550>]

In [7]:
fig, ax = plt.subplots(2)
ax[0].plot(x, np.sin(x))
ax[1].plot(x, np.cos(x));



In [8]:
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np

In [9]:
fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 1000)
plt.plot(x, np.sin(x))


Out[9]:
[<matplotlib.lines.Line2D at 0x10f89dd90>]

In [14]:
plt.plot(x, np.sin(x - 0), color='blue')
plt.plot(x, np.sin(x - 1), color='g')
plt.plot(x, np.sin(x - 2), color='0.75')
plt.plot(x, np.sin(x - 3), color='#FFDD44')
plt.plot(x, np.sin(x - 4), color=(1.0,0.2,0.3)) 
plt.plot(x, np.sin(x - 5), color='chartreuse')


Out[14]:
[<matplotlib.lines.Line2D at 0x10fb1d110>]

In [15]:
plt.plot(x, x + 4, linestyle='-') # solid 
plt.plot(x, x + 5, linestyle='--') # dashed 
plt.plot(x, x + 6, linestyle='-.') # dashdot 
plt.plot(x, x + 7, linestyle=':'); # dotted



In [16]:
plt.plot(x, x + 0, '-g') # solid green 
plt.plot(x, x + 1, '--c') # dashed cyan 
plt.plot(x, x + 2, '-.k') # dashdot black 
plt.plot(x, x + 3, ':r'); # dotted red



In [17]:
plt.plot(x, np.sin(x))
plt.xlim(-1, 11)
plt.ylim(-1.5, 1.5);



In [18]:
plt.plot(x, np.sin(x))
plt.xlim(10, 0)
plt.ylim(1.2, -1.2);



In [19]:
plt.plot(x, np.sin(x))
plt.axis([-1, 11, -1.5, 1.5]);  # [xmin, xmax, ymin, ymax]



In [20]:
plt.plot(x, np.sin(x))
plt.axis('tight');



In [21]:
plt.plot(x, np.sin(x))
plt.axis('equal');  # one unit in x is equal to one unit in y



In [22]:
plt.plot(x, np.sin(x))
plt.title("A Sine Curve")
plt.xlabel("x")
plt.ylabel("sin(x)");



In [23]:
plt.plot(x, np.sin(x), '-g', label='sin(x)')
plt.plot(x, np.cos(x), ':b', label='cos(x)')
plt.axis('equal')
plt.legend();



In [24]:
# • plt.xlabel() → ax.set_xlabel()
# • plt.ylabel() → ax.set_ylabel()
# • plt.xlim() → ax.set_xlim()
# • plt.ylim() → ax.set_ylim()
# • plt.title() → ax.set_title()
ax = plt.axes()
ax.plot(x, np.sin(x))
ax.set(xlim=(0, 10), ylim=(-2, 2), xlabel='x', ylabel='sin(x)', title='A Simple Plot');



In [25]:
x = np.linspace(0, 10, 30)
y = np.sin(x)
plt.plot(x, y, 'o', color='black');



In [27]:
rng = np.random.RandomState(0)
for marker in ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']:
    plt.plot(rng.rand(5), rng.rand(5), marker, label="marker='{0}'".format(marker))
plt.legend(numpoints=1)
plt.xlim(0, 1.8);



In [28]:
plt.plot(x, y, '-ok');  # line (-), circle marker (o), black (k)



In [29]:
plt.plot(x, y, '-p', color='gray',markersize=15, linewidth=4,
         markerfacecolor='white', markeredgecolor='gray',
         markeredgewidth=2)
plt.ylim(-1.2, 1.2);



In [30]:
# The primary difference of plt.scatter from plt.plot is that 
# it can be used to create scatter plots where the properties
# of each individual point (size, face color, edge color, etc.)
# can be individually controlled or mapped to data.
plt.scatter(x, y, marker='o');



In [31]:
rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3, cmap='viridis')
plt.colorbar(); # show color scale



In [33]:
from sklearn.datasets import load_iris
iris = load_iris()
features = iris.data.T
plt.scatter(features[0], features[1], alpha=0.2,
            s=100*features[3], c=iris.target, cmap='viridis')
plt.xlabel(iris.feature_names[0])
plt.ylabel(iris.feature_names[1]);

# as datasets get larger than a few thousand points, 
# plt.plot can be noticeably more efficient than plt.scatter.



In [34]:
x = np.linspace(0, 10, 50)
dy=0.8
y = np.sin(x) + dy * np.random.randn(50)
plt.plot(x, np.sin(x))
plt.errorbar(x, y, yerr=dy, fmt='.k');



In [37]:
plt.plot(x, np.sin(x))
plt.errorbar(x, y, yerr=dy, fmt='o', color='black',
             ecolor='lightgray', elinewidth=3, capsize=0);



In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()

In [17]:
import numpy as np
from sklearn.gaussian_process import GaussianProcessRegressor

x = np.array([1, 3, 5, 6, 8])
y = x * np.sin(x)
gp = GaussianProcessRegressor(normalize_y=True, random_state=0)
gp.fit(x[:, np.newaxis], y)
xt = np.linspace(0, 10, 1000)
yt, std = gp.predict(xt[:, np.newaxis], return_std=True)
dy = 2*std  # 2*sigma ~ 95% confidence region

plt.plot(xt, xt*np.sin(xt), 'r--')
plt.plot(x, y, 'or')
plt.plot(xt, yt, '-', color='gray')
plt.fill_between(xt, yt-dy, yt+dy, color='gray', alpha=0.2)


Out[17]:
<matplotlib.collections.PolyCollection at 0x11b33f5d0>

In [18]:
def f(x, y):
    return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)

x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)
X, Y = np.meshgrid(x, y)
Z=f(X,Y)

plt.contour(X, Y, Z, color='black')


Out[18]:
<matplotlib.contour.QuadContourSet at 0x11b519210>

In [19]:
plt.contour(X, Y, Z, 20, cmap='RdGy')  # short for Red-Gray, plt.cm.<TAB>


Out[19]:
<matplotlib.contour.QuadContourSet at 0x11b75c950>

In [20]:
plt.contourf(X, Y, Z, 20, cmap='RdGy')
plt.colorbar()


Out[20]:
<matplotlib.colorbar.Colorbar at 0x11be73090>

In [21]:
plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower', cmap='RdGy')
plt.colorbar()
plt.axis(aspect='image');



In [22]:
contours = plt.contour(X, Y, Z, 3, colors='black')
plt.clabel(contours, inline=True, fontsize=8)
plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower', cmap='RdGy', alpha=0.5)
plt.grid()
plt.colorbar();



In [23]:
data = np.random.randn(1000)
plt.hist(data)


Out[23]:
(array([   3.,   24.,   58.,  127.,  239.,  231.,  177.,  100.,   31.,   10.]),
 array([-3.10475012, -2.51273013, -1.92071015, -1.32869016, -0.73667017,
        -0.14465019,  0.4473698 ,  1.03938979,  1.63140977,  2.22342976,
         2.81544975]),
 <a list of 10 Patch objects>)

In [24]:
plt.hist(data, bins=30, normed=True, alpha=0.5,
         histtype='stepfilled', color='steelblue',
         edgecolor='none');



In [26]:
x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random.normal(-2, 1, 1000)
x3 = np.random.normal(3, 2, 1000)
kwargs = dict(histtype='stepfilled', alpha=0.3, normed=True, bins=40)
plt.hist(x1, **kwargs)
plt.hist(x2, **kwargs)
plt.hist(x3, **kwargs);



In [28]:
counts, bin_edges = np.histogram(data, bins=5)
print(counts)
print
print(bin_edges)


[ 27 185 470 277  41]

[-3.10475012 -1.92071015 -0.73667017  0.4473698   1.63140977  2.81544975]

In [30]:
mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 10000).T
plt.hist2d(x, y, bins=30, cmap='Blues')
cb = plt.colorbar()
cb.set_label('counts')



In [31]:
counts, xedges, yedges = np.histogram2d(x, y, bins=30)

In [32]:
plt.hexbin(x, y, gridsize=30, cmap='Blues')
cb = plt.colorbar(label='count in bin')



In [33]:
from scipy.stats import gaussian_kde
# fit an array of size [Ndim, Nsamples]
data = np.vstack([x, y])
kde = gaussian_kde(data)
# evaluate on a regular grid
xgrid = np.linspace(-3.5, 3.5, 40)
ygrid = np.linspace(-6, 6, 40)
Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)
Z = kde.evaluate(np.vstack([Xgrid.ravel(), Ygrid.ravel()]))
# Plot the result as an image
plt.imshow(Z.reshape(Xgrid.shape), origin='lower', aspect='auto',
           extent=[-3.5, 3.5, -6, 6], cmap='Blues')
cb = plt.colorbar()
cb.set_label("density")



In [34]:
x = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), '-b', label='Sine')
ax.plot(x, np.cos(x), '--r', label='Cosine')
ax.axis('equal')
leg = ax.legend();



In [35]:
ax.legend(loc='upper left', frameon=False)
fig


Out[35]:

In [36]:
ax.legend(frameon=False, loc='lower center', ncol=2)
fig


Out[36]:

In [37]:
ax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)
fig


Out[37]:

In [38]:
y = np.sin(x[:, np.newaxis] + np.pi * np.arange(0, 2, 0.5))
lines = plt.plot(x, y)
plt.legend(lines[:2], ['first', 'second']);



In [41]:
lines, x.shape, y.shape


Out[41]:
([<matplotlib.lines.Line2D at 0x11cc24750>,
  <matplotlib.lines.Line2D at 0x11cc248d0>,
  <matplotlib.lines.Line2D at 0x11cc24210>,
  <matplotlib.lines.Line2D at 0x11cf30190>],
 (1000,),
 (1000, 4))

In [42]:
plt.plot(x, y[:, 0], label='first')
plt.plot(x, y[:, 1], label='second')
plt.plot(x, y[:, 2:])
plt.legend(framealpha=1, frameon=True);



In [43]:
fig, ax = plt.subplots()
lines = []
styles = ['-', '--', '-.', ':']
x = np.linspace(0, 10, 1000)
for i in range(4):
    lines += ax.plot(x, np.sin(x - i * np.pi / 2),
                     styles[i], color='black')
ax.axis('equal')
# specify the lines and labels of the first legend
ax.legend(lines[:2], ['line A', 'line B'], loc='upper right', frameon=False)
# Create the second legend and add the artist manually.
from matplotlib.legend import Legend
leg = Legend(ax, lines[2:], ['line C', 'line D'],
             loc='lower right', frameon=False)
ax.add_artist(leg);



In [44]:
x = np.linspace(0, 10, 1000)
I = np.sin(x) * np.cos(x[:, np.newaxis])
plt.imshow(I)
plt.colorbar();



In [45]:
plt.imshow(I, cmap='gray');



In [46]:
from matplotlib.colors import LinearSegmentedColormap
def grayscale_cmap(cmap):
    """Return a grayscale version of the given colormap"""
    cmap = plt.cm.get_cmap(cmap)
    colors = cmap(np.arange(cmap.N))
    # convert RGBA to perceived grayscale luminance
    # cf. http://alienryderflex.com/hsp.html
    RGB_weight = [0.299, 0.587, 0.114]
    luminance = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight))
    colors[:, :3] = luminance[:, np.newaxis]
    return LinearSegmentedColormap.from_list(cmap.name + "_gray", colors, cmap.N)

def view_colormap(cmap):
    """Plot a colormap with its grayscale equivalent"""
    cmap = plt.cm.get_cmap(cmap)
    colors = cmap(np.arange(cmap.N))
    cmap = grayscale_cmap(cmap)
    grayscale = cmap(np.arange(cmap.N))
    fig, ax = plt.subplots(2, figsize=(6, 2), subplot_kw=dict(xticks=[], yticks=[]))
    ax[0].imshow([colors], extent=[0, 10, 0, 1])
    ax[1].imshow([grayscale], extent=[0, 10, 0, 1])

In [47]:
view_colormap('jet')



In [48]:
view_colormap('viridis')



In [49]:
view_colormap('cubehelix')



In [50]:
view_colormap('RdBu')



In [51]:
speckles = (np.random.random(I.shape) < 0.01)
I[speckles] = np.random.normal(0, 3, np.count_nonzero(speckles))
plt.figure(figsize=(10, 3.5))
plt.subplot(1, 2, 1)
plt.imshow(I, cmap='RdBu')
plt.colorbar()
plt.subplot(1, 2, 2)
plt.imshow(I, cmap='RdBu')
plt.colorbar(extend='both')
plt.clim(-1, 1);


Notice that in the left panel, the default color limits respond to the noisy pixels,

and the range of the noise completely washes out the pattern we are interested in.

In the right panel, we manually set the color limits, and add extensions to indicate

values that are above or below those limits. The result is a much more useful visualization of our data.


In [52]:
plt.imshow(I, cmap=plt.cm.get_cmap('Blues', 6))
plt.colorbar()
plt.clim(-1, 1);



In [54]:
# load images of the digits 0 through 5 and visualize several of them
from sklearn.datasets import load_digits
digits = load_digits(n_class=6)
fig, ax = plt.subplots(8, 8, figsize=(6, 6))
for i, axi in enumerate(ax.flat):
    axi.imshow(digits.images[i], cmap='binary')
    axi.set(xticks=[], yticks=[])



In [55]:
from sklearn.manifold import Isomap
iso = Isomap(n_components=2)
projection = iso.fit_transform(digits.data)
# plot the results
plt.scatter(projection[:, 0], projection[:, 1], lw=0.1,
            c=digits.target, cmap=plt.cm.get_cmap('cubehelix', 6))
plt.colorbar(ticks=range(6), label='digit value')
plt.clim(-0.5, 5.5)



In [ ]:
281