### 使用 Matplotlib 实现渐变色效果
Matplotlib 提供了多种方法来创建具有渐变色的效果图表。下面展示几种常见的方式。
#### 方法一:使用 `contourf` 函数绘制热力图
通过设置不同的色彩映射表 (`cmap`) 和调整层次(`levels`) 参数,可以轻松制作出平滑过渡的热力图[^1]。
```python
import numpy as np
import matplotlib.pyplot as plt
# 创建示例数据
x = np.linspace(0, 10, 100)
y = np.linspace(0, 10, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) + np.cos(Y)
# 绘制渐变热力图
plt.figure(figsize=(8,6))
plt.contourf(X, Y, Z, cmap='coolwarm', levels=20)
plt.colorbar(label='Value')
plt.title('Gradient Heatmap Example')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
```
#### 方法二:利用 `LinearSegmentedColormap` 自定义颜色映射
对于更复杂的场景,比如想要指定某些特殊位置上的颜色变化规律,则可以通过构建自己的线性分段颜色条来进行控制[^2]。
```python
from matplotlib.colors import LinearSegmentedColormap
colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] # R -> G -> B
n_bins = 100 # 色彩数量
custom_cmap = LinearSegmentedColormap.from_list(name='custom', colors=colors, N=n_bins)
# 应用于之前的例子中替换默认 colormap
plt.contourf(X, Y, Z, cmap=custom_cmap, levels=20)
plt.colorbar(label='Custom Value')
plt.title('Heatmap with Custom Gradient Color Map')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
```
#### 方法三:为折线添加渐变填充
当处理连续曲线时,还可以考虑给定路径下的区域赋予不同深浅的颜色以增强视觉表现力[^4]。
```python
fig, ax = plt.subplots()
def gradient_fill(x, y, fill_color=None, **kwargs):
"""
Plot line and add a gradient-colored area below it.
Parameters:
x : array-like or scalar
The horizontal coordinates of the data points.
y : array-like or scalar
The vertical coordinates of the data points.
fill_color : str or None
If not None, this specifies the base color used to create gradients;
otherwise default settings will be applied.
kwargs :
Additional arguments passed directly into ``ax.fill_between``
"""
if fill_color is None:
fill_color = next(ax._get_lines.prop_cycler)['color']
zorder = kwargs.pop("zorder", 3)
alpha = kwargs.get('alpha', 1)
npts = len(x)
vertices = list(zip(np.concatenate([x[::-1], x]), \
np.concatenate([np.zeros_like(y)+min(y)-.5*(max(y)-min(y)), y])))
codes = ([Path.MOVETO]+[Path.LINETO]*(len(vertices)-2)+[Path.CLOSEPOLY])
path = Path(vertices, codes=codes)
patch = patches.PathPatch(path, facecolor=fill_color,
edgecolor='none',
alpha=alpha*.75,zorder=zorder-.1,**kwargs)
collection = mcollections.PolyCollection(
[vertices],
closed=True,hatch=None,alpha=.9*zorder/float(max(zorder,npts)),
antialiased=False,**kwargs)
ax.add_patch(patch); ax.add_collection(collection);
t = np.linspace(-2*np.pi, 2*np.pi, 100)
s = np.sin(t)**3 * t**2 / 1e2
gradient_fill(t,s,'blue')
plt.plot(t, s, '-k', lw=2)
plt.xlim([-7, 7]); plt.ylim([-1, 1]);
plt.grid(True);
plt.gca().set_aspect('equal');
plt.title('Line Chart With Gradient Fill Below It')
plt.show();
```