装扮你的 Jupyter Notebook

这次,教大家如何搭建一个好看的 jupyter 环境。

安装 Jupyter

先来展示一下我的环境

  • python: 3.5.*

  • macos: 10.12.4

安装 Jupyter 的过程只需安装 Anaconda即可。

测试一下初始设置:

 
  1. jupyter notebook

配置 ipython

首先,如果每次你打开一个 nb(notebook)时,如果都需要载入一些模块,一个很好地方法就是配置 ipython 的配置文件,可以直接使用以下命令创建配置文件:

 
  1. ipython profile create

此时你会在 ~/.ipython/profile_default/ 目录中获得下面两个文件:

  • ipython_config.py:打开任意 ipython kernel 时都会运行

  • ipython_notebook_config.py:打开 notebook 时会运行

配置方式是在所需要的配置文件中先键入:

 
  1. c = get_config()

然后就可以通过修改 c 的属性来控制所有的配置。

显然,对大多数分析场景, numpyscipypandas 是肯定要载入的,因此,写到配置中即可:

 
  1. c.InteractiveShellApp.exec_lines = [

  2.        "import pandas as pd",

  3.        "import numpy as np",

  4.        "import scipy.stats as spstats",

  5.        "import scipy as sp",

  6.        ]

配置 matplotlib

还有一个常用功能就是 matplotlib。 matplotlib 在 notebook 中需要使用

 
  1. %matplotlib inline

才可默认在 notebook 中显示图像,一个简单地方法就是在配置文件中加入,

 
  1. c.IPKernelApp.matplotlib = 'inline'

当然,默认也需要载入 matplotlib

 
  1. c.InteractiveShellApp.exec_lines = [

  2.        "import pandas as pd",

  3.        "import numpy as np",

  4.        "import scipy.stats as spstats",

  5.        "import scipy as sp",

  6.        "import matplotlib.pyplot as plt"

  7.        ]

当然,也可以更多。但这样可能会影响初始化 notebook 和 ipython shell 的速度,这个请大家自己权衡。

matplotlib 显示中文

此外,单独拎 matplotlib 出来的另一个原因是, matplotlib 还有一个中文显示的问题。

首先,解决编码问题

python 2.7.* 的解决方案是,在配置中加入:

 
  1. import seaborn as sns

  2. import sys# print sys.getdefaultencoding()# ipython notebook 中默认是 ascii 编码

  3. reload(sys)

  4. sys.setdefaultencoding('utf8')

python 3.* 出于某些原因,不建议通过 sys 模块修改编码,原因参见 这里。

解决方案是,在 shell 的配置中重新设置配置变量(bash的话设置文件 .bashrczsh则设置文件 .zshrc)。方法是末尾添加:

 
  1. export PYTHONIOENCODING="utf8"

当然另一个方法是在启动 notebook 时使用

 
  1. PYTHONIOENCODING="utf8" & jupyter notebook

第二个是修改 matplotlib 的默认字体

首先我们来看可以使用的字体

 
  1. import matplotlib.font_manager

  2. fonts = matplotlib.font_manager.findSystemFonts()

  3. l = []

  4. for f in fonts:

  5.    try:

  6.        font =matplotlib.font_manager.FontProperties(fname=f)

  7.        #print(font.get_family())

  8.        l.append((f, font.get_name(), font.get_family(), font.get_weight()))

  9.    except:

  10.        pass

  11. df = pd.DataFrame(l, columns=['path', 'name', 'family', 'weight'])

  12. df

你应该看到下面这样的表格:

然后找到支持中文的字体名,然后设置 matplotlib 的默认字体:

 
  1. import matplotlib as mpl

  2. mpl.rc('font', family='Noto Sans CJK SC')

当然,你可以添加到刚才的配置中,或者采用 这个博客的方法。

此外,如果你使用 seaborn 的话, seaborn 在设置配置时可能会覆盖掉 matplotlib,此时采用以下代码即可:

 
  1. import seaborn as sns

  2. sns.set_style('ticks',

  3.              {

  4.                    'font.family': ['Noto Sans CJK SC'],

  5.    })

但是,该语句不建议写在配置中,因为经常需要修改,可能会覆盖之前的配置。

matplotlib 在 Retina 屏幕中显示模糊问题

直接使用下面语句即可,

 
  1. %config InlineBackend.figure_format = 'retina'

