Bokeh 初探

之前本來想想研究下 pandas+highchart 的解決方案指么,網(wǎng)上搜了下發(fā)現(xiàn)Bokeh 這個好東西宴合,簡單易用渠啊,天然就是支持python 和 pandas迷帜。而且很多場合都能用 (可以純python用物舒,可以在jupyter里面用,可以和flask結(jié)合用戏锹,甚至有自己的bokeh server)茶鉴, 挺有意思的

官方網(wǎng)址: http://bokeh.pydata.org/en/latest/
Github: https://github.com/bokeh/bokeh

安裝

bokeh需要這幾個庫:

  • NumPy
  • Jinja2
  • Six
  • Requests
  • Tornado >= 4.0
  • PyYaml
  • DateUtil

最方便的方式還是在anacode 下面安裝, 用這個命令 conda install bokeh

簡單的例子

from bokeh.plotting import figure, output_file, show

# prepare some data
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]

# output to static HTML file
output_file("lines.html")

# create a new plot with a title and axis labels
p = figure(title="simple line example", x_axis_label='x', y_axis_label='y')

# add a line renderer with legend and line thickness
p.line(x, y, legend="Temp.", line_width=2)

# show the results
show(p)

Jupyter 中的使用

先導(dǎo)入下面的package. from bokeh.io import push_notebook, show, output_notebook, 再用 output_notebook() 設(shè)置輸出在jupyter notebook里面景用。( 一般情況是用output_file()輸出為html文件。) 這樣還不夠惭蹂, 還需要在show()函數(shù)設(shè)置 notebook_hanlde 參數(shù)為True伞插。
下面是個官方的例子:

from bokeh.io import push_notebook, show, output_notebook
from bokeh.layouts import row
from bokeh.plotting import figure
output_notebook()

opts = dict(plot_width=250, plot_height=250, min_border=0)
p1 = figure(**opts)
r1 = p1.circle([1,2,3], [4,5,6], size=20)

p2 = figure(**opts)
r2 = p2.circle([1,2,3], [4,5,6], size=20)

# get a handle to update the shown cell with
t = show(row(p1, p2), notebook_handle=True)

可以用push_notebook() 函數(shù)更新上面的渲染的圖像。在上面的代碼后建新的cell:

# this will update the left plot circle color with an explicit handle
r1.glyph.fill_color = "white"
push_notebook(handle=t)

運行完后可以發(fā)現(xiàn)上面cell的輸出圖像變化了盾碗。

可以去github中example->howto->notebook_comms->basic Usage.ipynb 自己下載下來玩

chart 庫 + pandas

如何方便的bokeh去快速渲染pandas的數(shù)據(jù)呢媚污, 用chart, chart 庫的使用說明可以去http://bokeh.pydata.org/en/latest/docs/reference/charts.html

簡而言之廷雅,chart 庫下面支持下面的幾種渲染類型:

  • Area
  • Bar
  • BoxPlot
  • Chord
  • Donut
  • HeatMap
  • Horizon
  • Line
  • Scatter
  • Step
  • TimeSeries
    一個例子:
from bokeh.charts import Histogram, output_file, show
from bokeh.layouts import row
from bokeh.sampledata.autompg import autompg as df

hist = Histogram(df, values='mpg', title="Auto MPG Histogram", plot_width=400)
hist2 = Histogram(df, values='mpg', label='cyl', color='cyl', legend='top_right',
                  title="MPG Histogram by Cylinder Count", plot_width=400)

output_file('hist.html')
show(row(hist, hist2))

bokeh的sample data里面自帶一些pandas 的dataframe的數(shù)據(jù)

mpl 庫

我之前其實已經(jīng)有用matplotlib.pyplot 庫去產(chǎn)生圖片了耗美,mpl庫提供了一個快速替換的方法京髓。

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy import optimize

from bokeh import mpl
from bokeh.plotting import output_file, show

# Set the palette colors.
sns.set(palette="Set2")

# Build the sin wave
def sine_wave(n_x, obs_err_sd=1.5, tp_err_sd=.3):
    x = np.linspace(0, (n_x - 1) / 2, n_x)
    y = np.sin(x) + np.random.normal(0, obs_err_sd) + np.random.normal(0, tp_err_sd, n_x)
    return y

sines = np.array([sine_wave(31) for _ in range(20)])

# Generate the Seaborn plot with "ci" bars.
ax = sns.tsplot(sines, err_style="ci_bars", interpolate=False)
xmin, xmax = ax.get_xlim()
x = np.linspace(xmin, xmax, sines.shape[1])
out, _ = optimize.leastsq(lambda p: sines.mean(0) - (np.sin(x / p[1]) + p[0]), (0, 2))
a, b = out
xx = np.linspace(xmin, xmax, 100)
plt.plot(xx, np.sin(xx / b) + a, c="#444444")

plt.title("Seaborn tsplot with CI in bokeh.")

output_file("seaborn_errorbar.html", title="seaborn_errorbar.py example")

#原來用plt.show()去產(chǎn)生圖片
#plt.show()

