简体   繁体   English

熊猫混淆矩阵的散景热图

[英]Bokeh heatmap from Pandas confusion matrix

How can a Pandas DataFrame be shown as a Bokeh heatmap? 如何将Pandas DataFrame显示为Bokeh热图?

https://bokeh.pydata.org/en/latest/docs/user_guide/categorical.html#heat-maps shows some example, but trying to modify always only gave an empty plot. https://bokeh.pydata.org/zh-CN/latest/docs/user_guide/categorical.html#heat-maps显示了一些示例,但尝试进行修改始终只会得出空白。

Example confusion matrix: 混淆矩阵示例:

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'

First import packages and prepare data.frame : 首先导入包并准备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'

To use my solution you have to stack the data.frame : 要使用我的解决方案,您必须堆叠 data.frame:

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

Now, we can create the plot : 现在,我们可以创建图:

# 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)

*Note : I use a more complete solution than just call HeatMap from the bokeh library because 1) you have more control on parameters like this, 2) there are lot of incompatibilities with Bokeh, Pandas, etc and this is the only solution working with my configuration. *注意:我使用的是比从bokeh库中调用HeatMap更为完整的解决方案,因为1)您可以像这样对参数进行更多控制,2)与Bokeh,Pandas等存在很多不兼容,这是唯一与之兼容的解决方案我的配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM