【问题标题】:Clicking `seaborn` heatmap to print metadata from that cell单击“seaborn”热图以从该单元格打印元数据
【发布时间】:2022-01-05 00:14:50
【问题描述】:

我已经弄清楚如何打印matplotlib 散点图并根据单击点的元数据单击这些点以提供其他数据的图表。我现在想将类似的想法应用于seaborn 热图。问题是我用于matplotlib 图的逻辑似乎是散点图所独有的。以here 为特色并写在下面的循环不适用于热图。

import matplotlib.pyplot as plt

class custom_objects_to_plot:
    def __init__(self, x, y, name):
        self.x = x
        self.y = y
        self.name = name

a = custom_objects_to_plot(10, 20, "a")
b = custom_objects_to_plot(30, 5, "b")
c = custom_objects_to_plot(40, 30, "c")
d = custom_objects_to_plot(120, 10, "d")

def on_pick(event):
    print(event.artist.obj.name)

fig, ax = plt.subplots()
for obj in [a, b, c, d]:
    artist = ax.plot(obj.x, obj.y, 'ro', picker=5)[0]
    artist.obj = obj

fig.canvas.callbacks.connect('pick_event', on_pick)

plt.show()

为了更详细一点,我有五个主题,每个主题都根据十个参数对某事进行评分,总共有 50 个评分。我的数据框中除了“主题”、“参数”和“评级”列之外,还有一个用于 cmets 的列。当我单击热图时,我希望这些 cmets 打印出来,该热图具有沿水平轴的主题和沿垂直轴的参数。

似乎我应该能够使用热图中的位置来识别主题-参数组合并查找该主题对于该参数有哪些 cmets,但是从单击的单元格中提取主题和参数让我望而却步,并且带有custom_objects_to_plot 的参考代码似乎不适用于热图。虽然我对如何执行此任务有自己的想法,但如果我能从单击的单元格中获取主题和参数,我欢迎使用不同方法但仍然给我一个可单击的seaborn 热图的答案。

【问题讨论】:

    标签: python graphics onclick seaborn heatmap


    【解决方案1】:

    您可以尝试mplcursors,并使用虚拟图像(因为不支持由sns.heatmap 创建的QuadMesh)。使用hover=True,信息在悬停时显示在注释框中。使用hover=False(默认),这只会在单击时发生。如果你只是想打印一些东西,你可以设置sel.annotation.set_visible(False)并打印一些东西(或更新状态栏)。

    这是一个例子:

    import matplotlib.pyplot as plt
    import mplcursors
    import seaborn as sns
    import pandas as pd
    import numpy as np
    
    def show_annotation(sel):
        x = int(sel.target[0])
        y = int(sel.target[1])
        sel.annotation.set_text(f's:{subjects[y]} p:{parameters[x]} r:{df_rating.iloc[y, x]}\n'
                                f'{df_comment.iloc[y, x]}')
        sel.annotation.get_bbox_patch().set(alpha=0.9)
    
    subjects = np.arange(1, 6)
    parameters = [*'ABCDEFGHIJ']
    df = pd.DataFrame({'subject': np.repeat(subjects, len(parameters)),
                       'parameter': np.tile(parameters, len(subjects)),
                       'rating': np.random.randint(1, 11, len(subjects) * len(parameters)),
                       'comment': [f'comment subj {i} param {j}' for i in subjects for j in parameters]})
    df_rating = df.pivot('subject', 'parameter', 'rating')
    df_comment = df.pivot('subject', 'parameter', 'comment')
    sns.set_style('white')
    ax = sns.heatmap(df_rating, annot=True, lw=2)
    dummy_image = ax.imshow(df_rating.to_numpy(), zorder=-1, aspect='auto')
    cursor = mplcursors.cursor(dummy_image, hover=True)
    cursor.connect('add', show_annotation)
    plt.show()
    
    

    【讨论】:

    • 太棒了!当我将它与我的真实热图集成时,我想确保它能够正常工作,其中有一些我没有在这里包含的复杂性,但我认为它会。
    • 我没有mplcursors 也没有安装它的权限,但是这个答案在我可以测试的范围内有效,所以+15。
    • mplcursors 只是一个single file。不用安装,直接下载即可。
    猜你喜欢
    • 2017-10-31
    • 2019-05-12
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    相关资源
    最近更新 更多