Jupyter Notebook Learning

本章是对jupyter的简要介绍以及必要备注

jupyter预加载库配置

创建~/.ipython/profile_default/ipython_config.py文件. 加载库

import matplotlib as mpl

c = get_config()
# 多个输出打印
# c.InteractiveShell.ast_node_interactivity = "all"
# 默认引入的库
c.InteractiveShellApp.exec_lines = [
    "import pandas as pd",  # 载入pandas
    "import numpy as np",  # 载入numpy
    "import matplotlib.pyplot as plt",  # 载入绘图库
    "import seaborn as sns",  # 图表更美观
    "%%load_ext autoreload",  # 自动加载库
    "%%autoreload 2",
]
# 默认绘图库直接显示
c.IPKernelApp.matplotlib = 'inline'
# 设置绘图库的字体。支持中文
mpl.rcParams['font.sans-serif'] = ['SimHei']
# 显示负号
mpl.rcParams['axes.unicode_minus'] = False
# matplotlib在Retina屏幕中显示模糊问题
c.InlineBackend.figure_format = 'retina'

配置matplotlib正确显示中文字体

  • 下载ttf字体文件到 /opt/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf 下
  • 删除cache. rm -rf ~/.matplotlib/*.cache
  • 如果出现 RuntimeError: Python is not installed as a framework. 错误。可以执行一下命令.
    echo "backend: TkAgg" >> ~/.matplotlib/matplotlibrc

jupyter插件配置

安装支持其他语言的内核

安装R语言内核

conda install -c r r-essentials

matplotlib 绘图库

matplotlib 提供了几乎所有python内静态绘图框架的底层命令。相对较快,但是生成图表的命令较多,比较繁琐

In [1]:
x = np.arange(20)
y = x ** 2
plt.title(u"中文")
plt.plot(x, y); # 加上分号抑制最后一行的输出,直接绘图

ploty 绘图库

plotly是跨平台JavaScript交互式绘图包,由于开发者的核心是javascript,所以整个语法类似于写json配置,语法特质也介于「陈述式」和「命令式」之间,无服务版本是免费的。
优点是学习成本不高,可以很快将语句移植到javascript版本;缺点是语言相对繁琐。
初次使用时需要注册用户, 后续可以使用离线模式

注册用户

import plotly

#设置用户名和API-Key
plotly.tools.set_credentials_file(username='DemoAccount', api_key='lr1c37zw81')

# 或者编辑文件 ~/.plotly/.credentials 。填写user_name 和api_key
# {
#     "username": "",
#     "api_key": "",
#     "proxy_username": "",
#     "proxy_password": "",
#     "stream_ids": []
# }

离线使用

在线的时候将会画的图将会存入云账户中

import plotly
from plotly.graph_objs import Scatter, Layout

plotly.offline.init_notebook_mode(connected=True)
In [32]:
import plotly
import plotly.graph_objs as go
import plotly.plotly as py
plotly.offline.init_notebook_mode()

trace = go.Box(
    x=[1, 2, 3, 4, 5, 6, 7]
)
data = [trace]
plotly.offline.iplot(data)

ploty dashboard 发布

将代码组织成图表之后发布成dashboard, 需要依赖在线

In [31]:
import re
import plotly.dashboard_objs as dashboard

import IPython.display
from IPython.display import Image

def fileId_from_url(url):
    """Return fileId from a url."""
    raw_fileId = re.findall("~[A-z]+/[0-9]+", url)[0][1: ]
    return raw_fileId.replace('/', ':')

fileId_1 = fileId_from_url("https://plot.ly/~timking/0")

box_a = {
    'type': 'box',
    'boxType': 'plot',
    'fileId': fileId_1,
    'title': 'scatter-for-dashboard'
}

text_for_box = """ 测试测试 """

box_b = {
    'type': 'box',
    'boxType': 'text',
    'text': text_for_box,
    'title': 'Markdown Options for Text Box'
}

my_dboard = dashboard.Dashboard()
my_dboard.insert(box_a) # 将图box 插入到 dashboard中
my_dboard.insert(box_b, 'left', 1, fill_percent=30) # 文字box 
my_dboard["settings"]["title"] = "测试dashboard"
#my_dboard.get_preview() # 预览
py.dashboard_ops.upload(my_dboard, 'My First Dashboard with Python') # 上传到plotly
Out[31]:
'https://plot.ly/~timking/4/dashboard/'

IPython Widgets

ipywidgets 是ipython提供的一个可以创建和ipython交互的html组件的包
官方文档

scoll

In [1]:
widgets.interact(lambda x: x**2, x=widgets.IntSlider(
    min=10,
    max=50,
    step=1,
    value=10,
    description="Number"
));

boolean

In [2]:
widgets.interact(lambda x: x, x=True);

text

In [3]:
widgets.interact(lambda x: x.upper(), x='');
In [4]:
def handle_submit(sender):
    print(sender.value)

# 绑定方法
text = widgets.Text()
from IPython.display import display
display(text)

text.on_submit(handle_submit)

select

In [5]:
widgets.interact(lambda x: x, x=list("abcd"));
In [6]:
widgets.interact(lambda x: x, x={"one": 1, "ten": 10});

buttons

In [7]:
def on_button_clicked(btn):
    print(btn.description)
    
button = widgets.Button(description="Click Me!")
button.on_click(on_button_clicked)
display(button)
Click Me!

将控件和图组合

In [8]:
def plot(amplitude, color):
    fig, ax = plt.subplots(figsize=(4, 3))
    ax.grid(color='w', linewidth=2, linestyle='solid')
    x = np.linspace(0, 10, 1000)
    ax.plot(x, amplitude * np.sin(x), color=color,
            lw=5, alpha=0.4);
    ax.set_xlim(0, 10)
    ax.set_ylim(-1.1, 1.1)

widgets.interact(
    plot, 
    amplitude=widgets.FloatSlider(
        min=0.1,
        max=1.0,
        step=0.1,
        value=0.1,
        description="Number"
    ), 
    color=widgets.RadioButtons(options=['blue', 'green', 'red'])
);

Comments !