当然也可在配置中直接加入

 
  1. c.InlineBackend.figure_format = 'retina'

修改 notebook 样式

默认的 notebook 可以逼你心中大喊 WTF,这时候你需要一点 CSS 技能,修改 ~/.jupyter/custom/custom.css 的内容。

个人认为最需要修改的内容包括

  1. notebook 的默认宽度:notebook 默认比较宽,markdown 文字会显得比较少,如果需要对外展示,文字部分会过少。

  2. notebook 的代码字体

我的修改规则是:

 
  1. pre.CodeMirror-line {

  2.    font-family: 'BlinkMacSystemFont', 'Lucida Grande', 'Segoe UI', Ubuntu, Cantarell, sans-serif

  3. }

  4.  
  5. .output_subarea.output_text.output_result>pre {

  6.    font-family: 'BlinkMacSystemFont', 'Lucida Grande', 'Segoe UI', Ubuntu, Cantarell, sans-serif

  7. }

  8.  
  9. .output_subarea.output_text.output_stream.output_stdout>pre {

  10.    font-family: 'BlinkMacSystemFont', 'Lucida Grande', 'Segoe UI', Ubuntu, Cantarell, sans-serif

  11. }

  12.  
  13. #notebook-container {

  14.    max-width: 830px;

  15.    padding: 40px;

  16. }

安装 Jupyter 常用插件

这里推荐两个 jupyter 插件:

插件管理器 jupyter notebook extensions

github 地址在 这里。安装和介绍也可以参考。

然后你就可以在 jupyter 主页里找到下面的标签页管理插件了:

jupyter Dashboard

如果你的 jupyter 服务是搭建在主机上,并且平时和业务人员想用 notebook 地址的方式交付, jupyter dashboard 插件是一个不错的选择。

安装方法和 github 地址在 这里。

原本效果如下:

点击如下红色设置,并点击黄色按钮后

就可得到如下的报告形式(删去了业务人员不想查看的代码),然后就可以粘贴连接交付报告了:

切换成 dashboard 模式可以拖拽相关方格来设置位置。

安装 R kernel

R kernel 安装方式有两个:

通过 conda 安装

 
  1. conda create -n R-Env -c r r-essentials

  2. source activate R-Env

  3. conda install jupyter

然后在 R 中配置

 
  1. install.packages(c('repr', 'IRdisplay', 'evaluate', 'crayon', 'pbdZMQ', 'devtools', 'uuid', 'digest'))

  2. devtools::install_github('IRkernel/IRkernel')

  3. IRkernel::installspec()

建议一定要新建环境,不然会和你之前安装的 R 冲突。

当然,我不建议这种安装方式,原因是:

  1. 不是很多人想在电脑里有两个 R 环境

  2. 在 jupyter notebook 中不配置默认镜像,是没法选择镜像的,这导致没法再 notebook 中直接安装 R 包,当然你也可以配置好默认 CRAN 镜像,但这样显然很麻烦,切换网络环境后也很难调整

  3. 可能你在旧环境中已经安装了大量包,这样子迁移成为问题

  4. 你必须在这个新环境中启动 jupyter

直接使用原本安装

直接在 R 环境中使用以下语句

 
  1. install.packages(c('repr', 'IRdisplay', 'evaluate', 'crayon', 'pbdZMQ', 'devtools', 'uuid', 'digest'))

  2. devtools::install_github('IRkernel/IRkernel')

  3. IRkernel::installspec()

  4. IRkernel::installspec(user = FALSE)

设置 Jupyter 服务配置

这里请做个区别:ipython 是负责和 python 交互的部分,jupyter 是作为服务的部分。因此所有服务配置都要在 ~/.jupyter 中进行,而和 python、模块相关的配置都要在 ~/.ipython 中。

这里主要配置的有 ip 和默认文件夹。

首先,生成配置文件:

 
  1. jupyter notebook --generate-config

现在 ~/.jupyter/ 内就生成 jupyter_notebook_config.py 文件。

再次我们设置 ip,在其中添加,这样就可以外网访问。

 
  1. NotebookApp.ip = '127.0.0.1'

最后,加上默认启动位置,这样,在任何工作目录下都能保证,notebook 的启动位置一致。

 
  1. NotebookApp.notebook_dir = '/jupyter'


大功告成,现在开工!

猜你喜欢

转载自blog.csdn.net/dongnaoedu/article/details/81084155