Bokeh中columnDataSource的目的是什么?

20

我是bokeh的新手,正在尝试弄清楚columnDataSource是做什么的。它出现在很多地方,但我不确定它的目的以及它是如何工作的。有人可以解释一下吗?如果这是一个愚蠢的问题,请原谅...

(注意:已经翻译并保留了HTML标签)

4
如果您熟悉 R 或 Pandas 中的“DataFrame”对象,那么“ColumnDataSource”基本上是其简化版。它是一个数据数组集合(列),可以通过名称引用。实际的内部结构就是一个将字符串映射到列表/数组的字典。这是将数据从 Python 传输到 BokehJS 浏览器库的主要方式。 - bigreddot
2个回答

19

ColumnDataSource是Bokeh图表中存储数据的对象。你可以选择不使用ColumnDataSource,直接使用Python字典、pandas数据框等来生成图形,但是对于某些功能,例如在用户将鼠标悬停在图形上时显示数据信息的弹出窗口,你必须使用ColumnDataSource,否则弹出窗口将无法获取数据。其他用途包括流式传输数据。

你可以从字典和pandas数据框创建ColumnDataSource,然后使用它来创建图形。


2
请问您能否添加一个小例子来说明您在答案中所写的内容?比如一个时间序列,当鼠标悬停在图表上方时,您想要查看数据。 - famargar

6

这应该可以工作:

import pandas as pd
import bokeh.plotting as bp
from bokeh.models import HoverTool, DatetimeTickFormatter

# Create the base data
data_dict = {"Dates":["2017-03-01",
                  "2017-03-02",
                  "2017-03-03",
                  "2017-03-04",
                  "2017-03-05",
                  "2017-03-06"],
             "Prices":[1, 2, 1, 2, 1, 2]}

# Turn it into a dataframe
data = pd.DataFrame(data_dict, columns = ['Dates', 'Prices'])

# Convert the date column to the dateformat, and create a ToolTipDates column
data['Dates'] = pd.to_datetime(data['Dates'])
data['ToolTipDates'] = data.Dates.map(lambda x: x.strftime("%b %d")) # Saves work with the tooltip later

# Create a ColumnDataSource object
mySource = bp.ColumnDataSource(data)

# Create your plot as a bokeh.figure object
myPlot = bp.figure(height = 600,
               width = 800,
               x_axis_type = 'datetime',
               title = 'ColumnDataSource',
               y_range=(0,3))

# Format your x-axis as datetime.
myPlot.xaxis[0].formatter = DatetimeTickFormatter(days='%b %d')

# Draw the plot on your plot object, identifying the source as your Column Data Source object.
myPlot.circle("Dates",
          "Prices",
          source=mySource,
          color='red',
          size = 25)

# Add your tooltips
myPlot.add_tools( HoverTool(tooltips= [("Dates","@ToolTipDates"),
                                    ("Prices","@Prices")]))


# Create an output file
bp.output_file('columnDataSource.html', title = 'ColumnDataSource')
bp.show(myPlot) # et voilà.

这似乎是一个绘图示例,而不是数据类型的解释。 - Kyle
4
嗨,Kyle,谢谢你注意到了。说实话,我的回答是一个情节的示例,而不是数据类型的解释。我认为早期的一些答案已经很好地解释了理论。我的意图是根据@famargar在帖子中的要求添加一个简短的实际示例。 - amunnelly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接