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

如何在Matplotlib中叠加两个2D直方图?解决颜色暗淡问题

解决Matplotlib叠加hist2d颜色暗淡的问题

针对你叠加氢原子和氧化铝原子密度图时因设置alpha导致颜色暗淡的问题,推荐以下两种更合适的实现方法:

方法一:使用颜色混合模式替代全局alpha

通过修改第二个hist2d的颜色混合模式,让两种颜色在重叠区域自然混合,同时保持单个颜色的饱和度,避免暗淡。

示例代码

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(4, 4))
# 绘制氧化铝密度热图
al_plot = ax.hist2d(x=alx, y=aly, bins=50, cmap='Reds')
# 绘制氢原子密度热图
h_plot = ax.hist2d(x=hx, y=hy, bins=50, cmap='Blues')

# 修改氢原子热图的颜色混合模式,可选'screen'或'add'
h_plot[3].set_blend_mode('screen')

# 设置标题和坐标轴
ax.set_title('Adsorption over time, {} K'.format(temp))
ax.set_xlabel('picoseconds')
ax.set_ylabel('z-axis')

# 添加两个颜色条,分别对应两种元素的密度
cbar_al = fig.colorbar(al_plot[3], ax=ax, fraction=0.046, pad=0.04, label='Alumina Density')
cbar_h = fig.colorbar(h_plot[3], ax=ax, fraction=0.046, pad=0.04, label='Hydrogen Density')

fig.savefig(savename, dpi=300)

说明

  • screen混合模式会让重叠区域的颜色更明亮(红+蓝会呈现品红色),而不是通过降低透明度让颜色变暗。
  • 同时添加两个颜色条能更清晰地展示两种元素的密度刻度,比单一颜色条更直观。

方法二:自定义带透明通道的颜色映射

如果需要更精细的颜色控制,可以自定义颜色映射,给每种颜色的rgba通道单独设置透明度,既保证颜色饱和度,又能在重叠区域显示混合效果。

示例代码

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

# 自定义红色映射(完全不透明)
red_cmap = LinearSegmentedColormap.from_list('CustomReds', 
    [(1, 1, 1, 0), (1, 0.8, 0.8, 1), (1, 0, 0, 1)], N=256)
# 自定义蓝色映射(完全不透明)
blue_cmap = LinearSegmentedColormap.from_list('CustomBlues', 
    [(1, 1, 1, 0), (0.8, 0.8, 1, 1), (0, 0, 1, 1)], N=256)

fig, ax = plt.subplots(figsize=(4, 4))
ax.hist2d(x=alx, y=aly, bins=50, cmap=red_cmap)
ax.hist2d(x=hx, y=hy, bins=50, cmap=blue_cmap)

ax.set_title('Adsorption over time, {} K'.format(temp))
ax.set_xlabel('picoseconds')
ax.set_ylabel('z-axis')

fig.savefig(savename, dpi=300)

说明

  • 自定义的颜色映射保留了颜色的完全饱和度(alpha=1),仅在颜色渐变的起始点设置透明,确保重叠区域的混合效果自然,同时单个颜色不会暗淡。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:25:16