#!/usr/bin/env python # coding: utf-8 # # # # # #
# # # # #

Bokeh 教程

#
# #

04. 数据源和数据转换

# In[1]: from bokeh.io import output_notebook, show from bokeh.plotting import figure # In[2]: output_notebook() # # 概要 # # 我们已经看到Bokeh怎么能够很好地与Python列表、NumPy数组、Pandas序列一起工作。在底层,这些输入数据被转换为Bokeh的`ColumnDataSource`类型。这个数据类型是Bokeh使用的核心数据源对象。虽然Bokeh经常通过透明的方式创建该类型对象,但有些时候也需要通过显式的方式创建。 # # 下一节,我们会看到hover tooltips,computed transforms 和 CustomJS interactions 等使用`ColumnDataSource`的功能,所以,现在我们快速的瞄一眼。 # ## 通过 Python Dicts 创建 # # 从 `bokeh.models` 导入 `ColumnDataSource`: # In[3]: from bokeh.models import ColumnDataSource # `ColumnDataSource`是从列名(字符串)到值序列的映射。下面是一个简单的例子。映射是通过传入Python `dict`建立的,其字符串键作为列名,对应的Python list作为值序列。该值序列也可以是NumPy数组,或Pandas序列。 # # ***注意:`ColumnDataSource` 中所有的列必须等长。*** # # In[4]: source = ColumnDataSource(data={ 'x' : [1, 2, 3, 4, 5], 'y' : [3, 7, 8, 5, 1], }) # 到目前,我们已经通过直接传入文本列表或数组数据的方式调用函数,如`p.circle`。当我们这样做时,Bokeh会自动帮我们创建一个 `ColumnDataSource`。但我们也可以显式地把 `ColumnDataSource` 作为 `source` 参数传入glyph函数。当我们这样做时,如果我们想要给一个属性(如`"x"` 或 `"y"` 或 `"fill_color"`)指定一个值序列,我们传入对应的***列名***: # In[5]: p = figure(plot_width=400, plot_height=400) p.circle('x', 'y', size=20, source=source) show(p) # In[6]: # Exercise: create a column data source with NumPy arrays as column values and plot it # ## 通过 Pandas DataFrames 创建 # # 通过Pandas Dataframe创建 `ColumnDataSource` 对象也很容易。只需要在创建 `ColumnDataSource` 的时候把Dataframe传入就行: # In[7]: from bokeh.sampledata.iris import flowers as df source = ColumnDataSource(df) # 现在我们就可以使用这个对象绘制上例中的图了,把对应的列名传入glyph函数: # In[8]: p = figure(plot_width=400, plot_height=400) p.circle('petal_length', 'petal_width', source=source) show(p) # In[9]: # Exercise: create a column data source with the autompg sample data frame and plot it from bokeh.sampledata.autompg import autompg_clean as df