[英]How to plot confusion matrix in form of np.array as categorical heatmap in bokeh?
[英]Bokeh heatmap from Pandas confusion matrix
如何將Pandas DataFrame
顯示為Bokeh熱圖?
https://bokeh.pydata.org/zh-CN/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等存在很多不兼容,這是唯一與之兼容的解決方案我的配置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.