很多人可能用过Jupyter Notebok,作为了在线编辑和执行平台,它可以让我们通过浏览器就能进行代码编辑和执行,做为趁手的一个Web IDE特别Pyton码农(也支持其他语言比如R、JS、golang等)用它来开发,数据工程师用它做数据处理,网上也有大量的教程介绍它的用法,大家可以参考。今天虫虫就通过Jupyter Notebook进行可视化的用法,主要包括基于 markdown 模式下LaTex格式的数学公式的输入和显示,以及基于Graphivs的图形生成方法。
Jupyter Notebook和模块安装
Jupyter Notebook的运行依赖 Python 环境,可以支持window和Linux下,我们建议使用最新的Python 3.6版本,在安装Python 3.6和pip包管理器之后就可以通过pip安装:
pip install jupyter
本文用到的其他模块也通过这种安装方法,比如Graphivs和 matplotlib :
pip install graphivs
pip install matplotlib
如果在window下使用建议使用一键安装包Anaconda安装,Anaconda是一个开源的Python发行版本,内置了大量的Python和大多数的常用模块其中就包括了Jupyter Notebook。

Jupyter Notebook启动和基本使用
Jupyter Notebook启动很简单,在window命令行窗口执行:
jupyter notebook启动,并自动打开一个浏览器窗口,默认端口是8888:

浏览器结果如下:

在上述页面通过右边的new菜单打开一个执行环境,比如我的可执行环境包括Python 3和R语言(其他语言也可以通过插件扩展):

Jupyter Notebook cell操作模式
打开一个工作环境如下:

环境中主要操作环境都是基于cell块,比如上面绿色框就是一个cell编辑块,cell操作模式分三种、编辑模式(绿色)、命令模式(蓝色)和markdown模式。
编辑模式
编辑模式上面的图已经显示了,打开环境页面默认就是编辑模式。
命令模式
命令模式和vim的编辑模式类似,在编辑模式时候按Esc键进入,如下图所示:

命令模式下可以执行一些命令,比如要保存当前工作台信息,按s,删除当前cell可以用dd(和vim也类似)。
markdown模式
在命令模式下,按m则进入markdown模式,在markdown模式下可以按照markdown格式渲染显示,比如标题,同时我们本文要提到的数学公式也要在模式下执行才能显示具体显示。

md渲染结果:

Jupyter Notebook中输入和显示数学公式
在上面的cell markdown模式中我们也提到,要在Jupyter notebook中输入数学公式要用markdown模式,并且取用LaTex格式,但是有变化,在Jupyter notebook数学公式要用$$包住,$数学公式$。
先来一个公式看看

显示结果:

Jupyter Notebook通过Graphivs画图:
首先安装graphviz模块:
pip install graphviz
Hello,Chongchong
安装成功后,重启Jupyter Notebook,打开一个Python3环境,在cell中输入一个简单的例子”Hello,Chongchong”:

ctrl或者shift+Enter ,则会生成hello.gv.pdf的文件,并自动打开:

画个进程图

结果如下:

更多精彩的图也可以做出来,基于Graphivs语法可以做出很多有趣的图,甚至可以写代码生成脑图,这才是harck码农应该有的技能。