相关矩阵热图 - 使用图例切换可见项目

Correlation Matrix Heatmap - use legend to toggle visible items

我正在使用 Plotly 创建反映相关矩阵的热图。我想知道是否可以使用图例切换图中显示的项目。

例如,下面创建了一个 10x10 矩阵和相应的热图。我的目标是能够 select 情节本身中只有“A”、“B”和“C”,并且它正确显示仅包含这些项目的 3x3 热图。

import plotly.offline as pyo
import plotly.express as px
import plotly.graph_objs as go
import numpy as np
import pandas as pd

arr = np.random.rand(10,10)
np.fill_diagonal(arr,np.nan)

corr = pd.DataFrame(arr)
corr.columns = ['A','B','C','D','E','F','G','H','I','J']
corr.index = ['A','B','C','D','E','F','G','H','I','J']

trace = go.Heatmap(z=corr.values,x=corr.index.values,y=corr.columns.values,colorscale='RdBu_r',
                   zmax=1,zmin=-1,text=corr.values)
fig = go.Figure(data=[trace])
pyo.plot(fig)

也可以使用 plotly express imshow 根据以下内容创建绘图

fig = px.imshow(corr.values, text_auto='.2f',
                zmin=-1, zmax=1,
                color_continuous_scale='RdBu_r',aspect="auto",
                labels=dict(color="Correlation"),
                x=corr.index.values,
                y=corr.columns.values)
pyo.plot(fig)

对于可视化,我希望从这里开始;

到此;

使用图例(或等同物)

通过图例进行控制的一种方法是为您想要的每个键组合创建轨迹

  • 限于 powerset
  • 的子集
  • 对于其他组合,仅设置为 图例
import plotly.offline as pyo
import plotly.express as px
import plotly.graph_objs as go
import numpy as np
import pandas as pd
import more_itertools

arr = np.random.rand(10, 10)
np.fill_diagonal(arr, np.nan)

corr = pd.DataFrame(arr)
corr.columns = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
corr.index = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]

fig = px.imshow(
    corr.values,
    text_auto=".2f",
    zmin=-1,
    zmax=1,
    color_continuous_scale="RdBu_r",
    aspect="auto",
    labels=dict(color="Correlation"),
    x=corr.index.values,
    y=corr.columns.values,
)

fig.update_traces(name="All", showlegend=True)

ps = [c for c in more_itertools.powerset(corr.columns) if len(c) == 3]

for c in ps:
    fig.add_traces(
        px.imshow(
            corr.loc[list(c), list(c)].values,
            x=list(c),
            y=list(c),
            color_continuous_scale="RdBu_r",
            text_auto=".2f",
        )
        .update_traces(name=str(c), showlegend=True, visible="legendonly")
        .data
    )

fig.update_layout(coloraxis_colorbar_x=-0.2)