欢迎访问宙启技术站
智能推送

Python中使用Bokeh创建交互式图表

发布时间:2024-01-03 14:40:01

Bokeh是一个用于创建交互式图表的Python库。它提供了许多功能强大的工具和功能,使得可视化数据变得简单而直观。

以下是使用Bokeh创建交互式图表的一些示例:

1. 创建静态的散点图

from bokeh.plotting import figure, show

# 创建一个图表对象
p = figure(plot_width=400, plot_height=400)

# 添加散点数据
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
p.circle(x, y, size=10, color='red')

# 显示图表
show(p)

2. 创建动态的折线图

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource
from bokeh.io import curdoc
from random import randint

# 创建一个图表对象
p = figure(plot_width=400, plot_height=400)

# 创建一个数据源对象
source = ColumnDataSource(data=dict(x=[0], y=[0]))

# 添加折线图
p.line('x', 'y', source=source)

# 更新数据源
def update():
    new_data = dict(x=source.data['x'] + [len(source.data['x'])], y=source.data['y'] + [randint(0, 10)])
    source.data = new_data

# 创建一个周期定时器,每秒更新一次数据
curdoc().add_periodic_callback(update, 1000)

# 显示图表
show(p)

3. 创建动态的柱状图

from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, show
from bokeh.io import curdoc
from random import randint

# 创建一个图表对象
p = figure(plot_width=400, plot_height=400)

# 创建一个数据源对象
source = ColumnDataSource(data=dict(x=[0], height=[0]))

# 添加柱状图
p.vbar(x='x', top='height', source=source, width=0.5)

# 更新数据源
def update():
    new_data = dict(x=source.data['x'] + [len(source.data['x'])], height=source.data['height'] + [randint(0, 10)])
    source.data = new_data

# 创建一个周期定时器,每秒更新一次数据
curdoc().add_periodic_callback(update, 1000)

# 显示图表
show(p)

Bokeh还提供了许多其他功能,例如添加轴标签、图例、背景、颜色映射等。通过使用这些功能,可以创建出更加丰富多样的交互式图表。

希望以上内容能够帮助你使用Bokeh创建交互式图表。如果你想了解更多关于Bokeh的细节和用法,请参考Bokeh的官方文档。