python bokeh,如何制作相关图?

2023-11-29

如何在 Bokeh 中制作相关热图?

import pandas as pd
import bokeh.charts

df = pd.util.testing.makeTimeDataFrame(1000)
c = df.corr()

p = bokeh.charts.HeatMap(c) # not right

# try to make it a long form
# (and it's ugly in pandas to use 'index' in melt)

c['x'] = c.index
c = pd.melt(c, 'x', ['A','B','C','D'])

# this shows the right 4x4 matrix, but values are still wrong
p = bokeh.charts.HeatMap(c, x = 'x', y = 'variable', values = 'value') 

顺便问一下,我可以在侧面制作一个颜色条,而不是情节中的图例吗?以及如何选择颜色范围/映射,例如深蓝色(-1)到白色(0)到深红色(+1)?


所以我想我可以提供一个基线代码来帮助完成您所要求的工作,结合使用上面的答案和一些额外的预处理。

假设您有一个数据框df已经加载(在本例中UCI 成人数据)和计算的相关系数(p_corr).

import bisect
#
from math import pi
from numpy import arange
from itertools import chain
from collections import OrderedDict
#
from bokeh.palettes import RdBu as colors  # just make sure to import a palette that centers on white (-ish)
from bokeh.models import ColorBar, LinearColorMapper

colors = list(reversed(colors[9]))  # we want an odd number to ensure 0 correlation is a distinct color
labels = df.columns
nlabels = len(labels)

def get_bounds(n):
    """Gets bounds for quads with n features"""
    bottom = list(chain.from_iterable([[ii]*nlabels for ii in range(nlabels)]))
    top = list(chain.from_iterable([[ii+1]*nlabels for ii in range(nlabels)]))
    left = list(chain.from_iterable([list(range(nlabels)) for ii in range(nlabels)]))
    right = list(chain.from_iterable([list(range(1,nlabels+1)) for ii in range(nlabels)]))
    return top, bottom, left, right

def get_colors(corr_array, colors):
    """Aligns color values from palette with the correlation coefficient values"""
    ccorr = arange(-1, 1, 1/(len(colors)/2))
    color = []
    for value in corr_array:
        ind = bisect.bisect_left(ccorr, value)
        color.append(colors[ind-1])
    return color

p = figure(plot_width=600, plot_height=600,
           x_range=(0,nlabels), y_range=(0,nlabels),
           title="Correlation Coefficient Heatmap (lighter is worse)",
           toolbar_location=None, tools='')

p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None
p.xaxis.major_label_orientation = pi/4
p.yaxis.major_label_orientation = pi/4

top, bottom, left, right = get_bounds(nlabels)  # creates sqaures for plot
color_list = get_colors(p_corr.values.flatten(), colors)

p.quad(top=top, bottom=bottom, left=left,
       right=right, line_color='white',
       color=color_list)

# Set ticks with labels
ticks = [tick+0.5 for tick in list(range(nlabels))]
tick_dict = OrderedDict([[tick, labels[ii]] for ii, tick in enumerate(ticks)])
# Create the correct number of ticks for each axis 
p.xaxis.ticker = ticks
p.yaxis.ticker = ticks
# Override the labels 
p.xaxis.major_label_overrides = tick_dict
p.yaxis.major_label_overrides = tick_dict

# Setup color bar
mapper = LinearColorMapper(palette=colors, low=-1, high=1)
color_bar = ColorBar(color_mapper=mapper, location=(0, 0))
p.add_layout(color_bar, 'right')

show(p)

如果类别是整数编码的,这将导致以下绘图(这是一个可怕的数据示例):

Pearson Correlation Coefficient Heatmap in Bokeh

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python bokeh,如何制作相关图? 的相关文章