show(mpl.to_bokeh())

可以看到之前我用plt.show() 去產(chǎn)生圖片,現(xiàn)在可以直接用show(mpl.to_bokeh()) .只要改動一行代碼就可以了商架!

Flask 中的使用

一個例子, python:

'''This example demonstrates embedding a standalone Bokeh document
into a simple Flask application, with a basic HTML web form.

To view the example, run:

    python simple.py

in this directory, and navigate to:

    http://localhost:5000

'''
from __future__ import print_function

import flask

from bokeh.embed import components
from bokeh.plotting import figure
from bokeh.resources import INLINE
from bokeh.util.string import encode_utf8

app = flask.Flask(__name__)

colors = {
    'Black': '#000000',
    'Red':   '#FF0000',
    'Green': '#00FF00',
    'Blue':  '#0000FF',
}

def getitem(obj, item, default):
    if item not in obj:
        return default
    else:
        return obj[item]

@app.route("/")
def polynomial():
    """ Very simple embedding of a polynomial chart

    """

    # Grab the inputs arguments from the URL
    args = flask.request.args

    # Get all the form arguments in the url with defaults
    color = getitem(args, 'color', 'Black')
    _from = int(getitem(args, '_from', 0))
    to = int(getitem(args, 'to', 10))

    # Create a polynomial line graph with those arguments
    x = list(range(_from, to + 1))
    fig = figure(title="Polynomial")
    fig.line(x, [i ** 2 for i in x], color=colors[color], line_width=2)

    js_resources = INLINE.render_js()
    css_resources = INLINE.render_css()

    script, div = components(fig)
    html = flask.render_template(
        'embed.html',
        plot_script=script,
        plot_div=div,
        js_resources=js_resources,
        css_resources=css_resources,
        color=color,
        _from=_from,
        to=to
    )
    return encode_utf8(html)

if __name__ == "__main__":
    print(__doc__)
    app.run()

embed.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset='utf-8' />
    <meta http-equiv='content-type' content='text/html; charset=utf-8' />

    <title>Embed Demo</title>

    {{ js_resources|indent(4)|safe }}

    {{ css_resources|indent(4)|safe }}

    {{ plot_script|indent(4)|safe }}

  </head>
  <body>
    <!-- A simple form for changing the graph -->
    <p> Select your settings: </p>
    <form name="color_button" method='GET'>
        Color:
        <select name="color">
            <option {{ "selected" if color|indent(4)|safe == "Red" }} value="Red">Red</option>
            <option {{ "selected" if color|indent(4)|safe == "Green" }} value="Green">Green</option>
            <option {{ "selected" if color|indent(4)|safe == "Blue" }} value="Blue">Blue</option>
            <option {{ "selected" if color|indent(4)|safe == "Black" }} value="Black">Black</option>
        </select>
        <br>
        From:
        <input type="text" name="_from" value="{{ _from }}">
        <br>
        To:
        <input type="text" name="to" value="{{ to }}">
        <br>
        <button type="submit">Submit</button>
    </form>
    {{ plot_div|indent(4)|safe }}
    <p> Demonstrates some very simple embedding into a webpage</p>
  </body>
</html>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末堰怨,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子蛇摸,更是在濱河造成了極大的恐慌备图,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件赶袄,死亡現(xiàn)場離奇詭異揽涮,居然都是意外死亡,警方通過查閱死者的電腦和手機饿肺,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進店門蒋困,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人敬辣,你說我怎么就攤上這事雪标。” “怎么了购岗?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵汰聋,是天一觀的道長。 經(jīng)常有香客問我喊积,道長烹困,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任乾吻,我火速辦了婚禮髓梅,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘绎签。我一直安慰自己枯饿,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布诡必。 她就那樣靜靜地躺著奢方,像睡著了一般。 火紅的嫁衣襯著肌膚如雪爸舒。 梳的紋絲不亂的頭發(fā)上蟋字,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天,我揣著相機與錄音扭勉,去河邊找鬼鹊奖。 笑死,一個胖子當(dāng)著我的面吹牛涂炎,可吹牛的內(nèi)容都是我干的忠聚。 我是一名探鬼主播设哗,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼两蟀!你這毒婦竟也來了网梢?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤垫竞,失蹤者是張志新(化名)和其女友劉穎澎粟,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體欢瞪,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡活烙,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了遣鼓。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片啸盏。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖骑祟,靈堂內(nèi)的尸體忽然破棺而出回懦,到底是詐尸還是另有隱情,我是刑警寧澤次企,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布怯晕,位于F島的核電站,受9級特大地震影響缸棵,放射性物質(zhì)發(fā)生泄漏舟茶。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一堵第、第九天 我趴在偏房一處隱蔽的房頂上張望吧凉。 院中可真熱鬧,春花似錦踏志、人聲如沸阀捅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽饲鄙。三九已至,卻和暖如春圆雁,著一層夾襖步出監(jiān)牢的瞬間傍妒,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工摸柄, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人既忆。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓驱负,卻偏偏與公主長得像嗦玖,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子跃脊,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內(nèi)容