要实现“Bokeh 聚类条形图”,你可以使用以下步骤:
pip install bokeh
bokeh.plotting
、bokeh.models
和 bokeh.io
。此外,还需要导入其他必要的库,如 numpy
和 sklearn
(用于生成示例数据和进行聚类)。import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource
from bokeh.io import output_notebook
make_blobs
函数生成一些随机的聚类数据,用于演示。# 生成示例数据
X, y = make_blobs(n_samples=100, centers=3, random_state=0)
KMeans
类进行聚类,并将每个样本的聚类结果作为标签。# 进行聚类
kmeans = KMeans(n_clusters=3, random_state=0)
labels = kmeans.fit_predict(X)
figure
函数创建一个条形图,并使用 ColumnDataSource
将数据传递给图表。设置条形图的 x 轴为聚类标签,y 轴为每个聚类的样本数量。# 创建 Bokeh 图表
output_notebook() # 在 Jupyter Notebook 中显示图表
# 创建 ColumnDataSource
source = ColumnDataSource(data=dict(x=labels, top=np.bincount(labels)))
# 创建条形图
p = figure(plot_height=400, plot_width=400, title="Cluster Bar Chart")
p.vbar(x='x', top='top', source=source, width=0.9)
# 设置 x 和 y 轴标签
p.xaxis.axis_label = 'Cluster Label'
p.yaxis.axis_label = 'Number of Samples'
show
函数显示图表。# 显示图表
show(p)
完整的代码示例如下:
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource
from bokeh.io import output_notebook
# 生成示例数据
X, y = make_blobs(n_samples=100, centers=3, random_state=0)
# 进行聚类
kmeans = KMeans(n_clusters=3, random_state=0)
labels = kmeans.fit_predict(X)
# 创建 Bokeh 图表
output_notebook() # 在 Jupyter Notebook 中显示图表
# 创建 ColumnDataSource
source = ColumnDataSource(data=dict(x=labels, top=np.bincount(labels)))
# 创建条形图
p = figure(plot_height=400, plot_width=400, title="Cluster Bar Chart")
p.vbar(x='x', top='top', source=source, width=0.9)
# 设置 x 和 y 轴标签
p.xaxis.axis_label = 'Cluster Label'
p.yaxis.axis_label = 'Number of Samples'
# 显示图表
show(p)
运行以上代码,你将会在 Jupyter Notebook 中看到生成的 Bokeh 聚类条形图。