利用Bokeh绘制直方图的简洁代码示例
发布时间:2024-01-03 14:55:53
Bokeh是一个用于生成交互式图形的Python库。通过Bokeh,我们可以使用简洁的代码绘制各种图表,包括直方图。
以下是一个利用Bokeh绘制直方图的简洁代码示例:
import numpy as np
from bokeh.io import output_file, show
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
# 生成随机数据
data = np.random.normal(0, 1, 1000)
# 创建直方图的bins和频数
hist, edges = np.histogram(data, bins=30)
# 创建直方图的数据源
source = ColumnDataSource(data={'top': hist, 'left': edges[:-1], 'right': edges[1:]})
# 创建绘图对象
p = figure(plot_height=400, plot_width=600, x_axis_label='Value', y_axis_label='Count',
toolbar_location='above')
# 绘制直方图
p.quad(source=source, top='top', bottom=0, left='left', right='right', fill_color='dodgerblue',
line_color='black')
# 输出到HTML文件
output_file('histogram.html')
# 展示图表
show(p)
上述代码首先生成了具有1000个随机数据的数组。然后,使用np.histogram函数计算了直方图的频数和bins。接下来,创建了一个Bokeh的数据源ColumnDataSource,其中包含了直方图的top、left和right属性。绘图对象p通过figure函数创建,并设置了绘图的高度、宽度、横纵坐标的标签和工具栏的位置。最后,使用p.quad函数绘制了直方图,并将相关属性与数据源关联起来。最后,图表被输出到histogram.html文件中,并通过show函数展示出来。
下面是一个使用该代码绘制直方图的例子:
import numpy as np
from bokeh.io import output_file, show
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
# 生成随机数据
data = np.random.normal(0, 1, 1000)
# 创建直方图的bins和频数
hist, edges = np.histogram(data, bins=30)
# 创建直方图的数据源
source = ColumnDataSource(data={'top': hist, 'left': edges[:-1], 'right': edges[1:]})
# 创建绘图对象
p = figure(plot_height=400, plot_width=600, x_axis_label='Value', y_axis_label='Count',
toolbar_location='above')
# 绘制直方图
p.quad(source=source, top='top', bottom=0, left='left', right='right', fill_color='dodgerblue',
line_color='black')
# 输出到HTML文件
output_file('histogram.html')
# 展示图表
show(p)
