zhexian5

这类图同常用填色区间表示折线的误差(标准差)区间,或是用于鲜明地表现出两条折线的差异。

绘制填色区间的关键函数为:

1
Axes.fill_between(self, x, y1, y2, where=None, interpolate=False)

主要参数为:

1 x,横坐标

2 y1,y2为两条折线

3 where 条件,比如说将y1小于y2的地方填色,则where=(y1<y2)

4 interpolate 是否进行插值填充(后有示例展示区别)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5, 5, 0.5)
y1 = -5*x*x + x + 10
y2 = 5*x*x + x

fig = plt.figure(figsize=(15,5))

ax1 = fig.add_subplot(1,2,1)
ax1.plot(x, y1, x, y2, color='black')
ax1.fill_between(x, y1, y2, where=(y2 > y1), facecolor='red', alpha=0.5)
ax1.fill_between(x, y1, y2, where=(y2 <= y1), facecolor='blue', alpha=0.5)
ax1.set_title('interpolate = False')

ax2 = fig.add_subplot(1,2,2)
ax2.plot(x, y1, x, y2, color='black')
ax2.fill_between(x, y1, y2, where=(y2 > y1), facecolor='red', alpha=0.5,interpolate=True)
ax2.fill_between(x, y1, y2, where=(y2 <= y1), facecolor='blue', alpha=0.5,interpolate=True)
ax2.set_title('interpolate = True')

plt.show()

输出图形如下:

image-20200702161610554

其中,y1,y2也可以为常值。