In [1]:
%pylab inline
Populating the interactive namespace from numpy and matplotlib

Reference: http://matplotlib.org/index.html

2D Plot

In [23]:
with xkcd():
    t = arange(0.0, 2.0, 0.01)
    s = sin(2*pi*t)
    plot(t, s)

    xlabel('time (s)')
    ylabel('voltage (mV)')
    title('About as simple as it gets, folks')
    grid(True)
    savefig("test.png")
    show()
In [9]:
N = 50
x = random.rand(N)
y = random.rand(N)
colors = random.rand(N)
area = pi * (15 * random.rand(N))**2 # 0 to 15 point radiuses

scatter(x, y, s=area, c=colors, alpha=0.5, linewidth=0)
show()
In [10]:
for color in ['red', 'green', 'blue']:
    n = 750
    x, y = rand(2, n)
    scale = 200.0 * rand(n)
    scatter(x, y, c=color, s=scale, label=color,
                alpha=0.3, edgecolors='none')

legend()
grid(True)

show()
In [17]:
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * random.randn(10000)

num_bins = 50
# the histogram of the data
n, bins, patches = hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
# add a 'best fit' line
y = normpdf(bins, mu, sigma)
plot(bins, y, 'r--')
xlabel('Smarts')
ylabel('Probability')
title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')

# Tweak spacing to prevent clipping of ylabel
subplots_adjust(left=0.15)
show()
In [6]:
# By the way, what does y contains?
y
Out[6]:
array([  8.21158442e-08,   1.99123518e-07,   4.67627003e-07,
         1.06355031e-06,   2.34259884e-06,   4.99711379e-06,
         1.03233817e-05,   2.06540947e-05,   4.00195104e-05,
         7.50963465e-05,   1.36473169e-04,   2.40191246e-04,
         4.09400629e-04,   6.75804789e-04,   1.08037731e-03,
         1.67267311e-03,   2.50800343e-03,   3.64188819e-03,
         5.12161018e-03,   6.97537984e-03,   9.20048316e-03,
         1.17526239e-02,   1.45391987e-02,   1.74191731e-02,
         2.02113829e-02,   2.27115071e-02,   2.47159501e-02,
         2.60489424e-02,   2.65879168e-02,   2.62820936e-02,
         2.51603707e-02,   2.33268202e-02,   2.09447644e-02,
         1.82128055e-02,   1.53376791e-02,   1.25090370e-02,
         9.88028645e-03,   7.55782142e-03,   5.59893140e-03,
         4.01693771e-03,   2.79104268e-03,   1.87810250e-03,
         1.22392141e-03,   7.72447914e-04,   4.72135121e-04,
         2.79476207e-04,   1.60215602e-04,   8.89500505e-05,
         4.78265467e-05,   2.49042392e-05,   1.25591129e-05])
In [20]:
# the random data
x = random.randn(1000)
y = random.randn(1000)

nullfmt   = NullFormatter()         # no labels

# definitions for the axes
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left+width+0.02

rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom_h, width, 0.2]
rect_histy = [left_h, bottom, 0.2, height]

# start with a rectangular Figure
figure(1, figsize=(8,8))

axScatter = axes(rect_scatter)
axHistx = axes(rect_histx)
axHisty = axes(rect_histy)

# no labels
axHistx.xaxis.set_major_formatter(nullfmt)
axHisty.yaxis.set_major_formatter(nullfmt)

# the scatter plot:
axScatter.scatter(x, y)

# now determine nice limits by hand:
binwidth = 0.25
xymax = max( [max(fabs(x)), max(fabs(y))] )
lim = ( int(xymax/binwidth) + 1) * binwidth

axScatter.set_xlim( (-lim, lim) )
axScatter.set_ylim( (-lim, lim) )

bins = arange(-lim, lim + binwidth, binwidth)
axHistx.hist(x, bins=bins)
axHisty.hist(y, bins=bins, orientation='horizontal')

axHistx.set_xlim( axScatter.get_xlim() )
axHisty.set_ylim( axScatter.get_ylim() )

