%pylab inline
import scipy.special as spec
x = linspace(0, 20, 200)
f, ax = plt.subplots()
for n in range(0,10,3):
plot(x, spec.jn(n, x), label=r'$J_%i(x)$' % n)
grid()
legend()
title('Bessel Functions')
%qtconsole
You can italicize, boldface
and embed code meant for illustration instead of execution in Python:
def f(x):
"""a docstring"""
return x**2
or other languages:
if (i=0; i<n; i++) {
printf("hello %d\n", i);
x += 4;
}
Courtesy of MathJax, you can include mathematical expressions both inline: $e^{i\pi} + 1 = 0$ and displayed:
$$e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i$$from IPython.display import Image
Image(filename='fig/logo.png')
from IPython.display import HTML
HTML("""<table> <tr>
<th>Header 1</th>
<th>Header 2</th></tr>
<tr><td>row 1, cell 1</td>
<td>row 1, cell 2</td></tr>
<tr><td>row 2, cell 1</td>
<td>row 2, cell 2</td></tr></table>""")
import pandas
from IPython.display import display
pandas.core.format.set_printoptions(notebook_repr_html=True)
df = pandas.read_csv('data.csv', parse_dates=True)
display(df.head())
plt.plot(df.index, df['Adj Close']);
from IPython.display import HTML
video = open("fig/animation.m4v", "rb").read()
video_encoded = video.encode("base64")
video_tag = '<video controls alt="test" src="data:video/x-m4v;base64,{0}">'.format(video_encoded)
HTML(data=video_tag)
And more exotic objects can also be displayed, as long as their representation supports the IPython display protocol.
For example, videos hosted externally on YouTube are easy to load (and writing a similar wrapper for other hosted content is trivial):
from IPython.display import YouTubeVideo
YouTubeVideo('F4rFuIb1Ie4')
from IPython.display import HTML
HTML('<iframe src=http://en.mobile.wikipedia.org/?useformat=mobile width=650 height=350>')
Use %load
with any local or remote url, such as the always useful Matplotlib Gallery!
%load http://matplotlib.org/mpl_examples/api/hinton_demo.py
#Initial idea from David Warde-Farley on the SciPy Cookbook
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.ticker import NullLocator
#from matplotlib.collections import RegularPolyCollection
#from matplotlib.colors import BoundaryNorm, ListedColormap
def hinton(W, maxWeight=None, ax=None):
"""
Draws a Hinton diagram for visualizing a weight matrix.
"""
if not ax:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
if not maxWeight:
maxWeight = 2**np.ceil(np.log(np.abs(W).max())/np.log(2))
ax.patch.set_facecolor('gray')
ax.set_aspect('equal', 'box')
ax.xaxis.set_major_locator(NullLocator())
ax.yaxis.set_major_locator(NullLocator())
for (x,y),w in np.ndenumerate(W):
if w > 0: color = 'white'
else: color = 'black'
size = np.sqrt(np.abs(w))
rect = Rectangle([x - size / 2, y - size / 2], size, size,
facecolor=color, edgecolor=color)
ax.add_patch(rect)
ax.autoscale_view()
# Reverse the yaxis limits
ax.set_ylim(*ax.get_ylim()[::-1])
## Potential way using polygon collections that just has an issue with
## easily getting the squares scaled by the data.
# height,width = W.shape
# x = np.arange(width)
# y = np.arange(height)
# X,Y = np.meshgrid(x, y)
# xy = np.array([X.flatten(),Y.flatten()]).T
# scaled_data = W.flatten() / maxWeight
# cmap = ListedColormap(['black', 'white'])
# norm = BoundaryNorm([-1., 0., 1.], cmap.N)
# rect_col = RegularPolyCollection(4, rotation=np.pi/4,
# sizes=np.abs(scaled_data) * 72 / ax.figure.get_dpi(), offsets=xy,
# transOffset=ax.transData, norm=norm, cmap=cmap, edgecolor='none')
# ax.add_collection(rect_col)
# rect_col.set_array(scaled_data)
# ax.autoscale_view()
if __name__ == '__main__':
hinton(np.random.rand(20, 20) - 0.5)
plt.title('Hinton Example')
plt.show()
Objects can have a LaTeX representation, rendered thanks to MathJax:
from IPython.display import Math
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\,
\frac{\partial\vec{\mathbf{E}}}{\partial t} & = & \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = & 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\,
\frac{\partial\vec{\mathbf{B}}}{\partial t} & = & \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = & 0
\end{eqnarray}""")
%load_ext sympyprinting
from __future__ import division
from sympy import *
x, y = symbols("x y")
eq = ((x+y)**2 * (x+1)); eq
expand(eq)
(1/cos(x)).series(x, 0, 6)
diff(cos(x**2)**2 / (1+x), x)
%load_ext rmagic
A simple dataset plotted in Python
import numpy as np
import matplotlib.pyplot as plt
X = np.array([0,1,2,3,4])
Y = np.array([3,5,4,6,7])
plt.scatter(X, Y);
%%R -i X,Y -o XYcoef
XYlm = lm(Y~X)
XYcoef = coef(XYlm)
print(summary(XYlm))
par(mfrow=c(2,2))
plot(XYlm)
And now we have the python variable XYcoef
:
XYcoef
%load_ext cythonmagic
def f(x):
return x**2-x
def integrate_f(a, b, N):
s = 0; dx = (b-a)/N
for i in range(N):
s += f(a+i*dx)
return s * dx
%%cython
cdef double fcy(double x) except? -2:
return x**2-x
def integrate_fcy(double a, double b, int N):
cdef int i
cdef double s, dx
s = 0; dx = (b-a)/N
for i in range(N):
s += fcy(a+i*dx)
return s * dx
%timeit integrate_f(0, 1, 100)
%timeit integrate_fcy(0, 1, 100)