如何在Matplotlib子图中制作透明直方图?解决颜色与图例问题
问题解决方案
1. 修复颜色显示与透明度问题
你当前代码中给直方图传入cmap=cmap会导致所有模型的直方图使用整个viridis色阶,叠加后颜色混为紫色。正确的做法是给每个模型分配单一带透明度的颜色,而非整个色阶:
修改后的完整代码
import matplotlib.pyplot as plt import numpy as np from matplotlib import colors as mcolors def add_alpha_to_colormap(cmap, alpha): cmap = plt.cm.get_cmap(cmap) colors = cmap(np.arange(cmap.N)) RGBA = np.hstack([colors[:, :3], np.full((cmap.N, 1), alpha)]) new_cmap = mcolors.ListedColormap(RGBA) return new_cmap # 主绘图逻辑 num_bins = 20 fig, axes = plt.subplots(figsize=(18, 14), dpi=120, nrows=2, ncols=4) cmap = add_alpha_to_colormap('viridis', alpha=0.5) models = list(set(df.index)) # 为每个模型分配独一的带透明度颜色 model_colors = cmap(np.linspace(0, 1, len(models))) for idx, model in enumerate(models): color = model_colors[idx] # 逐个绘制指标直方图,指定单一颜色和标签 df.loc[model]['rouge1_recall'].plot.hist(color=color, bins=num_bins, title='Rouge1 recall', ax=axes[0, 0], label=model) df.loc[model]['rouge1_precision'].plot.hist(color=color, bins=num_bins, title='Rouge1 precision', ax=axes[1, 0], label=model) df.loc[model]['rouge2_recall'].plot.hist(color=color, bins=num_bins, title='Rouge2 recall', ax=axes[0, 1], label=model) df.loc[model]['rouge2_precision'].plot.hist(color=color, bins=num_bins, title='Rouge2 precision', ax=axes[1, 1], label=model) df.loc[model]['bert_recall'].plot.hist(color=color, bins=num_bins, title='BertScore recall', ax=axes[0, 2], label=model) df.loc[model]['bert_precision'].plot.hist(color=color, bins=num_bins, title='BertScore precision', ax=axes[1, 2], label=model) df.loc[model]['bleu'].plot.hist(color=color, bins=num_bins, title='Bleu', ax=axes[0, 3], label=model) # 为每个子图添加图例 for ax in axes.flat: ax.legend(loc='upper right', bbox_to_anchor=(1.1, 1)) plt.tight_layout() plt.show()
关键修改说明
- 替换
cmap=cmap为color=color:cmap参数用于数值到颜色的映射,单系列直方图应使用color指定单一颜色 - 预先生成与模型数量匹配的颜色列表,确保每个模型颜色唯一且保留透明度
- 修正了原代码中
bert_precision子图的标题错误(重复写了recall)
2. 图例添加逻辑
- 每次调用
plot.hist时传入label=model,为每个模型的直方图标记名称 - 遍历所有子图调用
ax.legend()生成图例,通过loc和bbox_to_anchor调整图例位置,避免遮挡直方图内容
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

