ipython notebook
介绍ipython notebook¶
1.简单介绍ipython notebook的安装和使用,在ubuntu上:
sudo apt-get install ipython
但是并不是所有的版本都支持notebook功能,本人的系统安装的是0.13的版本有
notebook,但是有个重要的功能没有,什么功能等会再说,所以本人手动安装的
ipython 1.1.0版本,你可以“ipython -V”查看版本号。
http://ipython.org/ 此网址可以下载最新的ipython版本¶
2.使用python的你也许对ipython有所耳闻或者使用过,简单的介绍ipython:
ipython是一个强大而交互式运算架构:
(1).强大的交互式shell(终端运行);
(2).一个基于浏览器的notbook,支持代码、文本、数学运算、内嵌plots等;
(3).支持交互式的数据可视化和GUI工具包的使用;
(4).灵活、内嵌的解释器加载到自己的项目;
(5).支持并行运算.¶
3.运行ipython notebook,在终端输入:
ipython notebook
如果你使用matplotlib内嵌进网页中,那么需要运行:
ipython notebook --matplotlib inline
OK,程序会自动在浏览器上新建一个标签窗口。
所以ipython notebook就是一个后端服务和一个前端表现,服务默认端口8888,
前端也就是你在浏览器中看到的,如下图:¶
In [5]:
from IPython.display import Image
Image(filename='/home/chaofan/Desktop/firstpage.png') #press shift+enter
Out[5]:
上图即是控制窗口,我们可以按"New Notebook"新建一个,本人已经见了5个。
你现在所读的页面即是上图 Advence打开后本人编辑 成现在的效果。¶
基本的操作¶
1.每次运行按shift-enter¶
In [7]:
i=0
print i #按shift+enter
可以看到输出了0,我们可以直接对上面的程序做修改,再运行。¶
2.ipython提供个很多魔数,以%或者%%开始¶
In [1]:
%matplotlib inline
%matplotlib就是一个魔数,如果你在命令行加入--matplotlib inline
运行此命令一样可以达到内嵌的效果。¶
下面是获得连接信息¶
In [30]:
%connect_info
3.可以直接运行bash¶
In [13]:
ls -l
In [14]:
pwd
Out[14]:
In [16]:
%%bash
echo 'Hello'
date
如果一个程序无线循环或者循环的时间太长想中断可以
按ctr-m i,如下:¶
In [27]:
import time
i=0
while True:
time.sleep(1)
print i
i+=1
4.载入图片¶
上面已经使用过了载入图片,下面载入notebook快捷键的图片,
按ctr-m h也会弹出帮助窗口。¶
In [19]:
Image(filename='/home/chaofan/Desktop/help.png')
Out[19]:
载入url图片:¶
In [22]:
Image(url='http://ww1.sinaimg.cn/mw600/6a77a719jw1dyx581xf1cj.jpg')
Out[22]:
高级处理¶
1.matplotlib使用¶
In [8]:
import numpy as np
In [9]:
import matplotlib.pyplot as plt
In [10]:
x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp');
plt.show()
url载入代码:¶
In [28]:
%load http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/integral_demo.py
In [29]:
#!/usr/bin/env python
# implement the example graphs/integral from pyx
from pylab import *
from matplotlib.patches import Polygon
def func(x):
return (x-3)*(x-5)*(x-7)+85
ax = subplot(111)
a, b = 2, 9 # integral area
x = arange(0, 10, 0.01)
y = func(x)
plot(x, y, linewidth=1)
# make the shaded region
ix = arange(a, b, 0.01)
iy = func(ix)
verts = [(a,0)] + list(zip(ix,iy)) + [(b,0)]
poly = Polygon(verts, facecolor='0.8', edgecolor='k')
ax.add_patch(poly)
text(0.5 * (a + b), 30,
r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment='center',
fontsize=20)
axis([0,10, 0, 180])
figtext(0.9, 0.05, 'x')
figtext(0.1, 0.9, 'y')
ax.set_xticks((a,b))
ax.set_xticklabels(('a','b'))
ax.set_yticks([])
show()
3.在来些matplotlib的例子¶
In [1]:
from pylab import *
In [2]:
x = linspace(0, 5, 10)
y = x ** 2
In [3]:
figure()
plot(x, y, 'r')
xlabel('x')
ylabel('y')
title('title')
show()
In [4]:
subplot(1,2,1)
plot(x, y, 'r--')
subplot(1,2,2)
plot(y, x, 'g*-');
In [5]:
fig = plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes
# main figure
axes1.plot(x, y, 'r')
axes1.set_xlabel('x')
axes1.set_ylabel('y')
axes1.set_title('title')
# insert
axes2.plot(y, x, 'g')
axes2.set_xlabel('y')
axes2.set_ylabel('x')
axes2.set_title('insert title');
In [6]:
fig, ax = plt.subplots()
ax.plot(x, x**2, label=r"$y = \alpha^2$")
ax.plot(x, x**3, label=r"$y = \alpha^3$")
ax.set_xlabel(r'$\alpha$', fontsize=18)
ax.set_ylabel(r'$y$', fontsize=18)
ax.set_title('title')
ax.legend(loc=2); # upper left corner
Out[6]:
In [7]:
fig, ax = plt.subplots(figsize=(12,6))
ax.plot(x, x+1, color="blue", linewidth=0.25)
ax.plot(x, x+2, color="blue", linewidth=0.50)
ax.plot(x, x+3, color="blue", linewidth=1.00)
ax.plot(x, x+4, color="blue", linewidth=2.00)
# possible linestype options ‘-‘, ‘–’, ‘-.’, ‘:’, ‘steps’
ax.plot(x, x+5, color="red", lw=2, linestyle='-')
ax.plot(x, x+6, color="red", lw=2, ls='-.')
ax.plot(x, x+7, color="red", lw=2, ls=':')
# custom dash
line, = ax.plot(x, x+8, color="black", lw=1.50)
line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...
# possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4', ...
ax.plot(x, x+ 9, color="green", lw=2, ls='*', marker='+')
ax.plot(x, x+10, color="green", lw=2, ls='*', marker='o')
ax.plot(x, x+11, color="green", lw=2, ls='*', marker='s')
ax.plot(x, x+12, color="green", lw=2, ls='*', marker='1')
# marker size and color
ax.plot(x, x+13, color="purple", lw=1, ls='-', marker='o', markersize=2)
ax.plot(x, x+14, color="purple", lw=1, ls='-', marker='o', markersize=4)
ax.plot(x, x+15, color="purple", lw=1, ls='-', marker='o', markersize=8, markerfacecolor="red")
ax.plot(x, x+16, color="purple", lw=1, ls='-', marker='s', markersize=8,
markerfacecolor="yellow", markeredgewidth=2, markeredgecolor="blue");
In [8]:
fig, ax1 = plt.subplots()
ax1.plot(x, x**2, lw=2, color="blue")
ax1.set_ylabel(r"area $(m^2)$", fontsize=18, color="blue")
for label in ax1.get_yticklabels():
label.set_color("blue")
ax2 = ax1.twinx()
ax2.plot(x, x**3, lw=2, color="red")
ax2.set_ylabel(r"volume $(m^3)$", fontsize=18, color="red")
for label in ax2.get_yticklabels():
label.set_color("red")
In [11]:
n = array([0,1,2,3,4,5])
xx = np.linspace(-0.75, 1., 100)
In [12]:
fig, axes = plt.subplots(1, 4, figsize=(12,3))
axes[0].scatter(xx, xx + 0.25*randn(len(xx)))
axes[1].step(n, n**2, lw=2)
axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)
axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5);
In [13]:
fig = plt.figure()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = linspace(0, 2 * pi, 100)
ax.plot(t, t, color='blue', lw=3);
In [31]:
import matplotlib.gridspec as gridspec
In [32]:
fig = plt.figure()
gs = gridspec.GridSpec(2, 3, height_ratios=[2,1], width_ratios=[1,2,1])
for g in gs:
ax = fig.add_subplot(g)
fig.tight_layout()
In [33]:
alpha = 0.7
phi_ext = 2 * pi * 0.5
def flux_qubit_potential(phi_m, phi_p):
return 2 + alpha - 2 * cos(phi_p)*cos(phi_m) \
- alpha * cos(phi_ext - 2*phi_p)
In [34]:
phi_m = linspace(0, 2*pi, 100)
phi_p = linspace(0, 2*pi, 100)
X,Y = meshgrid(phi_p, phi_m)
Z = flux_qubit_potential(X, Y).T
In [35]:
fig, ax = plt.subplots()
p = ax.pcolor(X/(2*pi), Y/(2*pi), Z, cmap=cm.RdBu,\
vmin=abs(Z).min(), vmax=abs(Z).max())
cb = fig.colorbar(p, ax=ax)
In [36]:
fig, ax = plt.subplots()
im = imshow(Z, cmap=cm.RdBu, vmin=abs(Z).min(),\
vmax=abs(Z).max(), extent=[0, 1, 0, 1])
im.set_interpolation('bilinear')
cb = fig.colorbar(im, ax=ax)
In [37]:
fig, ax = plt.subplots()
cnt = contour(Z, cmap=cm.RdBu, vmin=abs(Z).min(),\
vmax=abs(Z).max(), extent=[0, 1, 0, 1])
4.matplotlib 3D效果¶
In [38]:
from mpl_toolkits.mplot3d.axes3d import Axes3D
In [39]:
fig = plt.figure(figsize=(14,6))
# `ax` is a 3D-aware axis instance, because of the projection='3d' keyword argument to add_subplot
ax = fig.add_subplot(1, 2, 1, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0)
# surface_plot with color grading and color bar
ax = fig.add_subplot(1, 2, 2, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, \
cmap=cm.coolwarm, linewidth=0, antialiased=False)
cb = fig.colorbar(p, shrink=0.5)
In [23]:
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1, 1, 1, projection='3d')
p = ax.plot_wireframe(X, Y, Z, rstride=4, cstride=4)
In [24]:
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1,1,1, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
cset = ax.contour(X, Y, Z, zdir='z', offset=-pi, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-pi, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=3*pi, cmap=cm.coolwarm)
ax.set_xlim3d(-pi, 2*pi);
ax.set_ylim3d(0, 3*pi);
ax.set_zlim3d(-pi, 2*pi);
就演示这么多吧,本文所有内容全是在notebook上编辑的,可以看出对于教育、科研、
开发具有很强的运算处理,同时很好的记录,
也可以很好的演示给他人。写代码时也在写博客。ipython已经非常流行了,再此介绍给
热爱python的伙伴们.今年8月微软捐赠10万美元给ipython为支持其开发,足见其能量。¶
最后说一下为何ipython版本要高,因为在1.0+版本后有一个nbconvert功能,由于我们看到的
这个网页本身并不是html的,默认是ipynb格式的文件,存储的也都是json格式的内容,我们需要
把它转成html页面。
ipython nbconvert --to html Advance.ipynb¶
注:在博客园上显示科学计算效果很不好(也许是本人不知怎么弄),所以给个完整链接:
http://wuchaofan.github.io/blogsource/python/Advance.html此链接是完整的,博客园上的
把这部分删了。