show()
In [21]:
with xkcd():
    # the random data
    x = random.randn(1000)
    y = random.randn(1000)

    nullfmt   = NullFormatter()         # no labels

    # definitions for the axes
    left, width = 0.1, 0.65
    bottom, height = 0.1, 0.65
    bottom_h = left_h = left+width+0.02

    rect_scatter = [left, bottom, width, height]
    rect_histx = [left, bottom_h, width, 0.2]
    rect_histy = [left_h, bottom, 0.2, height]

    # start with a rectangular Figure
    figure(1, figsize=(8,8))

    axScatter = axes(rect_scatter)
    axHistx = axes(rect_histx)
    axHisty = axes(rect_histy)

    # no labels
    axHistx.xaxis.set_major_formatter(nullfmt)
    axHisty.yaxis.set_major_formatter(nullfmt)

    # the scatter plot:
    axScatter.scatter(x, y)

    # now determine nice limits by hand:
    binwidth = 0.25
    xymax = max( [max(fabs(x)), max(fabs(y))] )
    lim = ( int(xymax/binwidth) + 1) * binwidth

    axScatter.set_xlim( (-lim, lim) )
    axScatter.set_ylim( (-lim, lim) )

    bins = arange(-lim, lim + binwidth, binwidth)
    axHistx.hist(x, bins=bins)
    axHisty.hist(y, bins=bins, orientation='horizontal')

    axHistx.set_xlim( axScatter.get_xlim() )
    axHisty.set_ylim( axScatter.get_ylim() )

    show()
In [24]:
n_bins = 10
x = random.randn(1000, 3)

fig, axes = subplots(nrows=2, ncols=2)
ax0, ax1, ax2, ax3 = axes.flat

colors = ['red', 'tan', 'lime']
ax0.hist(x, n_bins, normed=1, histtype='bar', color=colors, label=colors)
ax0.legend(prop={'size': 10})
ax0.set_title('bars with legend')

ax1.hist(x, n_bins, normed=1, histtype='bar', stacked=True)
ax1.set_title('stacked bar')

ax2.hist(x, n_bins, histtype='step', stacked=True, fill=True)
ax2.set_title('stepfilled')

# Make a multiple-histogram of data-sets with different length.
x_multi = [random.randn(n) for n in [10000, 5000, 2000]]
ax3.hist(x_multi, n_bins, histtype='bar')
ax3.set_title('different sample sizes')

tight_layout()
show()
In [26]:
with xkcd():
    # The slices will be ordered and plotted counter-clockwise.
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    sizes = [15, 30, 45, 10]
    colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
    explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')

    pie(sizes, explode=explode, labels=labels, colors=colors,
            autopct='%1.1f%%', shadow=True, startangle=90)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    axis('equal')

    show()
In [27]:
def func(x):
    return (x - 3) * (x - 5) * (x - 7) + 85

a, b = 2, 9 # integral limits
x = linspace(0, 10)
y = func(x)

fig, ax = subplots()
plot(x, y, 'r', linewidth=2)
ylim(ymin=0)

# Make the shaded region
ix = linspace(a, b)
iy = func(ix)
verts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)]
poly = Polygon(verts, facecolor='0.9', edgecolor='0.5')
ax.add_patch(poly)

text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment='center', fontsize=20)

figtext(0.9, 0.05, '$x$')
figtext(0.1, 0.9, '$y$')

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')

ax.set_xticks((a, b))
ax.set_xticklabels(('$a$', '$b$'))
ax.set_yticks([])

show()

Plot 3D

In [28]:
from mpl_toolkits.mplot3d import Axes3D

step = 0.04
maxval = 1.0
fig = figure()
ax = fig.add_subplot(111, projection='3d')

# create supporting points in polar coordinates
r = linspace(0,1.25,50)
p = linspace(0,2*np.pi,50)
R,P = meshgrid(r,p)
# transform them to cartesian system
X,Y = R*np.cos(P),R*np.sin(P)

Z = ((R**2 - 1)**2)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.YlGnBu_r)
ax.set_zlim3d(0, 1)
ax.set_xlabel(r'$\phi_\mathrm{real}$')
ax.set_ylabel(r'$\phi_\mathrm{im}$')
ax.set_zlabel(r'$V(\phi)$')
show()

Interaction

In [31]:
from IPython.html.widgets import interactive
def myPlot(amplitude=0.0, color='red'):
    fig, ax = subplots(figsize=(4, 3), subplot_kw={'axisbg':'#EEEEEE', 'axisbelow':True})
    ax.grid(color='w', linewidth=2, linestyle='solid')
    x = linspace(0, 10, 1000)
    ax.plot(x, amplitude * sin(x), color=color, lw=5, alpha=0.4)
    ax.set_xlim(0, 10)
    ax.set_ylim(-1.1, 1.1)
    show()
In [34]:
myPlot(0.3,'g')
In [39]:
from IPython.html import widgets

