首页 > 编程笔记

Matplotlib fill_between:面积图

面积图是直线图的一种拓展,在 Matplotlib 库中可以使用 fill_between 方法和 fill_betweenx 方法来绘制面积图。

首先,使用 fill_between 方法绘制垂直方向上的面积图。示例代码如下。
In [1]: import numpy as np
   ...: from matplotlib import pyplot as plt
In [2]: n = 8
   ...: X = np.arange(n)+1
   ...: y1 = np.random.normal(2,1.0,n)
   ...: y2 = [-1]*n
In [3]: plt.fill_between(X,y1,y2)
Out[3]: <matplotlib.collections.PolyCollection at 0x8cf2278> 
结果如图 1 所示。

垂直房方向面积图
图1:垂直方向面积图

接下来,使用 fill_betweenx 方法绘制水平方向上的面积图。示例代码如下。
In [1]: import numpy as np
   ...: from matplotlib import pyplot as plt
In [2]: n = 8
   ...: y = np.arange(n)+1
   ...: x1 = np.random.normal(2,1.0,n)
   ...: x2 = [-1]*n
In [3]: plt.fill_betweenx(y,x1,x2)
Out[3]: <matplotlib.collections.PolyCollection at 0x8f11278>
结果如图 2 所示。

水平方向面积图
图2:水平方向面积图

优秀文章