随机推荐

  • 我可以仅在底部椭圆化剪贴蒙版吗?

    我正在尝试在 CSS 中的图像上创建弯曲的剪贴蒙版 该曲线本质上只是一个非常宽的椭圆的下半部分 要求是角度 曲率不会根据图像的高度 宽度而改变 它应该始终保持一致 这是一个视觉效果 尝试1 边框半径 溢出隐藏 固定宽度 问题 图像高度影响曲
  • 为什么“cut”反对我的标签?

    我试图根据值所属的范围来标记值 就像你对作业评分一样 因此 如果我有一个平均测验分数的数据框和一个数值数据框 我将其用作为这些平均值分配分数的下限 grades lt read table text Student Mean Adam 94
  • 私人运营商删除[重复]

    这个问题在这里已经有答案了 可能的重复 公共运算符 new 私有运算符删除 使用 new 时出现 C2248 无法访问私有成员 http efesx com 2009 12 01 public operator new and privat
  • jQuery addClass 方法链接以执行 CSS 转换

    我想做的事 broke div div
  • 通过java App查看PDF

    我想知道如何通过 Java 应用程序查看 PDF 我正在尝试创建一个应用程序来使用 NetBeans 6 8 查看 PDF 很少有 pdf 阅读器库 例如 iText pdfBox 但他们没有帮助我 请帮我 任何帮助都是感激的 谢谢你 这里
  • Spring集成:使用oubound网关处理http错误

    如何处理 http 出站网关中的异常 当我收到状态代码 500 或 400 时 会显示异常 那么我应该如何使用 spring 集成来处理 http 错误 我的配置是这样的
  • 将 JSON 从 ajax 发布到 Struts2 Action

    嘿 我正在尝试将 JSON 从 Ajax 发布到 Struts2 操作类方法 更多信息 我在 WAMP 服务器上运行客户端 在 Eclipse Tomcat 上运行 Struts2 我的客户端代码
  • Vue.js项目中添加Tailwind.css后,某些类没有效果

    我正在尝试将 Tailwind css 添加到 Vue js 项目中 有很多关于如何执行此操作的资源 其中大多数都遵循与这个视频 为了确保我处于与视频中相同的条件 我从头开始创建了一个 Vue 应用程序 使用vue cli使用默认预设 完成
  • 使用脚本在 Powershell 命令提示符中填写多个答案

    我正在尝试使用 Powershell 脚本自动填写提示的答案 提示问题如下所示 这些问题由 cmd 文件一个接一个地生成 这意味着输入不会返回到 Powershell 输入 我找到了很多答案来一次回答一个问题或多个是 否问题 但还没有这样的
  • .NET WebAPI集中授权

    在 NET WebAPI 中 我创建了一种将所有授权规则放在一个中央位置的方法 而不是分散在各个控制器中 我很好奇为什么这种集中化没有更频繁地进行 是否有影响 安全问题 我当前的方法是在 App Start 期间创建一个字典 其中包含我的所
  • 如何在我的应用程序中使用密码锁定场景?

    实际上 我构建了一个包含本地身份验证的应用程序 到目前为止我的代码 func authenticateUser let authenticationContext LAContext var error NSError let reason
  • 类中函数原型中的运算符 & 和 *

    我在这样的课程中遇到问题 class Sprite bool checkCollision Sprite spr 所以 如果我有这门课 我可以这样做 ball checkCollision bar1 但如果我将课程更改为 class Spr
  • 用于解压缩文件的 VBA 脚本 - 只是创建空文件夹

    我正在使用 Ron 的代码 http www rondebruin nl win s7 win002 htm 理论上可以将一堆 zip 文件解压到一个文件夹中 我相信下面的代码获取 下载 目录中的每个 zip 文件 使用 zip 文件的名称
  • 如何用selenium继续填充下一页的数据?

    我想通过以下方式登录Selenium 该过程分为2页 email 密码 现在我可以在第一页输入密钥 然后我应该进入下一页 输入密码并单击提交密钥 但是 如果我只在一个类中添加4个按键代码 则无法完成第二页按键输入 密码和提交 我猜想第一页按
  • 为什么Multiprocessing的Lock不会阻止其他进程使用对象?

    以下代码是一家商店的代码 该商店有 5 件商品 三个顾客各需要一件商品 import multiprocessing as mp class Shop def init self stock 5 self stock stock def g
  • 在映射时使用 adf 管道参数作为源到接收器列

    我有一个具有复制活动的 ADF 管道 我正在将数据从 Blob 存储 CSV 文件复制到 SQL 数据库 这按预期工作 我需要映射 CSV 文件的名称 这来自管道参数 并将其保存在目标表中 我想知道是否有办法将参数映射到目标列 列名不能直接
  • 在自定义控制器工厂中进行通用授权的良好做法?

    我的控制器共享一个客户端 ID 路线 clients clientId controller action id 示例网址 clients 1 orders details 1 clients 2 children index client
  • 通过堆栈进行 32 位扩展乘法

    这是我一直用来实现两个 32 位数字的扩展乘法的代码 有没有办法通过创建子程序并通过参数传递使用堆栈来实现类似的逻辑 使用 MUL 指令还是不使用 MUL 指令 有人可以帮忙吗 org 0x0100 jmp start multiplica
  • 迁移到 androidx 后,膨胀类 androidx.constraintlayout.ConstraintLayout 时出错

    我刚刚通过 Android Studio 菜单选项迁移到 androidxRefactor gt 重构为 AndroidX 我收到以下错误 android view InflateException 二进制 XML 文件行 2 二进制 XM
  • python bokeh,如何制作相关图?

    如何在 Bokeh 中制作相关热图 import pandas as pd import bokeh charts df pd util testing makeTimeDataFrame 1000 c df corr p bokeh ch