#interactive(myPlot, amplitude=(0.1, 1), color=('red', 'green', 'blue'))
#interactive(myPlot, amplitude=(0.1, 1), color=({'rosso':'r', 'verde':'g', 'blu':'b'}))
interactive(myPlot, amplitude=(0.1, 1),
            color=widgets.RadioButtonsWidget(values=['r', 'g', 'b'], 
                                             value='r'))
In [40]:
from IPython.html import widgets
mywidget = widgets.FloatSliderWidget()
In [46]:
mywidget
In [47]:
mywidget.max=80
mywidget.value=12
In [49]:
mywidget.value
Out[49]:
36.9
In [51]:
mysecondwidget = widgets.RadioButtonsWidget(values=["Item A", "Item B", "Item C"], value="Item A")
display(mysecondwidget)
In [57]:
button = widgets.ButtonWidget(description="Click Me!")
display(button)

def on_button_clicked(b):
    print("Button clicked.")

button.on_click(on_button_clicked)
Button clicked.

In [59]:
from IPython.html.widgets import interactive
from IPython.display import Audio, display
def beat_freq(f1=220.0, f2=224.0):
    max_time = 10
    rate = 8000
    times = linspace(0,max_time,rate*max_time)
    signal = sin(2*pi*f1*times) + sin(2*pi*f2*times)
    print(f1, f2, abs(f1-f2))
    display(Audio(data=signal, rate=rate))
    return signal
v = interactive(beat_freq, f1=(200.0,300.0), f2=(200.0,300.0))
display(v)
(275.1, 234.1, 41.00000000000003)

In [60]:
v.kwargs
Out[60]:
{u'f1': 275.1, u'f2': 213.3}
In [61]:
f1, f2 = v.children
f1.value = 255
f2.value = 260
plot(v.result[0:6000])
(255.0, 260.0, 5.0)

Out[61]:
[<matplotlib.lines.Line2D at 0x7f6b270c6990>]

Excelent tutorial about widgets

http://nbviewer.ipython.org/github/etpinard/ipython/blob/master/examples/widgets/Part%201%20-%20Basics.ipynb

Animations

In [63]:
# JSAnimation import available at https://github.com/jakevdp/JSAnimation
from JSAnimation import IPython_display
from matplotlib import animation

# create a simple animation
fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

x = np.linspace(0, 10, 1000)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    line.set_data(x, np.cos(i * 0.02 * np.pi) * np.sin(x - i * 0.02 * np.pi))
    return line,

animation.FuncAnimation(fig, animate, init_func=init,
                        frames=100, interval=20, blit=True)
Out[63]:


Once Loop Reflect
In [64]:
# JS Animation import is available at http://github.com/jakevdp/JSAnimation
from JSAnimation.IPython_display import display_animation
from matplotlib import animation

# Set up the axes, making sure the axis ratio is equal
fig = plt.figure(figsize=(6.5, 2.5))
ax = fig.add_axes([0, 0, 1, 1], xlim=(-0.02, 13.02), ylim=(-0.02, 5.02),
                  xticks=range(14), yticks=range(6), aspect='equal', frameon=False)
ax.grid(True)

# Define the shapes of the polygons
P1 = np.array([[0, 0], [5, 0], [5, 2], [0, 0]])
P2 = np.array([[0, 0], [8, 0], [8, 3], [0, 0]])
P3 = np.array([[0, 0], [5, 0], [5, 1], [3, 1], [3, 2], [0, 2], [0, 0]])
P4 = np.array([[0, 1], [3, 1], [3, 0], [5, 0], [5, 2], [0, 2], [0, 1]])

# Draw the empty polygons for the animation
kwds = dict(ec='k', alpha=0.5)
patches = [ax.add_patch(plt.Polygon(0 * P1, fc='g', **kwds)),
           ax.add_patch(plt.Polygon(0 * P2, fc='b', **kwds)),
           ax.add_patch(plt.Polygon(0 * P3, fc='y', **kwds)),
           ax.add_patch(plt.Polygon(0 * P4, fc='r', **kwds))]

# This function moves the polygons as a function of the frame i
Nframes = 30
def animate(nframe):
    f = nframe / (Nframes - 1.0)
    patches[0].set_xy(P1 + (8 - 8 * f, 3 - 3 * f + 0.5 * np.sin(f * np.pi)))
    patches[1].set_xy(P2 + (5 * f, 2 * f - 0.5 * np.sin(f * np.pi)))
    patches[2].set_xy(P3 + (8 - 3 * f, 0))
    patches[3].set_xy(P4 + (8, 1 - f))
    return patches
    
anim = animation.FuncAnimation(fig, animate, frames=Nframes, interval=50)
display_animation(anim, default_mode='once')
Out[64]:


Once Loop Reflect
In []: