python热力图颜色大全
时间: 2025-05-21 09:00:22 浏览: 16
### Python 绘制热力图时可用的颜色方案
在使用 `matplotlib` 和 `seaborn` 库绘制热力图时,有许多内置的颜色映射(colormap)可供选择。这些颜色映射可以根据具体需求调整热力图的视觉效果。
#### 使用 Seaborn 的预定义调色板
Seaborn 提供了一系列美观且实用的颜色调色板,可以直接应用于热力图中:
```python
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# 构造随机数据用于展示
data = np.random.rand(10, 12)
plt.figure(figsize=(10, 8))
sns.heatmap(data, cmap="coolwarm") # 使用 coolwarm 调色板
plt.title('Heatmap with Cool Warm Color Map')
plt.show()
```
此代码片段展示了如何利用 `"coolwarm"` 这样的预设调色板来创建热力图[^1]。
#### Matplotlib 中的颜色映射表
除了 Seaborn 自带的选择外,还可以通过 Matplotlib 访问更多种类的颜色映射表。以下是部分常用的 colormap 列表及其描述:
| Colormap Name | Description |
|---------------|-------------|
| viridis | A perceptually uniform sequential colormap that is good for many applications and colorblind-friendly. |
| plasma | Another perceptually uniform sequential colormap which provides high contrast across the entire range of values. |
| inferno | Similar to 'plasma', but starts from black instead of dark blue at low intensities. |
| magma | Like 'inferno' but slightly less saturated towards higher intensity levels. |
| cividis | Designed specifically to be accessible by people who are red-green or blue-yellow color blind while still being aesthetically pleasing. |
要查看完整的色彩列表并测试不同选项的效果,可执行如下脚本:
```python
from matplotlib.colors import ListedColormap
all_colormaps = ['viridis', 'plasma', 'inferno', 'magma', 'cividis']
fig, axes = plt.subplots(nrows=1, ncols=len(all_colormaps), figsize=(15, 3))
for ax, name in zip(axes.flatten(), all_colormaps):
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
ax.set_title(f'{name} colormap')
plt.tight_layout()
plt.show()
```
这段代码会生成一系列子图,每个子图对应一种不同的 colormap,并直观地显示出其渐变特性[^2]。
#### 定义自定义颜色映射
如果默认提供的 colormap 不满足特定应用场景下的需求,则可以通过组合多种基础颜色来自定义新的 colormap:
```python
custom_colors = ["white", "lightblue", "#add8e6", "darkblue"]
my_custom_cmap = ListedColormap(custom_colors)
plt.figure(figsize=(10, 7))
sns.heatmap(data, annot=True, fmt=".1f", linewidths=.5, square=True, cbar_kws={"shrink": .5}, cmap=my_custom_cmap)
plt.title('Custom Heatmap Colorscheme Example')
plt.show()
```
上述例子说明了怎样基于给定的颜色序列构建个性化 colormap 并应用到实际绘图当中[^3]。
阅读全文
相关推荐


















