You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Plotly Express绘制分类数据的二维热力图成对图?

生成分类数据的热力图矩阵(支持Streamlit交互)

针对分类数据的成对关联分析需求,以下提供两种可行方案,优先满足Plotly交互式需求,同时补充Seaborn方案作为备选:


方案1:Plotly + Subplots 构建交互式热力图矩阵

Plotly Express无直接生成成对热力图矩阵的API,可通过遍历列对生成子图,再用plotly.subplots组合成矩阵布局,保留交互特性。

代码实现

import pandas as pd
import plotly.express as px
import plotly.subplots as sp
import streamlit as st

# 初始化数据
df = pd.DataFrame({'gender': [1,2,1,1,2,1],
                   'rating': [2,1,1,3,4,5],
                   'speed': [1,5,5,3,2,4],
                   'value':[4,4,3,2,2,1],
                   'appearance':[1,2,3,3,1,1],
                   'will_buy': [2,2,1,5,2,3]})
cols = df.columns.tolist()
n_cols = len(cols)

# 创建子图网格,调整间距避免标签拥挤
fig = sp.make_subplots(
    rows=n_cols, cols=n_cols,
    subplot_titles=[f"{y} vs {x}" for y in cols for x in cols],
    vertical_spacing=0.08,
    horizontal_spacing=0.08
)

# 遍历列对生成热力图/直方图
for i in range(n_cols):
    for j in range(n_cols):
        y_col = cols[i]
        x_col = cols[j]
        if i == j:
            # 对角线用直方图展示单变量分布
            hist_fig = px.histogram(df, x=x_col)
            fig.add_trace(hist_fig.data[0], row=i+1, col=j+1)
            fig.update_yaxes(visible=False, row=i+1, col=j+1)
        else:
            # 非对角线用密度热力图展示观测计数
            heatmap_fig = px.density_heatmap(df, x=x_col, y=y_col, nbinsx=5, nbinsy=5)
            fig.add_trace(heatmap_fig.data[0], row=i+1, col=j+1)

# 统一优化布局与标签
fig.update_layout(
    height=800, width=800,
    title_text="分类数据热力图矩阵",
    showlegend=False
)

# 仅保留最外层坐标轴标签,避免重复拥挤
for i in range(n_cols):
    fig.update_xaxes(title_text=cols[i], row=n_cols, col=i+1)
    fig.update_yaxes(title_text=cols[i], row=i+1, col=1)

# 在Streamlit中展示
st.plotly_chart(fig, theme=None)

核心特性

  • 对角线展示单变量分布,非对角线展示列对观测计数
  • 支持悬停查看具体数值、缩放等交互操作
  • 自定义间距解决标签拥挤问题

方案2:Seaborn PairGrid 生成热力图矩阵

若接受非交互式方案,可通过Seaborn的PairGrid自定义热力图,直观展示分类变量间的计数关联。

代码实现

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import streamlit as st

# 初始化数据
df = pd.DataFrame({'gender': [1,2,1,1,2,1],
                   'rating': [2,1,1,3,4,5],
                   'speed': [1,5,5,3,2,4],
                   'value':[4,4,3,2,2,1],
                   'appearance':[1,2,3,3,1,1],
                   'will_buy': [2,2,1,5,2,3]})

# 创建PairGrid框架
g = sns.PairGrid(df)

# 对角线子图:绘制直方图
g.map_diag(sns.histplot)

# 非对角线子图:绘制计数热力图
def plot_count_heatmap(x, y, **kwargs):
    cross_tab = pd.crosstab(x, y)
    sns.heatmap(cross_tab, annot=True, fmt='d', cmap='Blues', **kwargs)

g.map_offdiag(plot_count_heatmap)

# 调整布局避免标签重叠
plt.subplots_adjust(hspace=0.2, wspace=0.2)

# 在Streamlit中展示
st.pyplot(g.fig)

核心特性

  • 热力图直接标注观测计数,清晰展示变量间关联
  • 布局简洁,适合快速分析分类数据规律

内容的提问来源于stack exchange,提问作者user173729

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:23:12