%pylab inline
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()
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()
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()
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()
# By the way, what does y contains?
y
# 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()
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()
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()
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()
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()
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()
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()
myPlot(0.3,'g')
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'))
from IPython.html import widgets
mywidget = widgets.FloatSliderWidget()
mywidget
mywidget.max=80
mywidget.value=12
mywidget.value
mysecondwidget = widgets.RadioButtonsWidget(values=["Item A", "Item B", "Item C"], value="Item A")
display(mysecondwidget)
button = widgets.ButtonWidget(description="Click Me!")
display(button)
def on_button_clicked(b):
print("Button clicked.")
button.on_click(on_button_clicked)
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)
v.kwargs
f1, f2 = v.children
f1.value = 255
f2.value = 260
plot(v.result[0:6000])
http://nbviewer.ipython.org/github/etpinard/ipython/blob/master/examples/widgets/Part%201%20-%20Basics.ipynb
# 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)
# 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')