Matplotlib
Matplotlib Tutorial. No comments. Just code.
Install / Use
/learn @zziz/MatplotlibREADME
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

plt.plot([1,2,3,4], [1,4,9,16])
plt.show()

plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0,6,0,20])
plt.show()

t = np.arange(0., 5., 0.2)
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

x = np.linspace(-np.pi, np.pi)
y = np.sin(x)
plt.plot(x, y, linewidth=2.0, color='r')
plt.show()

lines = plt.plot(x, y)
plt.setp(lines, color='r', linewidth=2.0)
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
plt.show()

def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05))
plt.ylim(-2,2)
plt.show()

x = np.linspace(0, 2 * np.pi)
y = np.sin(x)
plt.plot(x, y)
plt.show()

plt.style.use('ggplot')
plt.plot(x, y, 'r-o')
plt.show()

fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
r = np.arange(0,1,0.001)
theta = 2*2*np.pi*r
line, = ax.plot(theta, r, color='#ee8d18', lw=3)
ind = 800
thisr, thistheta = r[ind], theta[ind]
ax.plot([thistheta], [thisr], 'o')
ax.annotate('a polar annotation', xy=(thistheta, thisr), xytext=(0.05, 0.05), textcoords='figure fraction',
arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='left', verticalalignment='bottom')
plt.show()

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
plt.plot(t,s)
plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
plt.text(0.6, 0.6, r'$\mathcal{A}\ \mathrm{sin}(2 \omega t)$', fontsize=20)
plt.xlabel('time (s)')
plt.ylabel('volts (mV)')
plt.show()

plt.style.use('seaborn-white')
import matplotlib.image as mpimg
img = mpimg.imread('lenna.png')
print("img.shape: {}".format(img.shape))
print("img.dtype: {}".format(img.dtype))
img.shape: (512, 512, 3)
img.dtype: float32
imgplot = plt.imshow(img)

lum_img = img[:,:,0]
imgplot = plt.imshow(lum_img)

imgplot = plt.imshow(lum_img)
imgplot.set_cmap('hot')

imgplot = plt.imshow(lum_img)
imgplot.set_cmap('spectral')

imgplot = plt.imshow(lum_img)
imgplot.set_cmap('spectral')
plt.colorbar()
plt.show()

plt.hist(lum_img.flatten(), 256, range=(0.0,1.0), fc='k', ec='k')
plt.show()

imgplot = plt.imshow(lum_img)
imgplot.set_clim(0.0,0.7)

fig = plt.figure(1, figsize=(5,5))
fig.clf()
ax = fig.add_subplot(111)
ax.set_aspect(1)
x1 = -1 + np.random.randn(100)
y1 = -1 + np.random.randn(100)
x2 = 1. + np.random.randn(100)
y2 = 1. + np.random.randn(100)
ax.scatter(x1, y1, color="r")
ax.scatter(x2, y2, color="g")
bbox_props = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.9)
ax.text(-2, -2, "Sample A", ha="center", va="center", size=20, bbox=bbox_props)
ax.text(2, 2, "Sample B", ha="center", va="center", size=20, bbox=bbox_props)
bbox_props = dict(boxstyle="rarrow", fc=(0.8,0.9,0.9), ec="b", lw=2)
t = ax.text(0, 0, "Direction", ha="center", va="center", rotation=45, size=15, bbox=bbox_props)
bb = t.get_bbox_patch()
bb.set_boxstyle("rarrow", pad=0.6)
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
plt.show()

import matplotlib.patches as mpatch
x1, y1 = 0.3, 0.3
x2, y2 = 0.7, 0.7
fig = plt.figure(1, figsize=(8,3))
fig.clf()
from mpl_toolkits.axes_grid.axes_grid import AxesGrid
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText
def add_at(ax, t, loc=2):
fp = dict(size=10)
_at = AnchoredText(t, loc=loc, prop=fp)
ax.add_artist(_at)
return _at
grid = AxesGrid(fig, 111, (1, 4), label_mode="1", share_all=True)
grid[0].set_autoscale_on(False)
ax = grid[0]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatch.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("", xy=(x1, y1), xycoords='data', xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="-", color="0.5", patchB=None, shrinkB=0,connectionstyle="arc3,rad=0.3"))
add_at(ax, "connect", loc=2)
ax = grid[1]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatch.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("", xy=(x1, y1), xycoords='data', xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="-", color="0.5", patchB=el, shrinkB=0, connectionstyle="arc3,rad=0.3"))
add_at(ax, "clip", loc=2)
ax = grid[2]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatch.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("", xy=(x1, y1), xycoords='data', xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="-", color="0.5", patchB=el, shrinkB=5, connectionstyle="arc3,rad=0.3"))
add_at(ax, "shrink", loc=2)
ax = grid[3]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatch.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("", xy=(x1, y1), xycoords='data', xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="fancy", color="0.5", patchB=el, shrinkB=5, connectionstyle="arc3,rad=0.3"))
add_at(ax, "mutate", loc=2)
grid[0].set_xlim(0, 1)
grid[0].set_ylim(0, 1)
grid[0].axis["bottom"].toggle(ticklabels=False)
grid[0].axis["left"].toggle(ticklabels=False)
fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95)
plt.draw()
plt.show()

line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend(handles=[line_up, line_down])
plt.show()

plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.)
plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()

line1, = plt.plot([1,2,3], label="Line 1", linestyle='--')
line2, = plt.plot([3,2,1], label="Line 2", linewidth=4)
first_legend = plt.legend(handles=[line1], loc=1)
ax = plt.gca().add_artist(first_legend)
plt.legend(handles=[line2], loc=4)
plt.show()

z = np.random.randn(10)
red_dot, = plt.plot(z, "ro", markersize=15)
white_cross, = plt.plot(z[:5], "w+", markeredgewidth=3, markersize=15)
plt.legend([red_dot, (red_dot, white_cross)], ["Attr A", "Attr A+B"])
plt.show()

from matplotlib.legend_handler import HandlerPatch
class HandlerEllipse(HandlerPatch):
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans):
center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
p = mpatch.Ellipse(xy=center, width=width + xdescent, height=height + ydescent)
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]
c = mpatch.Circle((0.5, 0.5), 0.25, facecolor="green", edgecolor="red", linewidth=3)
plt.gca().add_patch(c)
plt.legend([c], ["An ellipse, not a rectangle"], handler_map={mpatch.Circle: HandlerEllipse()})
plt.show()

plt.subplot(2,1,1)
plt.xticks([]), plt.yticks([])
plt.text(0.5,0.5, 'subplot(2,1,1)',ha='center',va='center',size=24,alpha=.5)
plt.subplot(2,1,2)
plt.xticks([]), plt.yticks([])
plt.text(0.5,0.5, 'subplot(2,1,2)',ha='center',va='center',size=24,alpha=.5)
plt.show()

x = np.linspace(-np.pi, np.pi)
c, s = np.cos(x), np.sin(x)
p = plt.plot(x,c)
p = plt.plot(x,s)
plt.show()

plt.figure(figsize=(10,6), dpi=80)
plt.plot(x, c, 'b-', x, s, 'r-', linewidth=2.5)
plt.xlim(x.min() * 1.1, x.max() * 1.1)
plt.ylim(c.min() * 1.1, c.max() * 1.1)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], ['$-\pi$', '$-\pi/2$', '$0$', '$\pi/2$', '$\pi$'], fontsize ='xx-large')
plt.yticks([-1, 0, 1], ['$-1$', '$0$', '$+1$'], fontsize ='xx-large')
l = plt.legend(['cosine', 'sine'], loc='upper left', frameon=False)
t = 2 * np.pi / 3
plt.plot([t,t],[0,np.cos(t)], color ='blue', linewidth=2.5, linestyle="--")
plt.scatter([t,],[np.cos(t),], 50, color ='blue')
plt.annotate(r'$
