Skip to main content
 首页 » 编程设计

python之来自 Pandas 混淆矩阵的 Bokeh 热图

2025年05月04日13JustinYoung

如何将 Pandas DataFrame 显示为 Bokeh 热图?

https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html#heat-maps显示了一些示例,但尝试修改总是只给出一个空图。

示例混淆矩阵:

df = pd.DataFrame([[10, 0, 1], [1, 10, 0], [1, 1, 9]],  
                  columns=['A', 'B', 'C'],  
                  index=['A', 'B', 'C']) 
df.index.name = 'Treatment' 
df.columns.name = 'Prediction' 

请您参考如下方法:

首先导入包并准备data.frame:

import pandas as pd 
 
from bokeh.io import output_file, show 
from bokeh.models import BasicTicker, ColorBar, LinearColorMapper, ColumnDataSource, PrintfTickFormatter 
from bokeh.plotting import figure 
from bokeh.transform import transform 
 
df = pd.DataFrame( 
    [[10, 0, 1], [1, 10, 0], [1, 1, 9]], 
    columns=['A', 'B', 'C'], 
    index=['A', 'B', 'C']) 
df.index.name = 'Treatment' 
df.columns.name = 'Prediction' 

要使用我的解决方案,您必须堆叠 data.frame:

# Prepare data.frame in the right format 
df = df.stack().rename("value").reset_index() 

现在,我们可以创建绘图了:

# here the plot : 
output_file("myPlot.html") 
 
# You can use your own palette here 
colors = ['#d7191c', '#fdae61', '#ffffbf', '#a6d96a', '#1a9641'] 
 
# Had a specific mapper to map color with value 
mapper = LinearColorMapper( 
    palette=colors, low=df.value.min(), high=df.value.max()) 
# Define a figure 
p = figure( 
    plot_width=800, 
    plot_height=300, 
    title="My plot", 
    x_range=list(df.Treatment.drop_duplicates()), 
    y_range=list(df.Prediction.drop_duplicates()), 
    toolbar_location=None, 
    tools="", 
    x_axis_location="above") 
# Create rectangle for heatmap 
p.rect( 
    x="Treatment", 
    y="Prediction", 
    width=1, 
    height=1, 
    source=ColumnDataSource(df), 
    line_color=None, 
    fill_color=transform('value', mapper)) 
# Add legend 
color_bar = ColorBar( 
    color_mapper=mapper, 
    location=(0, 0), 
    ticker=BasicTicker(desired_num_ticks=len(colors))) 
 
p.add_layout(color_bar, 'right') 
 
show(p) 

*注意:我使用的解决方案比仅从 bokeh 库调用 HeatMap 更完整,因为 1) 您可以更好地控制这样的参数,2) 与 Bokeh、Pandas 有很多不兼容之处等等,这是唯一适用于我的配置的解决方案。