第一步 8: 提供和过滤数据#

之前的第一步指南中,您使用了不同的方法来显示和导出您的可视化。

在本节中,您将使用各种来源和结构来导入和筛选数据。

使用ColumnDataSource#

ColumnDataSource 是 Bokeh 自己的数据结构。有关 ColumnDataSource 的详细信息,请参阅用户指南中的 ColumnDataSource

到目前为止,您已经使用了像Python列表和NumPy数组这样的数据序列来将数据传递给Bokeh。Bokeh已经自动将这些列表转换为ColumnDataSource对象。

按照以下步骤直接创建一个ColumnDataSource

  • 首先,导入 ColumnDataSource

  • 接下来,创建一个包含你的数据的字典:字典的键是列名(字符串)。字典的值是数据列表或数组。

  • 然后,将你的字典作为 data 参数传递给 ColumnDataSource:

  • 然后你可以将你的ColumnDataSource用作渲染器的source

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource

# create dict as basis for ColumnDataSource
data = {'x_values': [1, 2, 3, 4, 5],
        'y_values': [6, 7, 2, 3, 6]}

# create ColumnDataSource based on dict
source = ColumnDataSource(data=data)

# create a plot and renderer with ColumnDataSource data
p = figure(height=250)
p.scatter(x='x_values', y='y_values', size=20, source=source)
show(p)

另请参阅

有关Bokeh的ColumnDataSource的更多信息,请参阅用户指南中的 ColumnDataSource和参考指南中的 ColumnDataSource

有关向ColumnDataSource添加数据的信息,请参阅 向ColumnDataSource追加数据。有关替换ColumnDataSource数据的信息,请参阅用户指南中的 替换ColumnDataSource中的数据

有关使用Python列表的更多信息,请参阅 Providing data with Python lists。有关在Bokeh中使用NumPy数据的更多信息,请参阅Providing NumPy data

转换pandas数据#

要使用来自 pandas DataFrame 的数据,请将您的 pandas 数据传递给 ColumnDataSource

source = ColumnDataSource(df)

另请参阅

有关在Bokeh中使用pandas数据的更多信息,请参阅用户指南中的使用pandas DataFrame。这包括有关使用pandas DataFrameMultiIndexGroupBy数据的信息。

数据过滤#

Bokeh 提供了多种过滤方法。如果你想创建一个包含在 ColumnDataSource 中的数据特定子集,可以使用这些过滤器。

在Bokeh中,这些过滤后的子集被称为“视图”。视图由Bokeh的CDSView类表示。

要使用过滤后的数据子集进行绘图,请将CDSView对象传递给渲染器的view参数。

一个 CDSView 对象有一个属性:

  • filter: Filter 模型的一个实例

最简单的过滤器是IndexFilter。一个 IndexFilter使用一组索引位置,并创建一个仅包含位于这些索引位置的数据点的视图。

例如,如果你的ColumnDataSource包含五个值的列表,并且你应用了一个带有[0,2,4]的IndexFilter,那么生成的view将只包含你原始列表中的第一个、第三个和第五个值:

from bokeh.layouts import gridplot
from bokeh.models import CDSView, ColumnDataSource, IndexFilter
from bokeh.plotting import figure, show

# create ColumnDataSource from a dict
source = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5]))

# create a view using an IndexFilter with the index positions [0, 2, 4]
view = CDSView(filter=IndexFilter([0, 2, 4]))

# setup tools
tools = ["box_select", "hover", "reset"]

# create a first plot with all data in the ColumnDataSource
p = figure(height=300, width=300, tools=tools)
p.scatter(x="x", y="y", size=10, hover_color="red", source=source)

# create a second plot with a subset of ColumnDataSource, based on view
p_filtered = figure(height=300, width=300, tools=tools)
p_filtered.scatter(x="x", y="y", size=10, hover_color="red", source=source, view=view)

# show both plots next to each other in a gridplot layout
show(gridplot([[p, p_filtered]]))

另请参阅

有关Bokeh中各种过滤器的更多信息,请参阅用户指南中的 过滤数据。更多信息也可以在参考指南中的 CDSViewFilter 条目中找到。