如何在单张图表中绘制多组1D分布热力图条形?
多个直方图转1D热力图“条形”实现方案
以下是针对需求的两种实现方式,可得到类似1D热力图条形的效果:
现有问题说明
你当前使用的seaborn.heatmap默认是网格状布局,要实现“条形”视觉效果,需要调整参数或换用其他绘制逻辑。
方案1:调整Heatmap参数实现条形化
通过修改热力图的布局、边框、尺寸等参数,让每行的色块更接近条形:
import numpy as np import seaborn as sns import matplotlib.pyplot as plt # 原始数据 foo = np.array([0, 2, 3, 1, 0]) bar = np.array([0, 0, 2, 1, 0]) baz = np.array([0, 1, 1, 0, 0]) bin_labels = ['0.0-0.2', '0.2-0.4', '0.4-0.6', '0.6-0.8', '0.8-1.0'] combined_data = np.vstack((foo, bar, baz)) # 设置画布尺寸,让每行更宽 plt.figure(figsize=(8, 3)) ax = sns.heatmap( combined_data, cmap='Blues', fmt='d', xticklabels=bin_labels, yticklabels=["foo", "bar", "baz"], cbar=True, linewidths=0, # 移除色块间的分隔线 annot=True, # 可选:显示每个色块的数值 cbar_kws={"orientation": "horizontal", "pad": 0.15} # 色条横向放置在底部 ) # 调整标签和布局 plt.xlabel('Bin Ranges') plt.ylabel('Type') plt.title('1D Heatmap Bars') ax.set_yticklabels(ax.get_yticklabels(), va='center') # y轴标签居中对齐 plt.tight_layout() plt.show()
方案2:用Barplot模拟热力条形
如果想要更贴近“条形”的视觉形态,可以固定条形高度,用颜色映射表示数值大小:
import numpy as np import seaborn as sns import matplotlib.pyplot as plt from matplotlib.colors import Normalize # 原始数据 foo = np.array([0, 2, 3, 1, 0]) bar = np.array([0, 0, 2, 1, 0]) baz = np.array([0, 1, 1, 0, 0]) bin_labels = ['0.0-0.2', '0.2-0.4', '0.4-0.6', '0.6-0.8', '0.8-1.0'] combined_data = np.vstack((foo, bar, baz)) types = ["foo", "bar", "baz"] fig, ax = plt.subplots(figsize=(8, 3)) # 定义颜色映射的归一化范围 norm = Normalize(vmin=combined_data.min(), vmax=combined_data.max()) cmap = plt.get_cmap('Blues') y_pos = np.arange(len(types)) bin_width = 1 / len(bin_labels) # 每个bin的条形宽度 # 遍历每个类型和bin,绘制彩色条形 for i, typ in enumerate(types): for j, val in enumerate(combined_data[i]): ax.bar( y_pos[i] + j * bin_width, 1, # 固定条形高度为1 width=bin_width, color=cmap(norm(val)) ) # 设置坐标轴刻度和标签 ax.set_yticks(y_pos + bin_width * (len(bin_labels)-1)/2) ax.set_yticklabels(types) ax.set_xticks(y_pos + bin_width * (len(bin_labels)-1)/2) ax.set_xticklabels(bin_labels) plt.xlabel('Bin Ranges') plt.ylabel('Type') plt.title('Heatmap-style Bars') # 添加颜色条 sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) sm.set_array([]) plt.colorbar(sm, orientation='horizontal', pad=0.15, label='Count') plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Darrell Revis
相关产品推荐
相关产品推荐

